C++ equal_range() 函数

函数原型:

#include <algorithm>
 pair<forward_iterator,forward_iterator> equal_range( forward_iterator first, forward_iterator last, const TYPE& val );
 pair<forward_iterator,forward_iterator> equal_range( forward_iterator first, forward_iterator last, const TYPE& val, CompFn comp );

函数equal_range()返回first和last之间等于val的元素区间.返回值是一对迭代器。 

此函数假定first和last区间内的元素可以使用<操作符或者指定的comp执行比较操作.
equal_range()可以被认为是lower_bound和upper_bound的结合,

pair中的第一个迭代器由lower_bound返回, 第二个则由upper_bound返回.

下面的代码使用equal_range()探测一个有序的vector中的可以插入数字8的位置:

vector<int> nums;
 nums.push_back( -242 );
 nums.push_back( -1 );
 nums.push_back( 0 );
 nums.push_back( 5 );
 nums.push_back( 8 );
 nums.push_back( 8 );
 nums.push_back( 11 );
 pair<vector<int>::iterator, vector<int>::iterator> result;
 int new_val = 8;  
 result = equal_range( nums.begin(), nums.end(), new_val ); 
cout<< "The first place that " 
 << new_val
 << " could be inserted is before " << *result.first
 << ", and the last place that it could be inserted is before " << *result.second
 << endl;
运行结果:

The first place that 8 could be inserted is before 8, and the last place that it could be inserted is before 11



你可能感兴趣的:(C++ equal_range() 函数)