equal_range

来源:互联网 发布:青海干部培训网络 编辑:程序博客网 时间:2024/04/29 13:47
/*STL中的equal_range算法返回一个pair类型的值range,vector<int> vec;...//vec initializepair<vector<int>::iterator,vector<int>::iterator> range;range = equal_range(vec.begin(),vec.end(),value); 其中range.first是可以在不改变原来排序顺序的情况下的可以插入value的最小迭代器位置, range.second是不改变原来排序顺序的情况下的可以插入value的最大迭代器位置. 实际情况是:如果vec中存在value,那么range.first就是vec中的指向第一个value位置的迭代器,而range.second则是vec中指向第一个大于value的值的位置的迭代器. 如果搜索值在容器中是最后一个值那么range.second就是container.end().当vec中没有value时,range返回一个0区间, 也就是range.first=range.second=指向vec中第一个值大于value的位置的迭代器(可能为vec.end,如果vec中所有值均小于value)。*/#include <iostream>     // std::cout#include <algorithm>    // std::equal_range, std::sort#include <vector>       // std::vectorbool 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);            //          ^        ^  std::cout << "bounds at positions " << (bounds.first - v.begin());  std::cout << " and " << (bounds.second - v.begin()) << '\n';  // 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';  system("pause");  return 0;}/*Output:bounds at positions 3 and 6bounds at positions 2 and 5*/

原创粉丝点击