生活随笔
收集整理的這篇文章主要介紹了
STL之 set简略介绍。
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
set常用函數及其講解?
?構造set集合的主要目的是為了快速檢索,使用set前,需要在程序頭文件中包含聲明“#include<set>”。?set集合容器實現了紅黑樹(Red-Black Tree)的平衡二叉檢索樹的的數據結構,在插入元素時,它會自動調整二叉樹的排列,把該元素放到適當的位置.例如會將數字進行從小到大的默認排序,將string按字典順序自動排列。?創建集合對象。?創建set對象時,需要指定元素的類型,這一點和其他容器一樣.采用inset()方法把元素插入到集合中(set像集合中容器中放入元素只有inset()),插入規則在默認的比較規則下,是按元素值從小到大插入,如果自己指定了比較規則函數,則按自定義比較規則函數插入。使用前向迭代器對集合中序遍歷,結果正好是元素排序后的結果。元素的方向遍歷。?使用反向迭代器reverse_iterator可以反向遍歷集合,輸出的結果正好是集合元素的反向排序結果。它需要用到rbegin()和rend()兩個方法,它們分別給出了反向遍歷的開始位置和結束位置。 #include<iostream>
#include<set>
using namespace std;
int main()
{set<int> s;s.insert(5); //第一次插入5,可以插入s.insert(1);s.insert(6);s.insert(3);s.insert(5); //第二次插入5,重復元素,不會插入set<int>::iterator it; //定義前向迭代器//中序遍歷集合中的所有元素for(it = s.begin(); it != s.end(); it++){cout << *it << " ";}cout << endl;return 0;
}
//運行結果:1 3 5 6 元素的刪除
? ? ? ? 與插入元素的處理一樣,集合具有高效的刪除處理功能,并自動重新調整內部的紅黑樹的平衡(集合內部元素的排序)。刪除的對象可以是某個迭代器位置上的元素、等于某鍵值的元素、一個區間上的元素和清空集合。
#include<iostream>
#include<set>
using namespace std;
int main()
{set<int> s;s.insert(5); //第一次插入5,可以插入s.insert(1);s.insert(6);s.insert(3);s.insert(5); //第二次插入5,重復元素,不會插入 集合內部:1 3 5 6s.erase(6); //刪除鍵值為6的元素 集合內部:1 3 5set<int>::reverse_iterator rit; //定義反向迭代器 //反向遍歷集合中的所有元素for(rit = s.rbegin(); rit != s.rend(); rit++){cout << *rit << " ";}cout << endl; set<int>::iterator it;it = s.begin();for(int i = 0; i < 2; i++)it = s.erase(it); //將 1 3刪除for(it = s.begin(); it != s.end(); it++)cout << *it << " ";cout << endl;s.clear(); //將集合清空cout << s.size() << endl; //輸出集合的大小,即元素個數return 0;
}
/*
運行結果:
5 3 1
5
0
*/ ?
自定義比較函數。使用insert將元素插入到集合中去的時候,集合會根據設定的比較函數獎該元素放到該放的節點上去。在定義集合的時候,如果沒有指定比較函數,那么采用默認的比較函數,即按鍵值從小到大的順序插入元素。但在很多情況下,需要自己編寫比較函數。
編寫比較函數有兩種方法。
(1)如果元素不是結構體,那么可以編寫比較函數。下面的程序比較規則為按鍵值從大到小的順序插入到集合中。
#include<iostream>
#include<set>
using namespace std;
struct mycomp
{ //自定義比較函數,重載“()”操作符bool operator() (const int &a, const int &b){if(a != b)return a > b;elsereturn a > b;}
};
int main()
{set<int, mycomp> s; //采用比較函數mycomps.insert(5); //第一次插入5,可以插入s.insert(1);s.insert(6);s.insert(3);s.insert(5); //第二次插入5,重復元素,不會插入set<int,mycomp>::iterator it;for(it = s.begin(); it != s.end(); it++)cout << *it << " ";cout << endl;return 0;
}
/*
運行結果:6 5 3 1
*/
(2)如果元素是結構體,那么可以直接把比較函數寫在結構體內。?
#include<iostream>
#include<set>
#include<string>
using namespace std;
struct Info
{string name;double score;bool operator < (const Info &a) const // 重載“<”操作符,自定義排序規則{//按score由大到小排序。如果要由小到大排序,使用“>”即可。return a.score < score;}
};
int main()
{set<Info> s;Info info;//插入三個元素info.name = "Jack";info.score = 80;s.insert(info);info.name = "Tom";info.score = 99;s.insert(info);info.name = "Steaven";info.score = 60;s.insert(info);set<Info>::iterator it;for(it = s.begin(); it != s.end(); it++)cout << (*it).name << " : " << (*it).score << endl; return 0;
}
/*
運行結果:
Tom : 99
Jack : 80
Steaven : 60
*/
?
部分內容選自?:https://blog.csdn.net/alibaba_lhl/article/details/81151409
總結
以上是生活随笔為你收集整理的STL之 set简略介绍。的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。