Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีสร้าง unordered_set ของคลาสหรือโครงสร้างที่ผู้ใช้กำหนดใน C++


ในบทช่วยสอนนี้ เราจะอภิบายโปรแกรมเพื่อทำความเข้าใจวิธีสร้าง unordered set ของคลาสหรือโครงสร้างที่ผู้ใช้กำหนดใน 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