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

后端 未结 10 1535
傲寒
傲寒 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条回答
  •  遇见更好的自我
    2021-01-30 08:45

    Yes. The question absolutely has a point. When someone gave these functions their names they were thinking only of sorted arrays with repeating elements. If you have an array with unique elements, "std::lower_bound()" acts more like a search for an "upper bound" unless it finds the actual element.

    So this is what I remember about these functions:

    • If you are doing a binary search, consider using std::lower_bound(), and read the manual. std::binary_search() is based on it, too.
    • If you want to find the "place" of a value in a sorted array of unique values, consider std::lower_bound() and read the manual.
    • If you have an arbitrary task of searching in a sorted array, read the manual for both std::lower_bound() and std::upper_bound().

    Failing to read the manual after a month or two since you last used these functions, almost certainly leads to a bug.

提交回复
热议问题