如何在std::map中查找指定范围内的元素?

How to find an element in a specified range in std::map?

是否有 std::find(first, last) 除了 std::map 的等效版本?即,是否有 std::mapfind 方法的版本可以搜索 map 中的元素,但将搜索限制在指定的 [first, last) 范围内?理想情况下,解决方案的大小应为 [first, last).

的对数

what I've seen开始,std::map::find本身不支持此功能(它总是搜索整个地图)。

您可以使用 std::lower_boundstd::upper_boundstd::equal_range 作为 std::map 地图中的迭代器和数据满足这些功能的要求,尽管您应该意识到由于线性迭代器增量,它的效率将低于 std::map::find()

来自 std::lower_bound documentation

The number of comparisons performed is logarithmic in the distance between first and last (At most log 2(last - first) + O(1) comparisons). However, for non-LegacyRandomAccessIterators, the number of iterator increments is linear.

重点是我的。

如果我对问题的理解正确,std::map::lower_bound 正是您要查找的内容 - 它为您提供了不小于键的元素。另一端也有 upper_bound