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

  • A+
Category:Languages

Is there an equivalent version of std::find(first, last) but for a std::map? I.e., 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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: