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