实在查不到解决方法了,请大家帮忙解惑,编译器是vs2010
#include <iostream>
#include <map>
#include <string>
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;
}
d:\avs\amfc\32\32\main.cpp(12): error C2143: 语法错误 : 缺少“,”(在“:”的前面)
1>d:\avs\amfc\32\32\main.cpp(12): error C2734: “w”: 如果不是外部的,则必须初始化常量对象
1>d:\avs\amfc\32\32\main.cpp(12): error C3531: “w”: 类型包含“auto”的符号必须具有初始值设定项
1>d:\avs\amfc\32\32\main.cpp(13): error C2143: 语法错误 : 缺少“;”(在“{”的前面)
1>d:\avs\amfc\32\32\main.cpp(14): error C2228: “.first”的左边必须有类/结构/联合
1> 类型是“int”
1>d:\avs\amfc\32\32\main.cpp(14): error C2228: “.second”的左边必须有类/结构/联合
1> 类型是“int”
1>d:\avs\amfc\32\32\main.cpp(14): error C2228: “.second”的左边必须有类/结构/联合
1> 类型是“int”
PHP中文网2017-04-17 11:51:38
will:
cpp
for (const auto &w : word_count) { cout << w.first << "occurs" << w.second << ((w.second > 1) ? " times" : " time") << endl; }
changed to:
cpp
for (auto w = word_count.cbegin(); w != word_count.cend(); ++w) { cout << w->first << " occurs " << w->second << ((w->second > 1) ? " times" : " time") << endl; }
That’s it.
Reason: range for loop only appeared in C++ 11, and VS2010 does not support this feature.
This program looks like it is from "C++ Primer 5th". This book requires the compiler to support at least C++ 11, and VS 2010 is obviously not compliant. Please change to VS 2012 or above, or use GCC 4.8+, Clang 3.4+ and other compilers directly.
黄舟2017-04-17 11:51:38
Are you sure vs2010 supports this feature? There is no problem with g++ 4.9.2. Why not try it with vs2012?
阿神2017-04-17 11:51:38
The problem may be that your current compiler does not support the new c++ version. You can change to the new vs2012. If you find it troublesome, you can try dev C++. You can change the compilation parameters, -std=c++11 or -std=c++14.