且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C ++中使用std :: unordered_set?

更新时间:2023-11-10 08:58:34

步骤1:为您的类型重载 operator ==

  bool operator ==(const Some& x,const Some& y)
{
return xa == ya;

$ / code>

第二步:专用 std :: hash
$ b

  namespace std 
{
template<> code>
struct hash< Some>
{
typedef一些argument_type;
typedef size_t result_type;

size_t operator()(const Some& x)const
{
return x.a;
}
};
}

第3步:简单测试:

  int main()
{
std :: unordered_set< Some>测试;
test.insert(一些{42});
}

第四步:获利!


I picked the concepts of hash tables in Java, so I was aware that for a generic "hash set" container to work for custom classes, one must provide definition for a hash function and an corresponding equality function.

In Java, this would mean overriding method

int hashCode()

and

boolean equals (Object o)

.

I was expecting the same logic in c++'s STL, but was having trouble understanding the syntax. Specifically, std::unordered_set<> accepts 5 template arguments (can you believe that?), which looks like a monster and makes my head spin.

So I would be appreciate it if one could give a simple example for the current toy class:

class Some{
public :
int a;
};

Of which the hash function simply returns the value of a, and the equality test functions returns true iff the values of member 'a' are the same.

Thanks

Step 1: Overload operator== for your type:

bool operator==(const Some& x, const Some& y)
{
    return x.a == y.a;
}

Step 2: Specialize std::hash for your type:

namespace std
{
    template<>
    struct hash<Some>
    {
        typedef Some argument_type;
        typedef size_t result_type;

        size_t operator()(const Some& x) const
        {
            return x.a;
        }
    };
}

Step 3: A simple test:

int main()
{
    std::unordered_set<Some> test;
    test.insert(Some{42});
}

Step 4: Profit!