【C++ 基礎語法 #7】C++ unorder_set() 用法筆記

前言

unorder_set() 作為一種 hashset 是一個滿經典的用法,
在 python 寫 set() 久了,換過來還真的有點不習慣,這裡稍微紀錄一下常見用法。

這裡只紀錄個人會常用到的用法,因此這裡「不會是完整的使用教學哦」(要完整請直接看文件)

初始化 unorder_set()

我們可以透過宣告一個 {},代表建立一個空的 set()

std::unordered_set<int> myset{};

insert,插入值進 unorder_set()

這邊留意一下 set 的特性,重複的值插入是「不會產生第二個」的

myset.insert(1);
myset.insert(2);
myset.insert(2);
myset.insert(3);

count,“單純” 確認元素存在

這裡我覺得很神奇,居然是用 count,
但 set 裡面最多就一個啊…. 是要 count 啥?

至少應該用 find? 不過 find 被另外拿去用了,下面會介紹, find 被拿去要來取出東西用的了

cout << "count 2 in myset = " << myset.count(2) << endl; // 1, 不會因為 insert 兩次變多
cout << "count 5 in myset = " << myset.count(5) << endl; // 1

find,尋找元素

find 與 count 的不同,就是 find 能幫我們拿到元素存在 set 的 iterator 位置,

cout << "find 2 in myset = " << *myset.find(2) << endl; // 透過 find 取得 iterator,並用 * 取得值

遍歷 unorder_set 中的元素

遍歷也很常需要用到,通常都是我自己 debug 的時候要看看有什麼…

這時就要呼叫我們的 iterator 了,然後就會感覺到程式變成超長又不好讀…

for (std::unordered_set<int>::iterator it = myset.begin(); it != myset.end(); it++) {
    cout << *it << endl;
}

C++ 11 以後的替代方案

謝天謝地的是,C++ 11 之後新增了 auto,可以幫我們處理掉前面那個看起來有點冗長的東西…

取而代之的就是,自己必須對 type 更加清楚,不然這會是個未來對 type 混亂災難性的開始…

把上面 type 的部分直接改成 auto 即可,
個人是認為雖然程式碼更簡潔了,但更考驗工程師對 type 的理解程度…

for (auto it = myset.begin(); it != myset.end(); it++) {
    cout << *it << endl;
}

完整範例程式碼

void exp_unordered_set(){
    std::unordered_set<int> myset{};
    myset.insert(1);
    myset.insert(2);
    myset.insert(2);
    myset.insert(3);

    cout << "find 2 in myset = " << myset.count(2) << endl;
    cout << "find 5 in myset = " << myset.count(5) << endl;

    for (std::unordered_set<int>::iterator it = myset.begin(); it != myset.end(); it++) {
        cout << *it << endl;
    }

    for (auto it = myset.begin(); it != myset.end(); it++) {
        cout << *it << endl;
    }
}
  • 結果:

Reference