为什么以下代码适用于在线ide(gcc 7.2.0)但在ubuntu上出错?

时间:2017-08-18 02:29:26

标签: c++ ubuntu gcc

当我在ubuntu上运行以下代码时(gcc(Ubuntu 5.4.0-6ubuntu1~16.04.4)):

#include<iostream>
#include<vector>
#include<list>
using namespace std;
int main(){
vector <int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
v.push_back(4);
v.push_back(5);
list<int> temp;
for(auto i:v){
    cout<<i<<" ";
    temp.push_back(i);
}
for(auto i:temp){
    cout<<i<<" ";
}
}


我收到以下错误:

try.cpp: In function ‘int main()’:
try.cpp:13:10: error: ‘i’ does not name a type
 for(auto i:v){
          ^
try.cpp:17:1: error: expected ‘;’ before ‘for’
 for(auto i:temp){
 ^
try.cpp:17:1: error: expected primary-expression before ‘for’
try.cpp:17:1: error: expected ‘;’ before ‘for’
try.cpp:17:1: error: expected primary-expression before ‘for’
try.cpp:17:1: error: expected ‘)’ before ‘for’
try.cpp:17:10: error: ‘i’ does not name a type
 for(auto i:temp){
          ^
try.cpp:20:1: error: expected ‘;’ before ‘}’ token
 }
 ^
try.cpp:20:1: error: expected primary-expression before ‘}’ token
try.cpp:20:1: error: expected ‘;’ before ‘}’ token
try.cpp:20:1: error: expected primary-expression before ‘}’ token
try.cpp:20:1: error: expected ‘)’ before ‘}’ token
try.cpp:20:1: error: expected primary-expression before ‘}’ token


但是当我在网上运行代码时,我的工作正常 代码有什么问题?
在线ide的代码链接:No errors


1 个答案:

答案 0 :(得分:3)

您的代码使用了一些C ++ 11功能,例如range based loopsauto specifier,但您不需要编译C ++ 11标准。您需要通过在编译时包含-std=c++11标志来启用C ++ 11支持:

g++ -std=c++11 -o try try.cpp

在线编译器使用-std=gnu++1z标志启用了此功能。