[英]C++ - type qualifiers error when hashing user defined object
我目前有一個名為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,使用自定義類類型作為鍵
但是,我一直面對這些錯誤。
在參數中刪除“ const”似乎也無濟於事。 我的實現有問題嗎? 我將無法使用其他庫,例如boost。
您需要確保編譯器成員函數不會修改* this指針
#include <vector>
#include <string>
class ResultTableEntry {
private:
int relIndex;
std::vector<int> paramIndex;
std::vector<std::string> result;
public:
ResultTableEntry(int, std::vector<int>, std::vector<std::string>);
int getRelationshipIndex() const;
std::vector<int> getParameterIndex() const;
std::vector<std::string> getResult() const;
};
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;
}
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.