1. 程式人生 > >set容器幾個關鍵函式

set容器幾個關鍵函式

set在OI中非常好用,歸納幾種常見的功能qwq

#include<iostream>
#include<cstdio>
#include<set>
//set容器常見用法 
using namespace std;
                                                    //用仿函式可以做到自定義排序規則 
class R
{
    public:
    bool operator()(const int &pre,const int &bac)
    {
        
return pre>bac;//保證序列前大於後 } }; set<int/*,R*/> s; //去掉註釋就會使用仿函式, int main() { s.insert(5); s.insert(4); s.insert(3); s.insert(2); s.insert(1); for(set<int>::iterator i=s.begin();i!=s.end();i++) cout<<*i<<"
"; //print 1 2 3 4 5 //erase cout<<endl<<"Erase"; cout<<endl<<s.erase(3)<<endl; //刪除成功返回1,否則返回0 for(set<int>::iterator i=s.begin();i!=s.end();i++) cout
<<*i<<" "; //print 1 2 4 5 //uper_bound & lower_bound //uper_bound(x):返回 s中 滿足大於x 的最小元素 的迭代器 //lower_bound(x):返回 s中 滿足大於等於x 的最小元素 的迭代器 cout<<endl<<"uper_bound & lower_bound"; cout<<endl<<*s.upper_bound(3); //print 4 cout<<endl<<*s.lower_bound(3)<<endl; //print 4 cout<<endl<<*s.upper_bound(4); //print 5 cout<<endl<<*s.lower_bound(4)<<endl; //print 4 cout<<endl<<(s.lower_bound(6)==s.end())<<endl; //print 1 當沒有一個元素大於等於6時,返回尾迭代器 //insert cout<<endl<<"insert"<<endl; s.insert(6); for(set<int>::iterator i=s.begin();i!=s.end();i++) cout<<*i<<" "; //print 1 2 4 5 6 return 0; }

值得注意的是,當我們用仿函式改變規則使序列從大到小後,upper_bound和lower_bound的意義就不是註釋所描述的那樣了。現在這兩個函式的功能會很奇怪,下面我用一種適用於任何情況的簡單非專業描述來說明這兩個函式的功能

lower_bound(x) :

  1. 當容器中存在等於x的元素,返回該元素迭代器
  2. 否則,假設按照容器元素排列規則將x插入容器合適位置,那麼返回的是插入後 x下一個(右邊)元素的迭代器,若無元素則返回尾迭代器

exa.

  • 6 5 3 2 1 x=4,假設插入後:6 5 4 3 2 1  此時 返回元素3的迭代器
  • # % ^ & * (  ,假設插入¥(假設這是有序序列),# ¥ % ^ & * (  此時 返回元素%的迭代器

upper_bound(x) :

  就是沒有1.規則的lower_bound(x) 。。。其他一樣