开发者

Is there a widely available C++ version of Java's NavigableMap interface?

开发者 https://www.devze.com 2023-02-19 12:20 出处:网络
In Java, you can have a NavigableMap, which lets you do useful things such as \"find the greatest key less than or equal to the given value\" (fl开发者_如何学运维oorKey method).So if myMap contains {1

In Java, you can have a NavigableMap, which lets you do useful things such as "find the greatest key less than or equal to the given value" (fl开发者_如何学运维oorKey method). So if myMap contains {1->"One", 2->"Two", 3->"Three", 7->"Seven"}, you can call myMap.floorKey(6) and it will return the key of 3.

In C++, STL provides a map class, which by default sorts entries according to ascending key value order. This is great, but how can I do something similar to floorKey in C++? All the references I've found so far suggest you have to do it manually (i.e. define an iterator, converge on the key - preferably using binary search, then find the next lower key). Is there a widely-available library function available to do this?


The simplest way to get this in C++ would be to call map::upper_bound and decrement the returned iterator:

#include <map>
#include <string>
#include <iostream>
int main()
{
        std::map<int, std::string> myMap =
               {{ 1, "One"},
                {2, "Two"},
                {3, "Three"},
                {7, "Seven"}};

        auto i = myMap.upper_bound(6);
        std::cout << (--i)->first << '\n';
}

but beware of corner cases (if upper_bound returned begin(), or the map is empty, etc)

test run: https://ideone.com/TP3DL


Use a priority queue. Is there a reason you must use a map?

0

精彩评论

暂无评论...
验证码 换一张
取 消