upper_bound()函数以及lower_bound()函数作用

版权声明:欢迎评论与转载,转载时请注明出处! https://blog.csdn.net/wjl_zyl_1314/article/details/83348909

说一下这两个函数的基本特征吧。
首先,这两个函数是STL标准函数库给我们提供的已经写好的函数。
其头文件是:

#include <algorithm>

其次让我们来细看一下这两个函数:

  • ForwardIter lower_bound(ForwardIter first, ForwardIter last,const _Tp& val)算法返回一个非递减序列[first, last)中的第一个大于等于值val的位置。
  • ForwardIter upper_bound(ForwardIter first, ForwardIter last, const _Tp& val)算法返回一个非递减序列[first, last)中最后一个大于val的位置
这里我们很容易看出两个函数都是有三个形参的,分别是序列的起始位置first,结束位置last,以及键值val(即你想要查询的值)。再仔细看这两个函数的区别就在于lower_bound()返回的是 大于等于val的第一个位置,而upper_bound()返回的是 大于val的最后一个位置。 更深层次的这两个函数可以在数组、vector、map、set等容器中使用,返回类型是一个指针或者是一个迭代器。下面是一个数组小的测试程序:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int num[10]={1,2,2,3,4,4,5,6,9,9};
    int* st=lower_bound(num,num+10,2);//返回是个int型的指针,指向的是存储第一个大于等于val值的地址
    cout<<"Start: "<<st<<endl;
    int* ed=upper_bound(num,num+10,4);//返回是个int型的指针,指向的是存储最后一个大于val值的地址
    cout<<"End: "<<ed<<endl;
    cout<<"End-Start :"<<ed-st<<endl;
}

以及运行结果:

Start: 0x6dfecc
End: 0x6dfee0
End-Start :5

下面是一个vector容器的测试小程序:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
    vector<int> num;
    num.push_back(1);
    num.push_back(2);
    num.push_back(2);
    num.push_back(3);
    num.push_back(4);
    num.push_back(4);
    num.push_back(5);
    vector<int>::iterator st=lower_bound(num.begin(),num.end(),2);//返回是个迭代器,指向的是存储第一个大于等于val值的地址
    //cout<<"Start: "<<st<<endl;由于输出输入迭代器涉及流操作,不做过多解释
    vector<int>::iterator ed=upper_bound(num.begin(),num.end(),4);//返回是个迭代器,指向的是存储最后一个大于val值的地址
    //cout<<"End: "<<ed<<endl;//
    cout<<"End-Start :"<<ed-st<<endl;//直接输出两个的迭代器之间的差值
}

以及运行结果:

End-Start :5

读者可以自己去做一些小测试,这里不再赘述。

猜你喜欢

转载自blog.csdn.net/wjl_zyl_1314/article/details/83348909