C++11 基于范围的 for 指针向量
我刚刚编译了 GCC 4.6.0,我想尝试一下新功能,从基于范围的 for
循环开始。
我想要更改的第一个循环是迭代指针的 std::vector
。我更改了代码以使用新语法,但它无法编译。
我尝试替换另一个 for
循环,该循环位于结构的 std::vector
上,并且它编译并运行得很好。
这是一个简短的测试代码来向您展示我的问题:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> values;
values.push_back(2);
values.push_back(5);
values.push_back(8);
values.push_back(13);
values.push_back(17);
for (int &n : values)
{
std::cout << n << "\n";
}
std::vector<int*> pointers;
pointers.push_back(new int(2));
pointers.push_back(new int(5));
pointers.push_back(new int(8));
pointers.push_back(new int(13));
pointers.push_back(new int(17));
for ((int*) &p : values)
{
std::cout << (*p) << "\n";
}
for (unsigned int i = 0; i < pointers.size(); ++i)
{
delete pointers[i];
}
return 0;
}
当我尝试编译它时(是的,我将 -std=c++0x 作为 g++ 的参数),它因以下错误而终止:
main.cpp|27|错误:在嵌套名称说明符中找到“:”,应为“::”
如果我注释掉第 27-30 行,就可以了。
我做错了什么?指针引用声明语法不对吗?
或者是否存在可以使用基于范围的 for
循环的包含类型的限制?
I have just compiled GCC 4.6.0, and I wanted to try the new features out, starting with the range-based for
loop.
The first loop I wanted to change was iterating on a std::vector
of pointers. I changed the code to use the new syntax, but it didn't compile.
I have tried to substitute another for
loop, which was on a std::vector
of structs, and it compiled and ran perfectly.
Here is a short test code to show you my problem:
#include <vector>
#include <iostream>
int main()
{
std::vector<int> values;
values.push_back(2);
values.push_back(5);
values.push_back(8);
values.push_back(13);
values.push_back(17);
for (int &n : values)
{
std::cout << n << "\n";
}
std::vector<int*> pointers;
pointers.push_back(new int(2));
pointers.push_back(new int(5));
pointers.push_back(new int(8));
pointers.push_back(new int(13));
pointers.push_back(new int(17));
for ((int*) &p : values)
{
std::cout << (*p) << "\n";
}
for (unsigned int i = 0; i < pointers.size(); ++i)
{
delete pointers[i];
}
return 0;
}
When I try to compile it (yes, I give -std=c++0x as a parameter to g++), it dies with this error:
main.cpp|27|error: found ‘:’ in nested-name-specifier, expected ‘::’
If I comment the lines 27–30 out, it's OK.
What am I doing wrong? Isn't the pointer-reference declaring syntax right?
Or is there a limitation of contained types where range-based for
loops can be used?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是错误的。
(int*)
是一个单独的表达式,因此您需要执行int*&
(没有括号,这会生成一个表达式 - 又名“不是类型名称”)至少要使其正确。我个人更喜欢使用 auto 或 auto& 。执行 :
or
or or :
您可以在通用代码中
This is wrong.
(int*)
is an expression alone, so you need to doint*&
(with no parenthesis, that makes an expression - aka "not a type name") at least to make it correct. I prefer to use auto or auto&, personally.You can do :
or
or
or in generic code:
我认为你的意思是迭代“指针”而不是“值”......
I think you meant to iterate over 'pointers' instead of 'values' there...