Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through all the members of a vector

I have two structs 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?

like image 925
R.J. Avatar asked Dec 03 '22 01:12

R.J.


1 Answers

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;
like image 147
Konrad Rudolph Avatar answered Dec 08 '22 00:12

Konrad Rudolph