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

51,885

Solution 1

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;
}

Solution 2

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.

Solution 3

You can't execute arbitrary expressions at global scope, so you should put

mymap.reserve(7000);

inside main.

This is also true for other STL containers like map and vector.

Share:
51,885
user788171
Author by

user788171

Updated on January 09, 2020

Comments

  • user788171
    user788171 over 4 years

    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'
    
  • Jonathan Wakely
    Jonathan Wakely about 11 years
    For GCC 4.6.2 that should be -std=c++0x
  • gongzhitaao
    gongzhitaao about 11 years
    @JonathanWakely Thanks. I forgot to mention my g++ version
  • user788171
    user788171 about 11 years
    Ah yes, stupid error, the reserve statement has to be inside main() and I do need to compile with the -std=c++0x flag for gcc 4.6.2. Unfortunately, I'm having some difficulties still with unordered_map, I am getting: error: 'class std::tr1::unordered_map<std::basic_string<char>, int>' has no member named 'reserve'
  • gongzhitaao
    gongzhitaao about 11 years
    @user788171 See here: en.cppreference.com/w/cpp/container/unordered_map/reserve. The reserve method is new in c++11. So either update your gcc or try other way around :)
  • user788171
    user788171 about 11 years
    The solution is to use the std=c++0x and remove the tr1/ in the include.
  • GeekyCoder
    GeekyCoder over 4 years
    this should be the correct answer... not the chosen one.