C ++ set upper_bound()函數(shù)用于返回一個迭代器,該迭代器指向set容器中的值,該值大于參數(shù)中傳遞的val。
iterator upper_bound (const value_type& val) const; //C++ 11 之前 iterator upper_bound (const value_type& val); //C++ 11 之后 const_iterator upper_bound (const value_type& val) const; //C++ 11 之后
val:要在集合容器中搜索的值。
它返回一個迭代器,該迭代器指向set容器中的值,該值大于參數(shù)中傳遞的val。如果沒有這樣的元素,則返回end()。
大小為對數(shù)。
沒有變化。
容器被訪問(const和非const版本都不能修改容器)。
同時訪問集合的元素是安全的。
如果引發(fā)異常,則容器中沒有任何更改。
讓我們看一個簡單的示例,以獲取給定值的上限:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m = {'a', 'b', 'c', 'd'};
auto it = m.upper_bound('b');
cout << "b的上限是(>): " << *it << endl;
return 0;
}輸出:
b的上限是(>): c
在上面的示例中,當(dāng)我們嘗試找到元素b的上限時,它將返回元素b的較大值,即c
讓我們看一個簡單的示例,從下限到上限擦除set的元素:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset;
set<int>::iterator itlow,itup;
for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
itlow=myset.lower_bound (30); // ^
itup=myset.upper_bound (60); // ^
myset.erase(itlow,itup); // 10 20 70 80 90
std::cout << "myset包含:";
for (set<int>::iterator it=myset.begin(); it!=myset.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}輸出:
myset包含: 10 20 70 80 90
在上面的示例中,erase()函數(shù)將set的元素從下限(=)刪除到上限(>),并打印其余內(nèi)容。
讓我們看一個簡單的實例:
#include<iostream>
#include<set>
using namespace std;
int main()
{
// 初始化容器
set<int> mp;
// 按隨機順序插入元素
mp.insert( 12 );
mp.insert( 11 );
mp.insert( 15 );
mp.insert( 14 );
// 當(dāng)11存在時
auto it = mp.upper_bound(11);
cout << "鍵11的上限是 ";
cout << (*it)<< endl;
// 當(dāng)13不存在時
it = mp.upper_bound(13);
cout << "鍵13的上限是 ";
cout << (*it)<< endl;
// 當(dāng)17大于最大鍵值時,按大小
// mp的返回值作為鍵,值為0。
it = mp.upper_bound(17);
cout << "鍵17的上限是 ";
cout << (*it);
return 0;
}輸出:
鍵11的上限是 12 鍵13的上限是 14 鍵17的上限是 4
在上面的示例中,當(dāng)我們嘗試找到不存在于集合容器中但未超過最大值的值的上限時,它將返回更大的值,即當(dāng)我們嘗試找到13的上限時,它將返回返回14,當(dāng)我們嘗試查找集合中不存在且超過容器最大值的值的上限時,它將返回到end()。
讓我們看一個簡單的實例:
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int> s1;
set <int> :: const_iterator s1_AcIter, s1_RcIter;
s1.insert( 10 );
s1.insert( 20 );
s1.insert( 30 );
s1_RcIter = s1.upper_bound( 20 );
cout << "集合s1的鍵大于20的第一個元素是: " << *s1_RcIter << "." << endl;
s1_RcIter = s1.upper_bound( 30 );
// 如果沒有找到匹配的鍵,則返回end()
if ( s1_RcIter == s1.end( ) )
cout << "集合s1沒有鍵值大于元素 30." << endl;
else
cout << "鍵> 40的集合s1的元素為: "
<< *s1_RcIter << "." << endl;
//可以找到集合中特定位置的元素
//通過使用解引用的迭代器尋址位置
s1_AcIter = s1.begin( );
s1_RcIter = s1.upper_bound( *s1_AcIter );
cout << "s1的第一個元素的鍵大于"
<< endl << "s1的初始元素是: "
<< *s1_RcIter << "." << endl;
return 0;
}輸出:
集合s1的鍵大于20的第一個元素是: 30. 集合s1沒有鍵值大于元素 30. s1的第一個元素的鍵大于 s1的初始元素是: 20.