muxecoid's blog

By muxecoid, 9 years ago, In English

Just something curious that I just noticed during practice.

std::map::upper_bound returns iterator to the first element with key strictly greater, than argument.

By intuition of symmetry one could expect std::map::lower_bound to return iterator to the last element with key strictly less, than argument. In fact it returns iterator exactly one after it.

What is the reason for this asymmetry? This is because map::end() points at one position after the last element, if we search for element greater than largest key in map upper_bound has a reasonable iterator to return map::end. map::begin() points at first element. To provide API symmetry lower_bound would need to return map::prebegin() which does not exist in standard. This way asymmetry between begin() and end() leads to asymmetry between lower_bound() and upper_bound().

What other cases of asymmetry are there in STL?

Tags c++, stl
  • Vote: I like it
  • -16
  • Vote: I do not like it

»
9 years ago, # |
  Vote: I like it +35 Vote: I do not like it

Look at this the following way: map::equal_range (range of equal elements) is [map::lower_bound, map::upper_bound).