Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compilation error related to map and unordered_map: "attempting to reference a deleted function"

Tags:

c++

c++11

I want to use map in C++ STL to create assosiation between vector and int. But I got multiple compilation error with code presented below:

#include <vector>
#include <map>
#include <unordered_map>

using namespace std;

int main(void)
{
    unordered_map<vector<char>, int> mp;
    return 0;
}

And got this compilation error in VC++:

error C2280: 'std::hash<_Kty>::hash(const std::hash<_Kty> &)': attempting to reference a deleted function

However, if I change my code like presented below, then the code can be compiled properly:

#include <vector>
#include <map>
#include <unordered_map>

using namespace std;

int main(void)
{
    map<vector<char>, int> mp;
    return 0;
}

I have found this question asked in StackoverFlow, whose title is: C++ unordered_map using a custom class type as the key. But I wondered that why using map<> can pass the compilation check but unable with unordered_map<> ?

like image 748
FS.L Avatar asked Jul 07 '18 05:07

FS.L


1 Answers

map requires that less-than comparison is implemented. Which it is, for a vector. But unordered_map requires a hash function, which you'll need to implement yourself. It's not a big deal, you can see how to use hash_combine to do that here: Fast hash function for `std::vector`

like image 161
John Zwinck Avatar answered Sep 22 '22 00:09

John Zwinck