在[1]對常用的STL容器進行了概覽,筆者在刷題過程中經常需要查詢一些STL容器的函數,實爲不便,因此在此對STL容器中常用的操作進行筆記。
std::unordered_set<key>
是一種STL提供的無序集合的類,集合的特點就是其中沒有任何重複的元素,這個特點非常適合用於紀錄某個數據中是否有重複的數據,並且將其挑出來。std::unordered_set
其和std::set
不同的一點是,前者是沒有順序的,而後者會對元素順序進行排序,也正是因爲其沒有順序,無序set的速度要快得多。通常可以在常數時間進行插入和刪除。無序set的鍵值和其內容值是一樣的,和map不同的,我們不能修改其內容,但是可以插入元素或者刪除元素。
其類聲明原型爲:
template < class Key, // unordered_set::key_type/value_type
class Hash = hash<Key>, // unordered_set::hasher
class Pred = equal_to<Key>, // unordered_set::key_equal
class Alloc = allocator<Key> // unordered_set::allocator_type
> class unordered_set;
其中最需要注意的其實就是key
的數據類型的指定了。其常用的函數也不多:
find()
查找元素insert()
插入元素erase()
刪除元素clear()
清空容器empty()
判斷容器是否爲空size()
返回容器的大小
我們通過下面的例子學會如何使用無序set:
#include <unordered_set>
using namespace std;
int main() {
unordered_set<int> s = {1,2,3,4};
auto got = s.find(2);
if (got == s.end())
cout << "not found" << endl ;
else
cout << "element" << *got << " is found" << endl;
s.insert(5);
s.erase(5);
s.clear(); // 清空容器
}
Reference
[1]. https://blog.csdn.net/LoseInVain/article/details/104189784