关于upper_bound,和lower_bound

在有序的空间查找一个元素的位置,并且在插入该元素之后,仍旧维持该空间的有序。

例如:一个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..");
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值