Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I've declare a vector like this:

C++
Vector<Point> vec(3);
for(Vector<Point>::iterator i=vec.begin(); i<vec.end(); i++){}


And I want to read the (x,y) elements of each point, How can I do it?
Posted

1 solution

Assuming x and y are accessible as members of your Point type,
C++
for (Vector<point>::iterator i = vec.begin(); i != vec.end(); ++i) // srsly, what's with the post-incr in ALL code??
{
    int x = i->x; // or whatever type it is
    // do stuff
}
</point>


If your compiler supports the C++11 range-based for, this could become
C++
for (Point const &p: vec) // or non-const, or by value, whatever
{
    // do stuff with p.x and p.y
}


Or using <algorithm> and C++11 lambda's:
C++
std::for_each(vec.begin(), vec.end(), [&]
(Point const &p) 
{
    // do stuff with p.x and p.y
});
 
Share this answer
 
Comments
CPallini 16-Jun-14 9:33am    
5. You may also use auto in the C++11 for range-loop.
Joren Heit 16-Jun-14 13:36pm    
Of course, but I tend to avoid auto outside complicated templates and/or very long nested types like iterators. Point is short enough to be written out explicitly :-)
Legor 17-Jun-14 5:59am    
Nice answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900