【发布时间】:2018-08-06 14:10:12
【问题描述】:
我目前有一个名为 ResultTableEntry 的用户定义类,我希望能够创建一个 std::unordered_set。我发现这将为我的类创建一个哈希函数,以便我初始化集合。
#include <vector>
#include <string>
class ResultTableEntry {
private:
int relIndex;
std::vector<int> paramIndex;
std::vector<std::string> result;
public:
ResultTableEntry::ResultTableEntry(int, std::vector<int>, std::vector<std::string>);
int getRelationshipIndex();
std::vector<int> getParameterIndex();
std::vector<std::string> getResult();
};
namespace std {
template <>
struct hash<ResultTableEntry>
{
std::size_t operator()(const ResultTableEntry& k) const
{
size_t res = 17;
for (auto p : k.getParameterIndex()) {
res = res * 31 + hash<int>()(p);
}
for (auto r : k.getResult()) {
res = res * 31 + hash<std::string>()(r);
}
res = res * 31 + hash<int>()(k.getRelationshipIndex());
return res;
}
};
}
我根据:C++ unordered_map using a custom class type as the key实现了我的哈希函数
但是,我一直面临这些错误。
- 对象具有与成员函数“ResultTableEntry::getParameterIndex”不兼容的类型限定符
- 对象具有与成员函数“ResultTableEntry::getResult”不兼容的类型限定符
- 对象具有与成员函数“ResultTableEntry::getRelationshipIndex”不兼容的类型限定符
- 类型为 'const std::hash' 的表达式会丢失一些 const-volatile 限定符,以便调用 'size_t std::hash::operator ()(ResultTableEntry &)'
删除参数中的 'const' 似乎也无济于事。我的实现有问题吗?我将无法使用 boost 等其他库。
【问题讨论】:
标签: c++ object hash operator-overloading user-defined-types