按矢量中的距离对矢量值进行排序 [英] Sorting vector values by Distance in vector
问题描述
我有两个位置,我的播放器位置(2D)和我在一个实体的向量,每个都有一个位置(2D),我想我的函数返回最近的距离,我的位置,但我不'我知道如何做,因为我被困在c#我可以只使用linq,但我正在学习c + +我的函数看起来像这样:
I have two locations, My player location (2D) and I'm looping over a vector of entitys each with a location (2D), I would like my function to return the closest distance to my location, But I don't know how to do it because I got stuck, in c# I could just use linq, But i'm learning c++ My function looks like this:
const Entity GetNearestEntity()
{
for (Entity i : fb.Entities)
{
double xDiff = (double)abs(fb.PlayerLocation.X - i.X);
double yDiff = (double)abs(fb.PlayerLocation.Y - i.Y);
//Stuck here..
//How can i get the closest object out of my vector<Entity> collection?
}
}
推荐答案
通过跟踪最近元素的索引可能更容易做到, 'for'loop like:
This may be easier to do by keeping track of the index of the closest element to you, which would be easier in a 'for' loop like:
Entity GetNearestEntity()
{
int closestEnt = 0;
double smallestDist = -1.0;
for (int i = 0; i < Entities.length(); i++)
{
double xDiff = (double)abs(fb.PlayerLocation.X - Entities[i].X);
double yDiff = (double)abs(fb.PlayerLocation.Y - Entities[i].Y);
double totalDist = sqrt(pow(xDiff, 2) + pow(yDiff, 2));
if ((totalDist < smallestDist) || (smallestDist == -1.0))
{
closestEnt = i;
smallestDist = totalDist;
}
}
return Entities[closestEnt];
}
这可能无法编译出来,和C ++一起玩,我对这是否是平方根和权力的正确方法不感兴趣。但是,它有很好的好处,只跟踪一个double和一个int,而不是一个对象。
This may not compile off the bat, it's been a while since I've played with C++, and I'm blanking on whether that's the right way to do square roots and powers. However, it has the nice benefit of only keeping track of a double and an int, instead of an object.
这篇关于按矢量中的距离对矢量值进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!