關於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的下一個位置
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章