简体   繁体   English

如何从实体向量中找到最小值?

[英]How can I find a minimum value from a vector of entities?

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: 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.我想检测离玩家最近的敌人,例如玩家的坐标是 50,敌人在 100、200、400,正如你在上面的例子中看到的。 I want to detect the nearest enemy in the vector.我想检测向量中最近的敌人。

You can use min_element from您可以使用 min_element 从

#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;
}

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.上面的示例将根据需要打印出最近(最小) enemy的 position。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM