Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make an unordered set of pairs of integers in C++?

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()'

like image 226
Pippi Avatar asked Mar 01 '13 15:03

Pippi


People also ask

Can we make unordered map of pair?

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.

What is unordered set in C?

(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.

Is an unordered set of a key value pair of items?

A dictionary is an unordered set of the keys, value pairs and is indexed, using the keys specified in it.


1 Answers

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.

like image 99
Sergey Kalinichenko Avatar answered Sep 19 '22 12:09

Sergey Kalinichenko