The following program does not compile an unordered set of pairs of integers, but it does for integers. Can unordered_set
and its member functions be used on user-defined types, and how can I define it?
#include <unordered_set> ... class A{ ... private: std::unordered_set< std::pair<int, int> > u_edge_; };
Compiler error:
error: no matching function for call to 'std::unordered_set >::unordered_set()'
How to create an unordered_map of pairs in C++? Unordered Map does not contain a hash function for a pair like it has for int, string, etc, So if we want to hash a pair then we have to explicitly provide it with a hash function that can hash a pair. unordered_map can takes upto 5 arguments: Key : Type of key values.
(since C++17) Unordered set is an associative container that contains a set of unique objects of type Key. Search, insertion, and removal have average constant-time complexity. Internally, the elements are not sorted in any particular order, but organized into buckets.
A dictionary is an unordered set of the keys, value pairs and is indexed, using the keys specified in it.
There is no standard way of computing a hash on a pair. Add this definition to your file:
struct pair_hash { inline std::size_t operator()(const std::pair<int,int> & v) const { return v.first*31+v.second; } };
Now you can use it like this:
std::unordered_set< std::pair<int, int>, pair_hash> u_edge_;
This works, because pair<T1,T2>
defines equality. For custom classes that do not provide a way to test equality you may need to provide a separate function to test if two instances are equal to each other.
Of course this solution is limited to a pair of two integers. Here is a link to an answer that helps you define a more general way of making hash for multiple objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With