[英]Extracting Values from vectors
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 ?
并且只在x坐标上进行计算吗?
You can use range-based for loops and avoid the iterators all together. 您可以将基于范围的for循环使用,并避免一起使用迭代器。
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 如果您无法使用C ++ 11,则可以在
else
块中执行以下操作
else
{
Vector const& ptA = *i;
Vector const& ptB = *j;
}
Depending on your implementation of Vector
you would then do something like 根据
Vector
的实现,您将执行类似
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. 要遍历向量,它需要一个无符号的迭代器,并且只访问其中一个元素,您必须使用(x)来访问它,其中x确定哪个元素。 in this question 0 is the x-coordinates
在这个问题中0是x坐标
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) );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.