Insert works with a set, but not with an unordered_set
In the following piece of code:
#include<unordered_set>
#include<iostream>
#include<utility>
#include<string>
#include<set>
using namespace std;
int main()
{
set<pair<string, string> > g;
pair<string, string> tmp;
tmp.first="hello";
tmp.second="world";
g.insert(tmp);
}
if i change set<pair<string, string> > g;
to unordered_set<pair<string, string> > g;
i get an error when inserting a pair like:
test1.cpp:15:14: note: candidate expects 2 arguments, 1 provided
g.insert(tmp);
^
is it something on the lines "hash function cannot be defined for a pair, but only for basic datatypes"? If I am wrong, please correct me, otherwise please clarify. Thank!
+3
source to share
1 answer
There is no standard way to compute the hash on a pair. You must provide a hash function for your pair. For example for example: -
struct hash_pair {
inline std::size_t operator()(const std::pair<std::string,std::string> & p) const {
return // howsoever you want to implement.
}
};
And then declare your std :: unordered_set as: -
std::unordered_set< std::pair<std::string, std::string>, hash_pair> mySet;
+6
source to share