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

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

本文关键字:范围内 元素 std map      更新时间:2023-10-16

除了std::map之外,是否有std::find(first, last)的等效版本? 也就是说,是否有一个版本的std::mapfind方法在map中搜索元素,但将搜索限制在指定的[first, last)范围内?理想情况下,解决方案应该是大小为[first, last)的对数。

据我所知,std::map::find本身不支持此功能(它总是搜索整个地图)。

您可以使用std::lower_boundstd::upper_boundstd::equal_range,因为映射中的迭代器和数据std::map满足这些函数的要求,尽管您应该知道,由于线性迭代器增量,它的效率将低于std::map::find()

std::lower_bound文档

执行的比较次数在第一个和最后一个之间的距离上是对数的(最多对数 2(最后一个 - 第一个)+ O(1) 比较)。但是,对于非 LegacyRandomAccessIterators,迭代器增量的数量是线性的

重点是我的。

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