Is there an equivalent version of std::find(first, last)
but for a std::map
? Ie, is there a version of std::map
's find
method that searches for an element in a map
, but restricting the search only to a specified [first, last)
range? Ideally, the solution should be logarithmic in the size of [first, last)
.
From what I've seen , std::map::find
itself doesn't support this functionality (it always searches the whole map).
You can use std::lower_bound
, std::upper_bound
or std::equal_range
for that as std::map
iterators and data in the map satisfy the requirement for those functions, though you should be aware that it will be less efficient than std::map::find()
due to linear iterator increments.
From 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 .
emphasis is mine.
If I understood the question correctly, std::map::lower_bound
is exactly what you are looking for - it gives you the element which is not less than the key. And there is upper_bound
as well for the other end.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.