C ++地图中java`TreeMap.lowerEntry`和`TreeMap.higherEntry`的等价物?

时间:2015-11-03 07:40:51

标签: java c++

我认为C++ std :: map.lower_bound等于java' s TreeMap.higherEntryTreeMap.lowerEntry std :: map中java C++的等价物是什么?

1 个答案:

答案 0 :(得分:1)

两个C ++函数的返回值都是双向迭代器。所以,你可以这样做:

lowerEntry = --mymap.lower_bound(mykey);

当然,只有mymap.lower_bound(mykey) != mymap.begin()才能执行此操作。

请注意,使用lower_bound而不是upper_bound至关重要。如果您使用upper_bound,则可能会或可能不会使用密钥等于mykey的货币对。

包含在一个函数中:

template < typename Key, typename Value, typename Compare, typename Alloc >
auto lowerEntry(std::map<Key, Value, Compare, Alloc> map, Key key) -> decltype(map.begin()) {
    auto iter = map.lower_bound(key); // find the first element to go at or after key
    if(iter == map.begin()) // all elements go after key
        return map.end(); // signals that no lowerEntry could be found
    return --iter; // pre-decrement to return an iterator to the element before iter
}

不要介意所有的模板内容 - 这很尴尬。

尾随返回类型(-> decltype(...))只是为了使函数头更具可读性。如果您无法访问C ++ 11(为什么不能使用?!),请将其用作标题:

typename std::map<Key, Value, Compare, Alloc>::iterator lowerEntry(std::map<Key, Value, Compare, Alloc> map, Key key) {

这是指向Wandbox上的代码段的链接(允许您在多个编译器中运行它):http://melpon.org/wandbox/permlink/slFyTXHgFzWiZEIL