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

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

    In this case, I think a picture is worth a thousand words. Let's assume we use them to search for 2 in the following collections. The arrows show what iterators the two would return:

    enter image description here

    So, if you have more than one object with that value already present in the collection, lower_bound will give you an iterator that refers to the first one of them, and upper_bound will give an iterator that refers to the object immediately after the last one of them.

    This (among other things) makes the returned iterators usable as the hint parameter to insert.

    Therefore, if you use these as the hint, the item you insert will become the new first item with that value (if you used lower_bound) or last item with that value (if you used upper_bound). If the collection didn't contain an item with that value previously, you'll still get an iterator that can be used as a hint to insert it in the correct position in the collection.

    Of course, you can also insert without a hint, but using a hint you get a guarantee that the insertion completes with constant complexity, provided that new item to insert can be inserted immediately before the item pointed to by the iterator (as it will in both these cases).

提交回复
热议问题