如何为自定义类使用C ++ unordered_set? [英] How can I use a C++ unordered_set for a custom class?

查看:392
本文介绍了如何为自定义类使用C ++ unordered_set?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在unordered_set中存储类的对象?我的程序需要经常检查此unordered_set中是否存在对象,如果存在,则对该对象进行一些更新.

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, then do some update on that object.

我在线上查找了如何使用unordered_set,但是可悲的是,大多数教程都涉及在intstring类型上使用它.但是如何在课堂上使用它呢?在下面的示例中,如何定义哈希函数以使node_id成为unordered_set的键?

I have looked up online on how to use unordered_set, but sadly most tutorials are about using it on int or string types. But how can I use it on a class? How can I define a hash function to make the node_id in the following example the key of the unordered_set?

#include <iostream>
#include <unordered_set>

using namespace std;

// How can I define a hash function that makes 'node' use 'node_id' as key?    
struct node
{
    string node_id;
    double value;
    node(string id, double val) : node_id(id), value(val) {}
};

int main()
{
    unordered_set<node> set;
    set.insert(node("1001", 100));
    if(set.find("1001") != set.end()) cout << "1001 found" << endl;
}

推荐答案

您可以尝试使用以下哈希函数对象(这是非常基本的,因此您可能需要对其进行改进以避免过多的冲突).

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<std::string>()(_node.node_id);
    }
}
// ...
std::unordered_set<node, node_hash> node_set;

但是,正如其中一项评论所指出的那样,您最好在此处使用std::unordered_map<std::string, double>.

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

这篇关于如何为自定义类使用C ++ unordered_set?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆