Iterating through all the members of a vector
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 开发者_JAVA技巧correct way of accessing the elements of the set?
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 your vertex
structure to make your code vastly more readable:
std::ostream& operator <<(std::ostream& out, vertex const& value) {
return out << value.x << " " << value.y << " " << value.z;
}
and then use it like this:
for ( ve = finalVertices.begin(); ve != finalVertices.end(); ve++ )
out << ve->v << endl;
What you should do is:
ve->v.x
What you can also do is:
(*ve).v.x
but it sucks. :)
out << *(ve).v.x << *(ve).v.y << *(ve).v.z << endl;
Your *(ve).v.x
is equivalent to *((ve).v.x)
. You probably want:
out << (*ve).v.x << (*ve).v.y << (*ve).v.z << endl;
Or:
out << ve->v.x << ve->v.y << ve->v.z << endl;
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:
for ( ve = finalVertices.begin(), end = finalVertices.end(); ve != end; ++ve )
Move your dereference to inside the parens, like so:
out << (*ve).v.x << (*ve).v.y << (*ve).v.z << endl;
I'd also suggest changing ve < finalVertices.end();
to ve != finalVertices.end();
.
for ( ve = finalVertices.begin(); ve != finalVertices.end(); ++ve )
{
ve->v.x;
}
You should not write ve < finalVertices.end() you must write ve != finalVertices.end()
精彩评论