【问题标题】:How to using boost::unordered_set with custom class?如何将 boost::unordered_set 与自定义类一起使用?
【发布时间】:2021-08-24 21:37:46
【问题描述】:

我很难调用 hash_value。 从这个post,我想申请vector<vector<E>>,其中E 是一个自定义对象。 我的代码如下:

struct E;
class myclass {
private:
     vector<E> lhs;
public:
    myclass(const vector<E>& v) :lhs{ v } {  };
    static size_t hash_value(const vector<E>& v) {
      size_t seed = 0;
         boost::hash_combine(seed, d.name);
         boost::hash_combine(seed, d.scope);
      return seed;
    }
    bool operator==(const vector<E> >& rhs) {
       for (unsigned i = 0; i < lhs.size(); i++)
         if (lhs[i].name != rhs[i].name || lhs[i].scope!= rhs[i].scope)
             return false;
       return true;
    };
};

然后我调用这个代码:

void test(std::vector<std::vector<E>>& A)
{
    boost::unordered_set < myclass > input_records(A.size());
    
    for (BOOST_AUTO(it, A.begin()); it != (A.end());) {
      auto k = input_records.insert(myclass{*it}); <<--
      ....
    }
}

但是我得到一个错误:

此外,在某些情况下,此代码会执行,但从未调用 hash_value。 我不确定我错过了什么?

我该如何解决这个问题?

【问题讨论】:

    标签: c++ boost


    【解决方案1】:

    您正在尝试使用boost::unordered_set&lt;myclass&gt;,它将在内部使用boost::hash&lt;myclass&gt;,它将通过Argument-Dependent Lookup 在与myclass 相同的命名空间中查找hash_value(myclass) 函数。您使您的hash_value() 成为myclass 的非静态成员,因此boost::hash 将无法找到它。但即使可以,它也希望您的 hash_value() 将单个 myclass 对象作为参数,而不是 vector

    请参阅 Boost 文档中的 Extending boost::hash for a custom data type

    此外,一个类的operator==*this 与另一个对象进行比较。在myclass 内部,您的operator== 应该将单个myclass 对象作为参数,而不是vector

    试试这个:

    struct E {
        string name;
        int scope;
    };
    
    size_t hash_value(const E& obj) {
        std::size_t seed = 0;
        boost::hash_combine(seed, obj.name);
        boost::hash_combine(seed, obj.scope);
        return seed;
    }
    
    class myclass {
    private:
        vector<E> vec;
    public:
        myclass(const vector<E>& v) : vec(v) {}
    
        bool operator==(const myclass& rhs) const {
           // vector has its own operator== for comparing elements in its array...
           return vec == rhs.vec;
        }
    
        friend size_t hash_value(const myclass& obj) {
            return boost::hash_range(obj.vec.begin(), obj.vec.end());
        }
    };
    
    void test(std::vector<std::vector<E>>& A)
    {
        boost::unordered_set<myclass> input_records(A.size());
        
        for (BOOST_AUTO(it, A.begin()); it != (A.end());) {
          auto k = input_records.insert(*it);
          ...
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-04-01
      • 1970-01-01
      • 2020-08-20
      • 2022-01-07
      • 2016-11-27
      • 1970-01-01
      • 2019-05-23
      • 2023-03-11
      相关资源
      最近更新 更多