需要std::unordereded_map构造函数的示例
Need example of std::unordered_map constructor
假设我使用自己的类作为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>
而填充的所有参数吗?
有三个std::unordered_map构造函数,它们将散列和等式函子的实例作为参数。这个例子展示了如何使用其中一个:
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());
编写一个能够在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);
}
};
然后,将散列函数作为模板参数传递给映射(它使用默认构造函数构造散列对象,因此不需要手动传递(:
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==
。即使这也可以通过模板参数进行自定义,我建议将其作为全局函数编写。
相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 初始化具有非默认构造函数的std::数组项的更好方法
- 编译器如何区分std::vector的构造函数
- 为什么std::vector和std::valarray初始化构造函数不同
- std::make_shared和protected/private构造函数
- std::vector::p ush_back() 不会在 MSVC 上编译具有已删除移动构造函数的对象
- 仅包含可移动 std::map 的类的移动构造函数不起作用
- std::ofstream 作为类成员删除复制构造函数?
- std::string 构造函数如何处理固定大小的 char[]?
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- 在构造函数中使用可变参数初始化 std::tuple
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 为什么 std::memmove 中联合的默认非平凡移动构造函数C++?
- 如何在构造函数参数中初始化"std::set"?
- 如何为 std::vector 分配内存,然后稍后为某些元素调用构造函数?
- 创建一个没有复制构造函数的类的 std::vector 的 std::vector
- 构造函数采用std::string_view与std::string并移动
- 通过模板构造函数(std ::功能和迷你案例)将构造函数触发
- 没有构造函数 std::istream_iterator 的实例
- 在placement构造函数std::vector中