user3543006
user3543006

Reputation: 83

Why do I get a compilation error when using the emplace method for unordered_map?

#include <string>
#include <unordered_map>

using namespace std;

....
....
unordered_map<char, int> hashtable;
string str = "hello";
char lower = tolower(str[0]);
hashtable.emplace(lower, 1);
....

returns the following compilation errors:

1   error C2780: 'std::pair<_Ty1,_Ty2> std::_Hash<_Traits>::emplace(_Valty &&)' : expects 1 arguments - 2 provided  
2   IntelliSense: no instance of function template "std::tr1::unordered_map<_Kty, _Ty, _Hasher, _Keyeq, _Alloc>::emplace [with _Kty=char, _Ty=int, _Hasher=std::hash<char>, _Keyeq=std::equal_to<char>, _Alloc=std::allocator<std::pair<const char, int>>]" matches the argument list

Upvotes: 0

Views: 1327

Answers (2)

rauzan
rauzan

Reputation: 51

Following some extensions which could fix your issue

#include <utility> // for std::pair
std::unordered_map<char, int> hashtable;
char lower = 'A';
hashtable.emplace(std::pair<char, int>(lower, 1));

If your pasted code compiles seems to be depending on the underlying compiler. Handling to emplace a std::pair works for e.g. c++11--according to the spec (e.g. cplusplus.com) your code snippet should work with c++14.

Upvotes: 1

Christian Hackl
Christian Hackl

Reputation: 27548

You are using an old version of Visual C++ which did not correctly support emplace. Probably Visual C++ 2010.

As the Visual C++ Team Blog once said:

As required by C++11, we've implemented emplace()/emplace_front()/emplace_back()/emplace_hint()/emplace_after() in all containers for "arbitrary" numbers of arguments (see below).

(...)

VC10 supported emplacement from 1 argument, which was not especially useful.

The best solution would be to upgrade to the latest version of the compiler.

Upvotes: 2

Related Questions