lundi 5 juillet 2021

How to make well-encapsulated classes while using unordered_set/map in c++?

I was looking at some tutorials on how to make an unordered_set for a class/struct. I found this easy-to-understand code (as a Java developer) which does the trick:

#include <iostream>
#include <unordered_set>
using namespace std;

struct Node{
    int val;
  
    bool operator==(const Node& n) const{
        return (this->val == n.val);
    }
};

class HashFunction{
    public:
        size_t operator()(const Node& n) const{
            return n.val;
        }
};

int main(){
    Node n1 = { 1 }, n2 = { 2 },
         n3 = { 3 }, n4 = { 4 };

    unordered_set<Node, HashFunction> us;
    us.insert(n1);
    us.insert(n2);
    us.insert(n3);
    us.insert(n4);
    
    for (auto node : us){
        cout << node.val << " ";
    }
    cout << endl;
    return 0;
}

I was wondering if we can make the struct Node a class, make the int val a private field and add unordered_set<Node, HashFunction> neighbours as a field to the Node class.

If not, what is a good practice to keep classes/structs well-encapsulated and have sets/maps fields for classes?

Aucun commentaire:

Enregistrer un commentaire