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

后端 未结 10 1722
傲寒
傲寒 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:57

    Both functions are very similar, in that they will find an insertion point in a sorted sequence that will preserve the sort. If there are no existing elements in the sequence that are equal to the search item, they will return the same iterator.

    If you're trying to find something in the sequence, use lower_bound - it will point directly to the element if it's found.

    If you're inserting into the sequence, use upper_bound - it preserves the original ordering of duplicates.

提交回复
热议问题