equal_range是C++ STL中的一种二分查找的算法,试图在已排序的[first,last)中寻找value,它返回一对迭代器i和j,其中i是在不破坏次序的前提下,value可插入的第一个位置(亦即lower_bound),j则是在不破坏次序的前提下,value可插入的最后一个位置(亦即upper_bound),因此,[i,j)内的每个元素都等同于value,而且[i,j)是[first,last)之中符合此一性质的最大子区间
如果以稍许不同的角度来思考equal_range,我们可把它想成是[first,last)内"与value等同"之所有元素形成的区间A,由于[fist,last)有序(sorted),所以我们知道"与value等同"之所有元素一定都相邻,于是,算法lower_bound返回区间A的第一个迭代器,算法upper_bound返回区间A的最后一个元素的下一个位置,算法equal_range则是以pair的形式将两者都返回
即使[fist,last)并未含有"与value等同"之任何元素,以上叙述仍然合理,这种情况下,"与value等同"之所有元素形成的,其实是一个空区间,在不破坏次序的情况下,只有一个位置可以插入value,而equal_range所返回的pair,其第一和第二(都是迭代器)皆指向该位置。
#include "algostuff.hpp"
#include <iterator>
#include <ostream>
using namespace std;
int main(){
list<int> coll;
INSERT_ELEMENTS(coll,1,9);
INSERT_ELEMENTS(coll,1,9);
coll.sort();
PRINT_ELEMENTS(coll);
cout<<endl;
pair<list<int>::iterator,list<int>::iterator> range;
range =equal_range(coll.begin(),coll.end(),5);
cout<<"5 could get position"
<<distance(coll.begin(),range.first)+1
<<"up to"
<<distance(coll.begin(),range.second)+1
<<"without breaking the sorting"<<endl;
cout<<"range.first:"<<*range.first<<endl;
cout<<"range.second:"<<*range.second<<endl;
return 1;
}
输出:
#include <iterator>
#include <ostream>
using namespace std;
int main(){
list<int> coll;
INSERT_ELEMENTS(coll,1,9);
INSERT_ELEMENTS(coll,1,9);
coll.sort();
PRINT_ELEMENTS(coll);
cout<<endl;
pair<list<int>::iterator,list<int>::iterator> range;
range =equal_range(coll.begin(),coll.end(),5);
cout<<"5 could get position"
<<distance(coll.begin(),range.first)+1
<<"up to"
<<distance(coll.begin(),range.second)+1
<<"without breaking the sorting"<<endl;
cout<<"range.first:"<<*range.first<<endl;
cout<<"range.second:"<<*range.second<<endl;
return 1;
}
输出:
1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
5 could get position9up to11without breaking the sorting
range.first:5
range.second:6