开发者

G++ doesn't compile C++0x range-based for loop

开发者 https://www.devze.com 2023-03-28 20:00 出处:网络
I was experimenting with some of the new C++0x features with G++.Lambdas, auto, and the other new features worked like a charm, but the range-based for-loop failed to compile.This is the program I was

I was experimenting with some of the new C++0x features with G++. Lambdas, auto, and the other new features worked like a charm, but the range-based for-loop failed to compile. This is the program I was testing:

#include <iostream>
#include <vector>

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

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

I compiled it with:

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

I 开发者_运维问答also tried gnu++0x, but the output was the same.

This was the output:

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

Thanks in advance for your help.

EDIT: I am using GCC version 4.5.2, which I now see is too old.


You need GCC 4.6 and above to get range-based for loops.

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)
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号