C++ 错误:“unordered_map”未命名类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15733163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:42:54  来源:igfitidea点击:

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

c++typesunordered-map

提问by user788171

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

EDIT2:正如下面所指出的,reserve 必须进入 main,我需要用 flag 编译

-std=c++0x

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

但是,似乎仍然存在与 unordered_map 相关的错误,即:

error: 'class std::tr1::unordered_map<std::basic_string<char>, int>' has no member named 'reserve'

回答by gongzhitaao

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

编译g++ -std=c++11(我的 gcc 版本是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;
}

回答by BarelyEthical

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.

如果您想支持<unordered_map>早于 c++11 的版本,请使用
#include<tr1/unordered_map>并以以下形式声明您的地图:-std::tr1::unordered_map<type1, type2> mymap
这将使用技术报告 1 扩展名以实现向后兼容性。

回答by taocp

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

你不能execute arbitrary expressions at global scope,所以你应该把

mymap.reserve(7000);

inside main.

里面主要。

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

这也适用于其他 STL 容器,如 map 和 vector。