I am trying to extract a set of points from a vector and do computation on them. The points are stored like
std::vector<Vector> m_points1;
m_points1.push_back(Vector( -4.0, 8.0));
m_points1.push_back(Vector( -1.0, -7.0));
m_points1.push_back(Vector( 0.0, -8.0));
m_points1.push_back(Vector( 2.0, -4.0));
m_points1.push_back(Vector( 3.0, 1.0));
I can't loop through it as I used to do with arrays and get the values I want. My code looks likes:
for(std::vector<Vector>::iterator i=points.begin();i != points.end();i++)
{
k=i;
for(std::vector<Vector>::iterator j=points.begin();j != points.end();j++)
{
if(k==j)
{
continue;
}
else
{
//How to get values ???
}
}
}
How can i extract the points? and do computations on only x coordinates ?
You can use range-based for loops and avoid the iterators all together.
for (auto const& ptA : points)
{
for (auto const& ptB : points)
{
if (&ptA == &ptB)
{
continue;
}
else
{
// directly use ptA and ptB
}
}
}
If you are unable to use C++11, you can do the following in your else
block
else
{
Vector const& ptA = *i;
Vector const& ptB = *j;
}
Depending on your implementation of Vector
you would then do something like
double width = ptA.x - ptB.x;
I figured it out. So i will write just a simple example
for(unsigned int i = 0 ; i<points.size() ; i++)
{
temp = points[i](0);
}
to loop through a vector it needed an unsigned iterator, and to access just one of the elements u have to access it with (x) where x determines which element. in this question 0 is the x-coordinates
else
{
// do wathever you want using
// i->x
// i->y
// j->x
// j->y
float dist = sqrt( (i->x-j->x)*(i->x-j->x)
+ (i->y-j->y)*(i->y-j->y) );
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.