假设我使用自己的类作为std::unordered_map的键
class MyClass {
public:
int a, b;
}www.cplusplus.com列出了以下可以使用的构造函数:
explicit unordered_map ( size_type n,
const hasher& hf = hasher(),
const key_equal& eql = key_equal(),
const allocator_type& alloc = allocator_type() );您能举例说明如何使用上述构造函数并填充所有参数来构造我的std::unordered_map<MyClass, std::string>吗
发布于 2013-03-25 01:39:17
有一些three std::unordered_map constructors将散列和相等函数器的实例作为参数。此示例说明如何使用其中一种方法:
struct MyHash {
std::size_t operator()(const MyClass& k) const { .... }
};
struct MyEqual {
bool operator()(const MyClass& lhs, const MyClass& rhs) const { .... }
};
std::unordered_map<MyClass, std::string, MyHash, MyEqual> m(42, // bucket count
MyHash(),
MyEqual());发布于 2013-03-25 01:26:09
编写一个能够在unordered_map中用作键的类并不是免费的,他们需要一个自定义的散列对象来实现这一点。
struct MyHash {
std::size_t operator()(const MyClass& k) const
{
// You may want to use a better hash function
return static_cast<std::size_t>(k.a) ^ static_cast<std::size_t>(k.b);
}
}; 然后,将散列函数作为模板参数传递给map (它使用默认构造函数构造散列对象,因此不需要手动传递):
std::unordered_map<MyClass, std::string, MyHash> m;或者,您可以在std名称空间中提供散列函数。
namespace std {
template <>
struct hash<MyClass> {
std::size_t operator()(const MyClass& k) const; // same as before
};
}现在,它完全如预期的那样:
std::unordered_map<MyClass, std::string> m;除了对unordered_map的特殊要求之外,您还需要定义一个operator==。即使这也可以通过模板参数进行自定义,我也建议将其编写为全局函数。
https://stackoverflow.com/questions/15601568
复制相似问题