c++ - 在 C++ Map 中返回严格小于给定键的最大键

标签 c++ stl

C++ STL Maps 有没有办法支持这一点,因为 map 上的 lower_bound 和 upper_bound 严格返回大于传递值的值。

Lower key

用例我有一个以时间为键的 map ,所以在 map 中

time t1   = value1
time t2   = value2
time t2.5 = value3

在这种情况下,如果我传递给这个 MAP t2.3,那么它应该给我 value2。是否在 map 上做一个 lower_bound 并返回一个等同于“返回最大键严格小于给定键”的元素,即

iterator = map.upper_bound(2.3)
and then 
iterator--;

最佳答案

是的,lower_bound 可以用来做这个,我以前见过它,并且是这样使用的。

map_type::iterator it = map.lower_bound(2.3);
if(it != map.begin()) {
    --it;
    // it now points at the right element
}

实际上会返回最大但更小的(如果 != map.begin() 为真)一个。如果它位于 .begin,则没有更小的键。评论中的好主意是返回 .end 如果没有更少的元素并将这些东西打包到一个函数中:

template<typename Map> typename Map::const_iterator 
greatest_less(Map const& m, typename Map::key_type const& k) {
    typename Map::const_iterator it = m.lower_bound(k);
    if(it != m.begin()) {
        return --it;
    }
    return m.end();
}

template<typename Map> typename Map::iterator 
greatest_less(Map & m, typename Map::key_type const& k) {
    typename Map::iterator it = m.lower_bound(k);
    if(it != m.begin()) {
        return --it;
    }
    return m.end();
}

模板也应该适用于 std::set

关于c++ - 在 C++ Map 中返回严格小于给定键的最大键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/529831/

相关文章:

c++ - 如何查询二进制文件的源代码版本

c++ - 对特定 `QObject::Signal()` 调用的disconnect()会自动断开lambda吗?

c++ - 在使用 QtCreator 和 Visual Studio 构建的应用程序之间使用 Qt STL

c++ - Std::vector 被初始化为垃圾。奇怪的行为。有什么想法吗?

c++ - 访问 std::pair 数组的元素时出错

c++ - 实现 IDropTarget

c++ - 在 C++ 中填充二维 vector

c++ - 使用 STL vector 作为字节数据的 FIFO 容器

c++ - 如果 T 是 POD,std::array<T, S> 是否保证是 POD?

c++ - 将一个迭代器的值赋给另一个迭代器 C++