Home > other >  How can I find a minimum value from a vector of entities?
How can I find a minimum value from a vector of entities?

Time:11-28

class enemy{
    ....
}

std::vector<std::unique_ptr<enemy> > enemies1;

for (unsigned i = 0; i < 3;   i)
    enemies1.emplace_back(...);

for (int i = 0; i < enemies1.size(); i  ) {
    std::cout << i <<"x: " << enemies1[i]->rect.getPosition().x << std::endl;
}

output:

100
200
400

How could I get the minimum coordinate value from multiple enemies in the vector? I want to detect the nearest enemy from the player, eg the player's coordinate is 50 and enemies are at 100, 200, 400, as you see in the above example. I want to detect the nearest enemy in the vector.

CodePudding user response:

You can use min_element from

#include <algorithm>
#include <iostream>
#include <vector>

struct enemy_t
{
    explicit enemy_t(const double d) :
        distance{ d }
    {
    }

    double distance;
};

int main()
{
    // create a vector of enemies using the constructor with one double
    std::vector<enemy_t> enemies{ 100.0,400.0,200.0,10.0 };

    // the last argument to min_element is a lambda function 
    // it helps you define by what condition you want to find your element.
    auto enemy = std::min_element(enemies.begin(), enemies.end(), [](const enemy_t& lhs, const enemy_t& rhs)
    {
        return lhs.distance < rhs.distance;
    });

    std::cout << "The minimum distance found = " << enemy->distance << "\n";

    return 0;
}

CodePudding user response:

For finding out the minimum you can use :

auto result = std::min_element(enemies.begin(), enemies.end(), [](auto a, auto b){return a->rect.getPosition()< b->rect.getPosition();});
std::cout<<"minimum is: "<<(**result).rect.getPosition()<<std::endl;

The above example will print out the position of the closest(minimum) enemy as you want. You just need to add the above two statements into your program.

To confirm that this works(compile and gives the expected result), below i have given an example whose output can be seen here.

#include <vector>
#include <iostream>
#include <algorithm>
struct Rectangle
{
    int getPosition() const 
    {
        return position;
    }
    Rectangle(int p):position(p)
    {
        
    }
    int position = 0;
};
struct enemy 
{
    Rectangle rect;
    enemy(int p): rect{p}
    {
        
    }

};
int main()
{
    std::vector<enemy*> enemies;
    enemy e1(600),e2(200),e3(400),e4(300), e5(100);
    enemies.push_back(&e1);
    enemies.push_back(&e2);
    enemies.push_back(&e3);
    enemies.push_back(&e4);
    enemies.push_back(&e5);
    
    auto result = std::min_element(enemies.begin(), enemies.end(), [](auto a, auto b){return a->rect.getPosition()< b->rect.getPosition();});
    std::cout<<"minimum is: "<<(**result).rect.getPosition()<<std::endl;
    return 0;
}

  • Related