如何在 std::map 中找到指定范围内的元素?
How to find an element in a specified range in std::map?
除了std::map
之外,是否有std::find(first, last)
的等效版本? 也就是说,是否有一个版本的std::map
find
方法在map
中搜索元素,但将搜索限制在指定的[first, last)
范围内?理想情况下,解决方案应该是大小为[first, last)
的对数。
据我所知,std::map::find
本身不支持此功能(它总是搜索整个地图)。
您可以使用std::lower_bound
、std::upper_bound
或std::equal_range
,因为映射中的迭代器和数据std::map
满足这些函数的要求,尽管您应该知道,由于线性迭代器增量,它的效率将低于std::map::find()
。
从std::lower_bound
文档
执行的比较次数在第一个和最后一个之间的距离上是对数的(最多对数 2(最后一个 - 第一个)+ O(1) 比较)。但是,对于非 LegacyRandomAccessIterators,迭代器增量的数量是线性的。
重点是我的。
如果我正确理解了这个问题,std::map::lower_bound
正是您要找的 - 它为您提供了不少于键的元素。另一端也有upper_bound
。
相关文章:
- 为什么在全局范围内使用"extern int a"似乎不行?
- 错误:未在此范围内声明'reverse'
- 使用std::transform将一个范围的元素添加到另一个范围中
- 并行用于C++17中数组索引范围内的循环
- 对于多个查询,查找在 l 到 r 范围内具有相同元素的最长公共子数组
- 我应该如何使用remove_if删除两个数字范围内的元素
- 从给定范围内的向量中查找最大元素
- 矢量擦除范围内的元素
- 如何擦除矢量中的所有元素,但特定范围内最大的元素除外
- 如何在 std::map 中找到指定范围内的元素?
- 如果地图擦除范围内的第一个和最后一个相等,则是否删除该元素
- 如何在向量的给定索引范围内查找最小元素
- C++中数组范围内的有效元素计数
- 查找范围内元素数量的最快方法
- 元素在给定范围内的子矩阵中唯一元素的数目
- 替换排序范围内的元素
- 从矢量范围内删除特定元素
- 如何在C++中检查一个集合是否有某个范围内的元素
- 当C++试图访问向量的元素(在范围内)时,Qt Quick Windows应用程序崩溃
- 查找矢量中位于指定范围内的元素