在命令提示符下对我的 g++ (5.1.0) 编译器使用 unordered_map 显示错误

Using unordered_map on my g++ (5.1.0) compiler in command prompt shows error

我最近将 MinGW 下载到我的计算机中,但在使用某些容器和迭代器(如 unordered_map 和 auto 时,它显示意外错误。

我的代码如下:

#include <bits/stdc++.h>
#include<unordered_map>
using namespace std;


int main()
{

    unordered_map<string, int> umap; 

    umap["GeeksforGeeks"] = 10; 
    umap["Practice"] = 20; 
    umap["Contribute"] = 30; 

    for (auto x : umap) 
      cout << x.first << " " << x.second << endl; 


    return 0;
}

它给出了以下错误:


C:\Users\naima\Documents\cpp>g++ -o try2 try2.cpp
In file included from C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/unordered_map:35:0,
                 from try2.cpp:2:
C:/TDM-GCC-64/lib/gcc/x86_64-w64-mingw32/5.1.0/include/c++/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support for the \
  ^
try2.cpp: In function 'int main()':
try2.cpp:9:5: error: 'unordered_map' was not declared in this scope
     unordered_map<string, int> umap;
     ^
try2.cpp:9:25: error: expected primary-expression before ',' token
     unordered_map<string, int> umap;
                         ^
try2.cpp:9:27: error: expected primary-expression before 'int'
     unordered_map<string, int> umap;
                           ^
try2.cpp:11:5: error: 'umap' was not declared in this scope
     umap["GeeksforGeeks"] = 10;
     ^
try2.cpp:15:15: error: 'x' does not name a type
     for (auto x : umap)
               ^
try2.cpp:19:5: error: expected ';' before 'return'
     return 0;
     ^
try2.cpp:19:5: error: expected primary-expression before 'return'
try2.cpp:19:5: error: expected ';' before 'return'
try2.cpp:19:5: error: expected primary-expression before 'return'
try2.cpp:19:5: error: expected ')' before 'return'

编译器准确地告诉了你哪里出了问题。通常会。

This file requires compiler and library support for the ISO C++ 2011 standard. This
support is currently experimental, and must be enabled with the -std=c++11 or
-std=gnu++11 compiler options.

您只需使用正确的标志进行编译,-std=c++11。我不知道您是否正在与评分者使用的版本匹配或使用什么,但是很少有充分的理由使用 minGW 编译器,其中对 8 年旧标准的支持仍被认为是实验性的。

您可以在此处看到它按预期工作:https://godbolt.org/z/JQxL00 如果删除 -std=c++11 标志,它将无法编译并给出相同的错误消息。

您可能还注意到我将包含内容更改为仅包含我使用的内容。这导致更快的编译时间、更小的可执行文件和更容易理解的代码段(因为很容易看到正在使用哪些标准功能)。您还可以避免污染您的名称空间。