如何正确使用struct / std :: pair?

时间:2017-04-16 22:51:16

标签: c++

我在我的项目中使用struct有一个unordered_map,我试图将一个结构或一对整数作为地图的关键,然后操纵地图,但无法编译,它说:

usr/include/c++/4.8/bits/hashtable_policy.h:1082:53: error: invalid use of incomplete type âstrruct std::hash<NAMESPACE::Span<int> >â
using __ebo_h1 = _Hashtable_ebo_helper<1, _H1>;

operator==(const unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>& __x,
 ^
/usr/include/c++/4.8/bits/unordered_map.h:1388:5: note:   template  argument deduction/substitution failed:
In file included from /usr/include/c++/4.8/string:48:0,

-----------------------------------------------------------
/usr/include/c++/4.8/bits/hashtable_policy.h: In instantiation of âstruct  std::__detail::_Hash_ccode_base<std::pair<int, int>, std::pair<const std::pair<int, int>, NAMESPACE::ConfigSet>, std::__detail::_Select1st, std::hash<std::pair<int, int> >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, true>â:
/usr/include/c++/4.8/bits/unordered_map.h:100:18:   required from âclass std::unordered_map<std::pair<int, int>, RTBKIT::ConfigSet>â

怎么了?这是我的结构:

namespace MYNAMESPACE {

template<typename T>
//can pass in a list than a range for IntervalFilter
struct Span
{
    //no arg/two args not working for the template typename T
    //span(T lb, T ub);
    //span();

    T lowerBound;
    T upperBound;

    static Span
    createFromJson(const Json::Value & val); 


    void fromJson(const Json::Value & val);

    Json::Value toJson() const;

    bool empty() const;
    //didn't declare this template type, isIncluded is not used
    template<typename U> bool isIncluded(const U & value) const;

 };
 } //namespace

 #endif 

代码使用struct:      ...

 private:
    static constexpr unsigned PRIORITY = 0x1401; }
    //std::unordered_map<Span<int>, ConfigSet> data;
    std::unordered_map<std::pair<int,int>, ConfigSet> data;
    void setConfig(unsigned configIndex, const AgentConfig& config) {
         auto range = [] (int first, int last) {
         return std::make_pair(first, last);
         };
         //int l = config.rangeFilter.lowerBound;
         //int r  = configrangeFilter.upperBound;
         //data[config.rangeFilter].set(configIndex);
         data[range(config.rangeFilter.lowerBound, config.rangeFilter.upperBound)].set(configIndex);
    }

};

1 个答案:

答案 0 :(得分:1)

问题是该标准没有为hash定义std::pair专门化。编译器(间接地)告诉你它不知道如何为你的密钥生成哈希值。

您应该定义自己的哈希类并在data声明中使用它。像这样:

struct MyHash
{
  size_t operator()(std::pair<int, int> value) const
  {
    // I make no promise that this is a good hash function for your dataset.
    return value.first + value.second;
  }
};

std::unordered_map<std::pair<int, int>, ConfigSet, MyHash> data;