C ++ set equal_range()函數(shù)用于返回包含容器中等于val的所有元素的范圍的邊界。由于set容器中沒有重復(fù)的值,因此此范圍最多包含一個元素。
如果val不匹配容器中的任何值,返回值范圍將為0,兩個迭代器都將指向最近的大于val的值,否則,如果val大于容器中的所有元素,它將指向end。
pair<const_iterator,const_iterator> equal_range (const value_type& val) const; pair<iterator,iterator> equal_range (const value_type& val);
該范圍由兩個迭代器定義,一個指向不小于val的第一個元素,另一個指向大于val的第一個元素。
val:要在集合容器中搜索的值。
該函數(shù)返回pair。其中pair :: first位于范圍的下邊界,具有與lower_bound(val)將返回的值相同的值,pair :: second是與upper_bound(val)將返回的值相同,它對應(yīng)的范圍的上限。
大小為對數(shù)。
沒有變化。
容器被訪問(const和非const版本都不能修改容器)。
同時訪問集合的元素是安全的。
如果引發(fā)異常,則容器中沒有任何更改。
讓我們看一個簡單的實例:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m = {'a','b','c','d'};
auto ret = m.equal_range('b');
cout << "b的下限是: " << *ret.first<< endl;
cout << "b的上限是: " << *ret.second<< endl;
return 0;
}輸出:
b的下限是: b b的上限是: c
在上面的示例中,b的下限為b,b的上限為c。
讓我們看一個簡單的實例:
#include <iostream>
#include <set>
using namespace std;
int main()
{
// 初始化容器
set<int> mp;
// 按隨機順序插入元素
mp.insert( 4 );
mp.insert( 1 );
mp.insert( 6 );
pair<set<int>::const_iterator,set<int>::const_iterator> ret;
ret = mp.equal_range(10);
cout << "下限是: " << *ret.first;
cout << "\n上限是: " << *ret.second;
return 0;
}輸出:
下限是 3 上限是 3
在上面的示例中,equal_range()函數(shù)返回到end(),即3,因為它試圖查找set mp中不存在的10。
讓我們看一個簡單的實例:
#include <set>
#include <iostream>
int main( )
{
using namespace std;
typedef set<int, less< int > > IntSet;
IntSet s1;
set <int, less< int > > :: const_iterator s1_RcIter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
pair <IntSet::const_iterator, IntSet::const_iterator> p1, p2;
p1 = s1.equal_range( 20 );
cout << "集合s1中鍵為20的元素的上限為: "
<< *(p1.second) << "." << endl;
cout << "集合s1中鍵為20的元素的下限為: "
<< *(p1.first) << "." << endl;
//直接調(diào)用upper_bound
s1_RcIter = s1.upper_bound( 20 );
cout << "直接調(diào)用upper_bound(20)得到 "
<< *s1_RcIter << "," << endl
<< "匹配該pair的第二個元素"
<< " 由equal_range(20)返回。" << endl;
p2 = s1.equal_range( 40 );
//如果找不到匹配的鍵,
//該pair的兩個元素都返回end()
if ( ( p2.first == s1.end( ) ) && ( p2.second == s1.end( ) ) )
cout << "集合s1沒有鍵小于40的元素。" << endl;
else
cout << "集合s1的鍵> = 40的元素是: "
<< *(p1.first) << "." << endl;
return 0;
}輸出:
集合s1中鍵為20的元素的上限為: 30. 集合s1中鍵為20的元素的下限為: 20. 直接調(diào)用upper_bound(20)得到 30, 匹配該pair的第二個元素 由equal_range(20)返回。 集合s1沒有鍵小于40的元素。
讓我們看一個簡單的實例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
std::set<int> myset;
for (int i=1; i<=5; i++) myset.insert(i*10); // myset: 10 20 30 40 50
pair<std::set<int>::const_iterator,set<int>::const_iterator> ret;
ret = myset.equal_range(30);
cout << "下限指向: " << *ret.first << '\n';
cout << "上限指向: " << *ret.second << '\n';
return 0;
}輸出:
下限指向: 30 上限指向: 40