rationale for std::lower_bound and std::upper_bound?

后端 未结 10 1524
傲寒
傲寒 2021-01-30 08:13

STL provides binary search functions std::lower_bound and std::upper_bound, but I tend not to use them because I\'ve been unable to remember what they do, because their contract

10条回答
  •  闹比i
    闹比i (楼主)
    2021-01-30 08:59

    If you have multiple elements in the range [first, last) whose value equals the value val you are searching for, then the range [l, u) where

    l = std::lower_bound(first, last, val)
    u = std::upper_bound(first, last, val)
    

    is precisely the range of elements equal to val within the range [first, last). So l and u are the "lower bound" and "upper bound" for the equal range. It makes sense if you're accustomed to thinking in terms of half-open intervals.

    (Note that std::equal_range will return both the lower and upper bound in a pair, in a single call.)

提交回复
热议问题