[英]How to get values from interval_maps for given key?
I'm using boost::icl::interval_maps
with int interval
s and I was wondering how can I get the values for int (key) that belongs to some interval?我正在使用
boost::icl::interval_maps
和 int interval
s,我想知道如何获取属于某个间隔的 int (key) 的值?
For example if we have a interval map that has the following structure例如,如果我们有一个具有以下结构的区间图
[0, 5): ["A1", "A2"],
[5, 10): ["A2"]
and I use the key 4
I would like to get ["A1", "A2"]
.我使用我想要获得的密钥
4
["A1", "A2"]
。 All the examples that I've seen in the boost documentation iterate over the whole structure.我在 boost 文档中看到的所有示例都遍历整个结构。
This implementation should work, but there might be a more elegant one, or even a function in icl, which does exactly that.这个实现应该可以工作,但可能有一个更优雅的实现,或者甚至是 icl 中的一个函数,它正是这样做的。 I recommend studying the documentation.
我建议研究文档。
Most functions in icl provide access by the key type, which is the interval. icl 中的大多数函数都提供按密钥类型(即间隔)的访问。 You would like to query for a point, which can be represented by a closed interval [N,N].
您想查询一个点,它可以用闭区间 [N,N] 表示。 lower_bound seems like the the obvious choice followed by a check that this interval is not "above/greater" your query point.
lower_bound 似乎是显而易见的选择,然后检查此间隔是否“高于/大于”您的查询点。
#include <iostream>
#include <boost/optional.hpp>
#include <boost/icl/interval_map.hpp>
#include <boost/icl/interval.hpp>
using namespace boost::icl;
template<typename Key, typename Value>
boost::optional<Value> query(const interval_map<Key,Value>& map, Key key)
{
auto kvp = map.lower_bound(interval<int>::closed(key, key));
if(kvp != map.end() && contains(kvp->first, key))
return kvp->second;
else
return boost::none;
}
int main()
{
interval_map<int,std::string> map;
map += std::make_pair(interval<int>::right_open(1,5), std::string("A"));
map += std::make_pair(interval<int>::right_open(2,3), std::string("B"));
map += std::make_pair(interval<int>::right_open(1,3), std::string("C"));
map += std::make_pair(interval<int>::right_open(5,6), std::string("D"));
auto value = query(map, 2);
if(value)
std::cout << *value;
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.