关于algorithm中lower_bound与upper_bound的理解

lower_bound 与 upper_bound 均只用了时间复杂度为O(logn)的二分查找算法。
lower_bound(first, last, val, comp)
first, last: the forward iterator represents the range [first, last) of a sort sequence.注意一定要是已排序的对象
val: the value of lower bound search for in the range.
comp: 二元函数,第一个参数为forward iterator所指向的元素,第二个参数始终为val.
return value: 返回[first, last)内,符合val要求的lower bound的位置;若范围内所有元素均小于val,返回last.

upper_bound(first, last, val, comp)
与lower_bound不同的是,upper_bound返回符合val要求的upper_bound的下一个位置。

eg:

#include <algorithm>	//lower_bound, upper_bound
#include <vector>

int aa[8] = { 10, 20, 10, 30, 50, 40, 20, 10 };
vector<int> nums_40(aa, aa + 8);
sort(nums_40.begin(), nums_40.end()); //10 10 10 20 20 30 40 50
vector<int>::iterator it, it1;
it = lower_bound(nums_40.begin(), nums_40.end(), 20);
cout << *it <<endl;	//20,此时的it指向第一个20的位置
it1 = upper_bound(nums_40.begin(), nums_40.end(), 20);
cout << *it1 << endl;	//30  不是20,此时的it1指向右侧20的下一个位置
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章