在有序的空间查找一个元素的位置,并且在插入该元素之后,仍旧维持该空间的有序。
例如:一个vec,其中存在元素:0,3,5,8;
如果试图插入元素4,
两个元素返回的都是5所对应的位置,执行insert在该位置插入4后,该vec是这个样子:0,3,4,5,8;
如果试图插入元素5,
则lower_bound返回元素5的位置,而upper_bound返回元素8的位置。
此时如果执行插入5后,vec看起来的样子是一样的。但实际上,对lowwer插入的5在原先的5之前,而对upper_bound插入的5在原先的5之后。
综合起来说,lowwer_bound返回第一个可以插入的位置,而upper_bound返回的最后一个可以插入的位置。
备注:这两个函数的比较是基于等价的比较,而不是相等的比较,何为等价,何为相等,请参阅《effective stl》。
关于lowwer_bound和upper_bound的测试代码如下:
// alg_upper_bound.cpp
// compile with: /EHsc
#include <vector>
#include <algorithm>
#include <functional> // For greater<int>( )
#include <iostream>
// Return whether modulus of elem1 is less than modulus of elem2
struct Print
{
template <typename T>
void operator () (const T &val)
{
std::cout << val << "\t";
}
};
int main( )
{
typedef std::vector<int> VecInt;
typedef VecInt::iterator It;
const int VECSIZE = 10;
srand(0);
VecInt vi, vi2;
vi.reserve(VECSIZE);
for (int i = 0; i < VECSIZE; ++i)
{
vi.push_back(int(double(rand())/RAND_MAX * 100));
}
vi2.assign(vi.begin(), vi.end());
sort(vi.begin(), vi.end(), std::less<int>());
sort(vi2.begin(), vi2.end(), std::greater<int>());
std::cout << "value in vi: " << std::endl;
std::for_each(vi.begin(), vi.end(), Print());
std::cout << "value in vi2: " << std::endl;
std::for_each(vi2.begin(), vi2.end(), Print());
It iter = std::lower_bound(vi.begin(), vi.end(), 23);
std::cout << "lower_boudn of vi for 23 is: " << *iter << std::endl;
iter = std::upper_bound(vi.begin(), vi.end(), 23);
std::cout << "upper_boudn of vi for 23 is: " << *iter << std::endl;
iter = std::lower_bound(vi2.begin(), vi2.end(), 23, std::greater<int>());
std::cout << "lower_boudn of vi2 for 23 is: " << *iter << std::endl;
iter = std::upper_bound(vi2.begin(), vi2.end(), 23, std::greater<int>());
std::cout << "upper_boudn of vi2 for 23 is: " << *iter << std::endl;
iter = std::lower_bound(vi.begin(), vi.end(), 24);
std::cout << "lower_boudn of vi for 24 is: " << *iter << std::endl;
iter = std::upper_bound(vi.begin(), vi.end(), 24);
std::cout << "upper_boudn of vi for 24 is: " << *iter << std::endl;
iter = std::lower_bound(vi2.begin(), vi2.end(), 24, std::greater<int>());
std::cout << "lower_boudn of vi2 for 23 is: " << *iter << std::endl;
iter = std::upper_bound(vi2.begin(), vi2.end(), 24, std::greater<int>());
std::cout << "upper_boudn of vi2 for 24 is: " << *iter << std::endl;
system("pause..");
}