在':'标记之前的预期初始化程序

时间:2018-05-01 02:37:55

标签: c++

我的代码如下所示:

#include <vector>
#include <iostream>
#include <map>
using namespace std;

    int main()
    {
     std::map<int, std::vector<int> > map;
     map[1].push_back(5);
     map[1].push_back(3);
     map[3].push_back(2);
     map[2].push_back(1);
     map[1].push_back(-1);
     map[3].push_back(2);

     int sum2 = 0;
     for (const pair<int, vector<int> >& index_vec : map) 
      {
        int sum = 0;
         for (int elem : index_vec.second) 
        { 
            sum += elem; 
        }
        sum2 += sum*sum;
         cout << "index " << index_vec.first << ": " << sum << endl;
      }
    cout << "sum_2: " << sum2 << endl; 
    return 0;
    };

在我的笔记本电脑上工作正常,但在使用桌面时会出现以下错误:

map.cpp: In function ‘int main()’:
map.cpp:17: error: expected initializer before ‘:’ token
map.cpp:29: error: expected primary-expression at end of input
map.cpp:29: error: expected ‘;’ at end of input
map.cpp:29: error: expected primary-expression at end of input
map.cpp:29: error: expected ‘)’ at end of input
map.cpp:29: error: expected statement at end of input
map.cpp:29: error: expected ‘}’ at end of input

输出应为:

index 1: 7
index 2: 1
index 3: 4
sum_2: 66

我的笔记本电脑正如预期的那样。我完全不知道,能不能帮我解决一下?

1 个答案:

答案 0 :(得分:2)

您的代码无需任何修改即可使用。请检查您的编译器。您将需要一个C ++ 11编译器。如果你使用g ++,就像这样:

g++ -std=c++11 A.cpp

https://gcc.gnu.org/projects/cxx-status.html#cxx11。你需要至少4.7。请更新您的古老编译器。