45

I want to get the iterator for the element I'm testing for in binary-search. But it only returns a bool indicating whether it found the value or not. How to get the iterator?

0

1 Answer 1

38

You want either lower_bound, upper_bound, or equal_range.

2
  • I'm curious if std::lower_bound can find occurrences from right to left? such as std::find (container.rbegin(), container.end(), target); Apr 22, 2022 at 9:34
  • @IonutAlexandru You shouldn't pair rbegin with end, you should use rbegin and rend. You also need to be really careful--in general, reversing a sorted container doesn't result in a sorted container unless you invert the less-than operator as well, which means your lower_bound will need a custom comparison function.
    – AHelps
    Sep 28, 2022 at 22:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.