Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert works with set but not with unordered_set

Tags:

c++

c++11

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 the error while inserting the pair, like:

test1.cpp:15:14: note:   candidate expects 2 arguments, 1 provided
  g.insert(tmp);
              ^

is it something on the lines of "hash function can't be defined for a pair but only for basic data types"? If I'm wrong please correct me, else elaborate it. Thanks!

like image 358
theharshest Avatar asked Jan 10 '23 04:01

theharshest


1 Answers

There is no standard way of computing a hash on a pair. You should provide hash function for your pair. For e.g:-

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;
like image 80
ravi Avatar answered Jan 18 '23 22:01

ravi