How can I use a C++ unordered_set for a custom class?

后端 未结 4 1788
逝去的感伤
逝去的感伤 2021-02-04 07:32

How can I store objects of a class in an unordered_set? My program needs to frequently check if an object exists in this unordered_set and if it does,

4条回答
  •  梦如初夏
    2021-02-04 07:40

    You could try using the following hash function object (it's pretty basic so you may want to improve it to avoid too many collisions).

    struct node_hash {
        std::size_t operator()(const node& _node) const {
            return std::hash()(_node.node_id);
        }
    }
    // ...
    std::unordered_set node_set;
    

    However, as one of the comments points out, you may be better off using a std::unordered_map here.

提交回复
热议问题