gpt4 book ai didi

c++ - 如何在 C++ 中制作一组无序的整数对?

转载 作者:太空宇宙 更新时间:2023-11-04 12:37:46 24 4
gpt4 key购买 nike

下面的程序不编译无序的整数对集,但它编译整数。 unordered_set 及其成员函数是否可以用于用户定义的类型,我该如何定义它?

#include <unordered_set>
...

class A{
...
private:
std::unordered_set< std::pair<int, int> > u_edge_;
};

编译器错误:

error: no matching function for call to 'std::unordered_set >::unordered_set()'

最佳答案

没有计算一对散列的标准方法。将此定义添加到您的文件中:

struct pair_hash {
inline std::size_t operator()(const std::pair<int,int> & v) const {
return v.first*31+v.second;
}
};

现在你可以像这样使用它:

std::unordered_set< std::pair<int, int>,  pair_hash> u_edge_;

这行得通,因为 pair<T1,T2>定义平等。对于不提供测试相等性方法的自定义类,您可能需要提供一个单独的函数来测试两个实例是否彼此相等。

当然,这个解决方案仅限于一对两个整数。这是 a link to an answer这有助于您定义一种更通用的方法来为多个对象制作哈希。

关于c++ - 如何在 C++ 中制作一组无序的整数对?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55605515/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com