简体   繁体   中英

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?

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"] . All the examples that I've seen in the boost documentation iterate over the whole structure.

This implementation should work, but there might be a more elegant one, or even a function in icl, which does exactly that. I recommend studying the documentation.

Most functions in icl provide access by the key type, which is the interval. You would like to query for a point, which can be represented by a closed interval [N,N]. lower_bound seems like the the obvious choice followed by a check that this interval is not "above/greater" your query point.

#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;    
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM