gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:10:14 26 4
gpt4 key购买 nike

我正在用 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,我现在发现它太旧了。

最佳答案

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

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)

关于c++ - G++ 不编译 C++0x 基于范围的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7071199/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com