C ++ unordered_map causing a compile-time error

I have the following:

#include<iostream> #include<unordered_map> #include<tuple> using namespace std; class CTest { // Properties public: unordered_map<const string, tuple<int, int> > Layout; // Methods public: CTest (); ~CTest (); }; CTest::CTest () { Layout["XYZ"] = make_tuple (0, 1); } CTest::~CTest () { // Do nothing } int main (int argc, char *argv[]) { CTest Test; return 0; } 

Compiling this simple program gives the following error:

error C2678: binary '==': operator not found that accepts a left operand of type 'const std :: string' (or not an acceptable conversion)

I am using Visual Studio 2010 Professional on Windows 7.

+4
source share
4 answers

In addition to changing the Layout to:

 unordered_map<string, tuple<int, int> > Layout; 

as pointed out by Johan and Benjamin, you also need #include <string> .

Notice I don’t understand why changing Layout is required, even if const is redundant.

+3
source

You need to remove the const qualifier on the key.

 unordered_map<const string, tuple<int, int> > Layout; 

in

 unordered_map<string, tuple<int, int> > Layout; 

this is because the keys are always const, according to this answer:

Using const key for unordered_map

I believe the main reason is related to the Duplicate attribute const, resolved in C, but not in C ++?

Also, as other posts pointed out, you might need to include a line (although with gcc it seems to come with iostream)

+2
source

As stated, the reason for your initial error was that you had to include <string> . However, you may have another problem:

 unordered_map<const string, tuple<int, int> > Layout; 

You (possibly) need to remove const from this line:

 unordered_map<string, tuple<int, int> > Layout; 

It may not be necessary on your compiler, but it is on mine. First of all, const is redundant, map / unordered_map keys are const any, but that is not a problem. The problem is that the hash function template does not work for const types.

The following simple program isolates the problem for me:

 #include <functional> int main (int argc, char *argv[]) { std::hash<const int> h; h(10); } 

http://ideone.com/k2vSy

 undefined reference to `std::hash<int const>::operator()(int) const' 

I cannot explain this at the moment.

+1
source

Visual Studio 2010 will compile your source code just like you would #include <string> so that it has benchmarks for string .

As other posters mention, you should also make your key a regular string , not a const string , since this is in accordance with the STL standard, but it is not absolutely necessary for VS 2010 to compile the source above.

+1
source

Source: https://habr.com/ru/post/1391320/


All Articles