C++ - 地图 - 错误:'W',这是非类类型'const int'的成员'第一'的请求

问题描述:

我想在C++中使用地图作为关联容器。我复制这个例子中,直接出C++ PrimerC++ - 地图 - 错误:'W',这是非类类型'const int'的成员'第一'的请求

#include <stdio.h> 
#include <iostream> 
#include <string> 
#include <map> 

using namespace std; 

int main() 
{ 
    map<string, size_t> word_count; 
    string word; 

    while (cin >> word) 
     ++word_count[word]; 
    for (const auto &w : word_count) 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 

    return 0; 
} 

当我尝试和运行它,我得到“错误:请求成员‘第一’在‘W’,这是无级式‘const int的’的”。 C++ Primer的作者称为使用GNU 4.7.0。我试过使用minGW(TDM-GCC-32)和Visual C++ 14.为什么我得到这个错误?

+2

无法重现。请提供真实的代码。 – SergeyA

+2

此编译在[Coliru](http://coliru.stacked-crooked.com/)与GCC和Clang。 – chris

+3

确保您的编译器设置为C++ 11模式。 –

您没有编译一个足够新的语言标准版本。

如果你有发言权编译,C++ 98,你会看到以下内容:

g++ -std=c++98 -o main a.cpp                              1 
a.cpp: In function ‘int main()’: 
a.cpp:15:22: error: ISO C++ forbids declaration of ‘w’ with no type [-fpermissive] 
    for (const auto &w : word_count) 
        ^
a.cpp:15:26: warning: range-based ‘for’ loops only available with -std=c++11 or -std=gnu++11 
    for (const auto &w : word_count) 
         ^
a.cpp:16:19: error: request for member ‘first’ in ‘w’, which is of non-class type ‘const int’ 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 
       ^
a.cpp:16:44: error: request for member ‘second’ in ‘w’, which is of non-class type ‘const int’ 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 
              ^
a.cpp:16:58: error: request for member ‘second’ in ‘w’, which is of non-class type ‘const int’ 
     cout << w.first << " occurs " << w.second << ((w.second > 1) ? " times" : " time") << endl; 

这在C++ 11推出range-based for loop到期。
尝试编译:

g++ -std=c++11 -o main a.cpp 

(当然这取决于你使用的编译器)