Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error: 'unordered_map' does not name a type

I am doing everything correctly as far as I can tell and I have gotten the error message:

error: 'unordered_map' does not name a type
error: 'mymap' does not name a type

In my code, I have:

#include <unordered_map>

using namespace std;

//global variable
unordered_map<string,int> mymap;
mymap.reserve(7000);

void main {
  return;
}

I don't see what can be missing here....

EDIT: when I update my declaration to

std::tr1::unordered_map<string,int> mymap;

I an able to eliminate the first error, but when I try to reserve, I still get the second error message.

EDIT2: As pointed out below, reserve must go into main and I need to compile with flag

-std=c++0x

However, there still appear to be errors related to unordered_map, namely:

error: 'class std::tr1::unordered_map<std::basic_string<char>, int>' has no member named 'reserve'
like image 550
user788171 Avatar asked Mar 31 '13 18:03

user788171


People also ask

Is unordered_map initialized with 0?

The value object is value-initialized, not zero-initialized.

What does unordered_map return if key not found?

Note that while unordered_map::at() will throw if the key is not found, unordered_map::find() returns an invalid iterator ( unordered_map::end() ) - so you can avoid handling exceptions this way.

Can we use string in unordered_map?

So the bottom line is - make sure you have a #include <string> if you're trying to use strings in an unordered_map<> - actually, any time you're using std::string . Unfortunately, the compiler will sometimes let you get away without the include because of side effects from other includes.


2 Answers

Compile with g++ -std=c++11 (my gcc version is gcc 4.7.2) AND

#include <unordered_map>
#include <string>

using namespace std;

//global variable
unordered_map<string,int> mymap;

int main() {
  mymap.reserve(7000); // <-- try putting it here
  return 0;
}
like image 71
gongzhitaao Avatar answered Oct 12 '22 13:10

gongzhitaao


If you want to support <unordered_map> for versions older than c++11 use
#include<tr1/unordered_map> and declare your maps in the form :- std::tr1::unordered_map<type1, type2> mymap
which will use the technical report 1 extension for backward compatibility.

like image 24
BarelyEthical Avatar answered Oct 12 '22 13:10

BarelyEthical