从矢量中提取值
问题描述:
我想从矢量中提取一组点并对它们进行计算。这些点存储像从矢量中提取值
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));
我不能通过它循环,因为我用数组并获得我想要的值。我的代码看起来像:
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 ???
}
}
}
我如何提取点?并只做x坐标计算?
答
您可以使用range-based for loops并避免迭代器在一起。
for (auto const& ptA : points)
{
for (auto const& ptB : points)
{
if (&ptA == &ptB)
{
continue;
}
else
{
// directly use ptA and ptB
}
}
}
如果您不能使用C++ 11,你可以做你的else
块
else
{
Vector const& ptA = *i;
Vector const& ptB = *j;
}
以下根据您的实现的Vector
那么你会做这样的事情
double width = ptA.x - ptB.x;
+0
'如果你不能使用C++ 11'你可以使用任何东西从答案 – 2014-11-20 19:08:27
+0
对不起,错过'你的else块' – 2014-11-20 19:12:54
答
我想通了。所以我将写只是一个简单的例子
for(unsigned int i = 0 ; i<points.size() ; i++)
{
temp = points[i](0);
}
遍历它需要一个无符号的迭代器的载体,并访问只u有与(X)来访问它,其中x确定哪些元素中的元素中的一个。在这个问题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));
}
你的循环顺便说一句p? – Jake0x32 2014-11-20 19:02:34
抱歉没有p,我编辑了它 – 2014-11-20 19:05:00
@NarekMinaskan - 您的目标只是为了获得'x'坐标并对它们做些什么? – PaulMcKenzie 2014-11-20 19:09:01