【问题标题】:C++ - type qualifiers error when hashing user defined objectC++ - 散列用户定义对象时出现类型限定符错误
【发布时间】: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


    【解决方案1】:

    您需要向编译器保证成员函数不会修改 *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;
            }
        };
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多