1 / 3
Sep 2009

what is the easiest way (shortest code, fastest) to find largest element smaller than x in std::map (handling all cases - especially when map is empty) ?

  • created

    Sep '09
  • last reply

    Sep '09
  • 2

    replies

  • 339

    views

  • 2

    users

  • 1

    link

Are you sure you shouldn't be using std::set instead?
Anyway, std::map::lower_bound() returns an iterator to the smallest element which is greater than or equal to x.
If you decrement this iterator, you should get an iterator to the largest element smaller than x, as desired.
You just have to watch out for one special case: if lower_bound() returns an iterator to the beginning of the map, then there does not exist an element satisfying your description. Make sure you handle that properly, because decrementing the begin() iterator yields undefined behavior.

Suggested Topics

Topic Category Replies Views Activity
C and C++ 0 13 6d

Want to read more? Browse other topics in C and C++ or view latest topics.