0、概述
-
unordered_set
容器,可直譯為無序 set 容器。即unordered_set
容器和set
容器很像,唯一的區(qū)別就在于set
容器會自行對存儲的數(shù)據(jù)進行排序,而unordered_set
容器不會。 - 下面是
set
、multiset
和unordered_set
之間的差別。注意這三種集合的底層實現(xiàn),他決定了算法的時間復雜度。特別注意
multiset
其實是數(shù)值可重復版本的set
。 - 需要添加頭文件和命名空間
#include<vector> using namespace std ;
1、unordered_set容器初始化
- 創(chuàng)建空的set
unordered_set<int> set1;
- 拷貝構(gòu)造
unordered_set<int> set2(set1);
- 使用迭代器構(gòu)造 【常用】
unordered_set<int> set3(set1.begin(), set1.end());
- 使用數(shù)組作為其初值進行構(gòu)造
unordered_set<int> set4(arr,arr+5);
- 使用處置列表進行構(gòu)造
unordered_set<int> set6 {1,2,10,10};
2、unordered_set遍歷
- C11
for(int x : set1) { cout << x << endl; }
- 迭代器 【常用】
for(unordered_set<int>::iterator it = set1.begin(); it != set1.end(); ++it){ cout << *it << end; }
-
下面的遍歷方式不正確
for(int i=0;i<set1.size();i++){ cout << set1[i] << endl; }
3、unordered_set常用函數(shù)
- find() 【常用】
myset.find(x)
功能為:查找x
,找到之后返回迭代器,失敗則返回myset.end()
。注意:unordered_set
中數(shù)值不可重復,所以被尋找的數(shù)只有存在和不存在這兩種情況,不可能出現(xiàn)多次。 - insert() 【常用】
myset.insert(x)
功能為:插入元素x
- erase()
myset.erase(x)
功能為:刪除元素x
,成功則返回1,失敗則返回0
文章來源地址http://www.zghlxwxcb.cn/news/detail-491793.html
文章來源:http://www.zghlxwxcb.cn/news/detail-491793.html
到了這里,關于STL容器——unordered_set的用法的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!