需要std::unordereded_map构造函数的示例

Need example of std::unordered_map constructor

本文关键字:构造函数 std unordereded 需要 map      更新时间:2023-10-16

假设我使用自己的类作为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==。即使这也可以通过模板参数进行自定义,我建议将其作为全局函数编写。