43

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?

nakiya
  • 14,063
  • 21
  • 79
  • 118

1 Answers1

36

You want either lower_bound, upper_bound, or equal_range.

CTT
  • 16,901
  • 6
  • 41
  • 37
  • I'm curious if ```std::lower_bound``` can find occurrences from right to left? such as ```std::find (container.rbegin(), container.end(), target);``` – Ionut Alexandru Apr 22 '22 at 09: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 '22 at 22:42