簡體   English   中英

C ++-哈希用戶定義的對象時出現類型限定符錯誤

[英]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,使用自定義類類型作為鍵

但是,我一直面對這些錯誤。

  • 該對象具有與成員函數“ ResultTableEntry :: getParameterIndex”不兼容的類型限定符
  • 該對象具有與成員函數“ ResultTableEntry :: getResult”不兼容的類型限定符
  • 該對象具有與成員函數“ ResultTableEntry :: getRelationshipIndex”不兼容的類型限定符
  • 具有'const std :: hash'類型的表達式將丟失一些const-volatile限定符,以便調用'size_t std :: hash :: operator()(ResultTableEntry&)'

在參數中刪除“ 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM