G ++不编译C ++ 0x基于范围的for循环

时间:2011-08-15 21:47:00

标签: c++ c++11 g++

我正在尝试使用G ++的一些新的C ++ 0x功能。 Lambdas,auto和其他新功能就像魅力一样,但基于范围的for循环无法编译。这是我正在测试的程序:

#include <iostream>
#include <vector>

int main ()
{
    std::vector<int> data = { 1, 2, 3, 4 };

    for ( int datum : data )
    {
        std::cout << datum << std::endl;
    }
}

我编译它:

g++ test.cpp -std=c++0x

我也尝试了gnu++0x,但输出结果相同。

这是输出:

test.cpp: In function ‘int main()’:
test.cpp:8:21: error: expected initializer before ‘:’ token
test.cpp:12:1: error: expected primary-expression before ‘}’ token
test.cpp:12:1: error: expected ‘;’ before ‘}’ token
test.cpp:12:1: error: expected primary-expression before ‘}’ token
test.cpp:12:1: error: expected ‘)’ before ‘}’ token
test.cpp:12:1: error: expected primary-expression before ‘}’ token
test.cpp:12:1: error: expected ‘;’ before ‘}’ token

提前感谢您的帮助。

编辑:我正在使用GCC版本4.5.2,我现在看到它太旧了。

1 个答案:

答案 0 :(得分:14)

您需要GCC 4.6及更高版本才能获得基于范围的循环。

GCC's C++0x status

$ cat for.cpp
#include <iostream>
int main()
{
  for (char c: "Hello, world!")
    std::cout << c;
  std::cout << std::endl;
  return 0;
}
$ g++ -std=c++0x -o for for.cpp
$ ./for
Hello, world!
$ g++ --version
g++ (GCC) 4.6.1 20110325 (prerelease)
相关问题