如何在 C++ 中建立自定義類或結構的無序集?
在本教程中,我們將討論一個程式來了解如何在 C++ 中建立自定義類或結構的無序集。
為此,我們將建立一個結構型別,然後使用使用者定義的函式比較兩個結構型別以儲存雜湊函式。
示例
#include <bits/stdc++.h> using namespace std; //defined structure struct Test { int id; bool operator==(const Test& t) const{ return (this->id == t.id); } }; //defined class for hash function class MyHashFunction { public: size_t operator()(const Test& t) const{ return t.id; } }; int main(){ Test t1 = { 110 }, t2 = { 102 }, t3 = { 101 }, t4 = { 115 }; //defining unordered set unordered_set<Test, MyHashFunction> us; us.insert(t1); us.insert(t2); us.insert(t3); us.insert(t4); for (auto e : us) { cout << e.id << " "; } return 0; }
輸出
115 101 110 102
廣告