首页 > 实在查不到解决方法了,请大家帮忙解惑,编译器是vs2010

实在查不到解决方法了,请大家帮忙解惑,编译器是vs2010

实在查不到解决方法了,请大家帮忙解惑,编译器是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”


确定vs2010支持这个特性吗,g++ 4.9.2是没问题的,要不换vs2012试试吧。


将:

cppfor (const auto &w : word_count)
{
    cout << w.first << "occurs" << w.second << ((w.second > 1) ? " times" : " time") << endl;
}

改为:

cppfor (auto w = word_count.cbegin(); w != word_count.cend(); ++w)
{
    cout << w->first << " occurs " << w->second << ((w->second > 1) ? " times" : " time") << endl;
}

即可。

原因:range for loop 是 C++ 11 里才出现的,VS2010 不支持该特性。


这个程序看起来是 《C++ Primer 5th》 里的,这本书要求编译器起码支持 C++ 11,而 VS 2010 是显然不符合的。请您换 VS 2012 以上版本,或直接使用 GCC 4.8+、Clang 3.4+ 等编译器。


问题可能是你现在的编译器不支持新的c++的版本。换新的vs2012可以,如果嫌麻烦,可以试一试dev C++。可以改编译参数,—std=c++11 或-std=c++14。

【热门文章】
【热门文章】