c++stdmap

Find the nearest Keys that exists in the range boundary `[x,y]` in std::map in C++


I need to find the nearest keys in my map in a given range [x,y]. I am trying below

std::map<int, char> m{ {-2,'B'}, {1, 'C'},  {2, 'A'}};

auto itCurrent = m.lower_bound(-3);
auto itNext = m.upper_bound(-3);

auto it1 = m.lower_bound(3);
auto it2 = m.upper_bound(3);

I was hoping to get iterators that point to -2 and 2 by using lower_bound and uppper_bound around the enquiry boundary keys [-3,3]. it1 and it2 are returning end while itCurrent and itNext return iterator to key -2.

How do I get iterators to -2 and 2 as result?


Solution

  • If I understand the question correctly, you have a map m and two keys x and y, and you want the first element of m not less than x and the last element of m not greater than y.

    The first is exactly what lower_bound gives you. That's itCurrent in your example. The second, you can easily get with lower_bound and std::advance.

    auto inverse_lower_bound(auto const& map, auto const& key) {
        auto it = map.lower_bound(key);
        if (it == map.end() && !map.empty()) {
            std::advance(it, -1);
        }
        return it;
    }
    

    Demo