C++ - map - error: request for member 'first' in 'w', which is of non-class type 'const int'

C++ - map - error: request for member 'first' in 'w', which is of non-class type 'const int'

我正在尝试使用 C++ 中的映射作为关联容器。这个例子我是直接从C++ Primer:

复制出来的
#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;
}

当我尝试 运行 时,我得到 "error: request for member 'first' in 'w', which is of non-class type 'const int'"。 C++ Primer 的作者声称使用 GNU 4.7.0。我试过使用 minGW ( TDM-GCC-32 ) 和 Visual C++ 14。为什么我会收到这个错误?

您没有使用足够新的语言标准版本进行编译。

如果您使用 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  

(当然要看你用的是什么编译器)