如果以稍许不同的角度来思考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,其第一和第二(都是迭代器)皆指向该位置。
// map::equal_elements
#include
#include
using namespace std;
int main ()
{
map mymap;
pair
mymap['a']=10;
mymap['b']=20;
mymap['c']=30;
ret = mymap.equal_range('b');
cout << "lower bound points to: ";
cout << ret.first->first << " => " << ret.first->second << endl;
cout << "upper bound points to: ";
cout << ret.second->first << " => " << ret.second->second << endl;
return 0;
}
运行结果:
lower bound points to: 'b' => 20
upper bound points to: 'c' => 30