lower_bound()、upper_bound()

来源:互联网 发布:泛微协同软件 编辑:程序博客网 时间:2024/05/22 19:40

参考一

函数作用

  iterator lower_bound( const key_type &key ): 返回一个迭代器,指向键值>= key的第一个元素。

  iterator upper_bound( const key_type &key ):返回一个迭代器,指向键值> key的第一个元素。

 

lower_bound()函数

第一个版本:

  template< class ForwardIterator, class Type >

  ForwardIterator

  lower_bound( ForwardIterator first,

  ForwardIterator last, const Type &value );

 

  第二个版本:

  template< class ForwardIterator, class Type, class Compare >

  ForwardIterator

  lower_bound( ForwardIterator first,

  ForwardIterator last, const Type &value,

  Compare comp );

函数介绍

  lower_bound()返回一个 iterator 它指向在[first,last)标记的有序序列中可以插入value,而不会破坏容器顺序的第一个位置,而这个位置标记了一个大于等于value 的值。

 

  例如,有如下序列:

 

  ia[]={12,15,17,19,20,22,23,26,29,35,40,51};

 

  用值21调用lower_bound(),返回一个指向22的iterator。用值22调用lower_bound(),也返回一个指向22的iterator。第一个版本使用底层的 < (小于)操作符,第二个版本根据comp进行排序和比较。

注意事项

  调用lower_bound之前必须确定序列为有序序列,否则调用出错。第一个版本排序根据底层的 <(小于)操作符,第二个版本根据comp进行排序。

 

参考二

// lower_bound/upper_bound example#include <iostream>     // std::cout#include <algorithm>    // std::lower_bound, std::upper_bound, std::sort#include <vector>       // std::vectorint 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;}


Output:

lower_bound at position 3upper_bound at position 6

 

参考三

#include<iostream>#include<algorithm>#include<vector>using namespace std;class student{public:int key;int value;/*bool operator()(student a,student b){return a.key<b.key;}*/};bool cmp(student a,student b){return a.key<b.key;}int main(){vector<student> vec(6);int i;vector<student>::iterator low;vec[0].key=15;vec[0].value=1;vec[1].key=2;vec[1].value=2;vec[2].key=2;vec[2].value=2;;vec[3].key=3;vec[3].value=3;vec[4].key=3;vec[4].value=4;vec[5].key=7;vec[5].value=5;sort(vec.begin(),vec.end(),cmp);for(i=0;i<6;i++)cout<<vec[i].key<<endl;low=lower_bound(vec.begin(),vec.end(),vec[3],cmp);cout<<int(low-vec.begin())<<endl;}


 

原创粉丝点击