迭代向量的所有成员
我有两个 struct 定义如下:
struct vertex
{
double x;
double y;
double z;
};
struct finalVertex
{
int n;
vertex v;
};
我使用以下代码迭代列表并打印所有成员:
vector<finalVertex> finalVertices;
vector<finalVertex>::iterator ve;
for ( ve = finalVertices.begin(); ve < finalVertices.end(); ve++ )
{
out << *(ve).v.x << *(ve).v.y << *(ve).v.z << endl;
}
我收到以下错误代码:
main.cpp:651: 错误:'class __gnu_cxx::__normal_iterator > >'没有 名为“v”的成员
访问集合元素的语法上正确的方法是什么?
I have two struct
s defined as in the following:
struct vertex
{
double x;
double y;
double z;
};
struct finalVertex
{
int n;
vertex v;
};
I use the following code to iterate through the list and print all the members:
vector<finalVertex> finalVertices;
vector<finalVertex>::iterator ve;
for ( ve = finalVertices.begin(); ve < finalVertices.end(); ve++ )
{
out << *(ve).v.x << *(ve).v.y << *(ve).v.z << endl;
}
I receive the following code of error:
main.cpp:651: error: 'class __gnu_cxx::__normal_iterator > >' has no
member named 'v'
What is the syntactically correct way of accessing the elements of the set?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
问题在于运算符优先级:编写
(*ve).vx
或更简单的ve->vx
。除此之外,我建议您重写
vertex
结构的operator <<
,以使代码更具可读性:然后像这样使用它:
The problem is operator precedence: write
(*ve).v.x
or simpler,ve->v.x
.Apart from that, I would advise you to override
operator <<
for yourvertex
structure to make your code vastly more readable:and then use it like this:
你应该做的是:
你也可以做的是:
但这很糟糕。 :)
What you should do is:
What you can also do is:
but it sucks. :)
您的
*(ve).vx
相当于*((ve).vx)
。您可能想要:或者:
另外,您的循环效率并不高。不需要每次迭代都调用 end() ,并且迭代器的后增量可能比普通指针/整数重得多,因此您应该尽可能习惯使用预增量:
Your
*(ve).v.x
is equivalent to*((ve).v.x)
. You probably want:Or:
Also, your loop isn't as efficient as it could be. Calling
end()
every iteration isn't needed, and post-increment can be a lot heavier with iterators than plain pointers/integers so you should get used to using pre-increment when possible:将取消引用移到括号内,如下所示:
我还建议更改
ve
ve < FinalVertices.end();
到ve != FinalVertices.end();
。Move your dereference to inside the parens, like so:
I'd also suggest changing
ve < finalVertices.end();
tove != finalVertices.end();
.你不应该写
已经< FinalVertices.end()
你必须写
ve != FinalVertices.end()
You should not write
ve < finalVertices.end()
you must write
ve != finalVertices.end()