gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:09:56 24 4
gpt4 key购买 nike

我在我的项目中使用结构,它有一个 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

代码使用结构: ...

 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);
}

};

最佳答案

问题在于标准没有为 std::pair 定义 hash 特化。编译器(间接地)告诉您它不知道如何为您的键生成哈希值。

您应该定义自己的哈希类并在您的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;

关于c++ - 如何正确使用 struct/std::pair?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43442982/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com