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?
}
}
help appreciated!
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:
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.