1. 簡(jiǎn)介
邊界函數(shù)必須先排序,才能使用
函數(shù) | 作用 | 文檔 |
---|---|---|
lower_bound(beg,end,val) |
在[beg ,end )范圍內(nèi)的可以插入val 而不破壞容器順序的第一個(gè)位置数尿,返回一個(gè)ForwardIterator 果漾。 |
lower_bound() |
lower_bound(beg,end,val,comp) |
使用函數(shù)comp 代替比較操作符執(zhí)行lower_bound() 。 |
lower_bound() |
upper_bound(beg,end,val) |
在[beg ,end )范圍內(nèi)插入val 而不破壞容器順序的最后一個(gè)位置原环,該位置標(biāo)志一個(gè)大于val 的值棒动,返回一個(gè)ForwardIterator 恋博。 |
upper_bound() |
upper_bound(beg,end,val,comp) |
使用函數(shù)comp 代替比較操作符執(zhí)行upper_bound() 瘫絮。 |
upper_bound() |
equal_range(beg,end,val) |
返回一對(duì)iterator 涨冀,第一個(gè)表示lower_bound ,第二個(gè)表示upper_bound 麦萤。 |
equal_range() |
equal_range(beg,end,val,comp) |
使用函數(shù)comp 代替比較操作符執(zhí)行lower_bound() 鹿鳖。 |
equal_range() |
2. 示例代碼
- lower_bound/upper_bound
// lower_bound/upper_bound example
#include <iostream> // std::cout
#include <algorithm> // std::lower_bound, std::upper_bound, std::sort
#include <vector> // std::vector
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
std::vector<int>::iterator low,up;
low=std::lower_bound (v.begin(), v.end(), 20); // ^
up= std::upper_bound (v.begin(), v.end(), 20); // ^
std::cout << "lower_bound at position " << (low- v.begin()) << '\n';
std::cout << "upper_bound at position " << (up - v.begin()) << '\n';
return 0;
}
- equal_range
// equal_range example
#include <iostream> // std::cout
#include <algorithm> // std::equal_range, std::sort
#include <vector> // std::vector
bool mygreater (int i,int j) { return (i>j); }
int main () {
int myints[] = {10,20,30,30,20,10,10,20};
std::vector<int> v(myints,myints+8); // 10 20 30 30 20 10 10 20
std::pair<std::vector<int>::iterator,std::vector<int>::iterator> bounds;
// using default comparison:
std::sort (v.begin(), v.end()); // 10 10 10 20 20 20 30 30
bounds=std::equal_range (v.begin(), v.end(), 20); // ^ ^
// using "mygreater" as comp:
std::sort (v.begin(), v.end(), mygreater); // 30 30 20 20 20 10 10 10
bounds=std::equal_range (v.begin(), v.end(), 20, mygreater); // ^ ^
std::cout << "bounds at positions " << (bounds.first - v.begin());
std::cout << " and " << (bounds.second - v.begin()) << '\n';
return 0;
}