如何检查 unique_ptr 是否指向这个

how to check if unique_ptr points to this

为了遵循代码的和平,我试图找到另一个与 this 具有相同坐标的对象。如何正确操作?

        auto& organism_vector = world->get_vector();
        auto attacked_organism = find_if(begin(organism_vector), end(organism_vector), [this](const unique_ptr<Organism>& attacked_organism)
            {
                return this->get_coordinates() == attacked_organism->get_coordinates() && *this != *attacked_organism;
            });

还有一点,当我好不容易拿到这个iterator时,如何引用attacked_organism class方法?

*attacked_organism.get_coordinates();

*this != *attacked_organism改为this != attacked_organism.get():

auto& organism_vector = world->get_vector();
auto attacked_organism = find_if(begin(organism_vector), end(organism_vector),
    [this](const unique_ptr<Organism>& attacked_organism)
    {
        return this->get_coordinates() == attacked_organism->get_coordinates() && this != attacked_organism.get();
    }
);

一旦你有了 find_if() returns 的 iterator (并且在你验证它不是 end 迭代器之后),你可以在 Organism 首先取消引用迭代器以访问持有 Organism* 指针的 unique_ptr,然后取消引用 unique_ptr 以访问 Organism 本身:

auto attacked_organism = find_if(...);
if (attacked_organism != end(organism_vector))
{
    (**attacked_organism).get_coordinates();
    or:
    (*attacked_organism)->get_coordinates();
    ...
}

附带说明:我不建议为您的迭代器变量提供与 lambda 参数相同的名称。这只会让事情变得难以阅读。 lambda试图找到一个Organism进行攻击,但它还没有真正被攻击过,所以你应该更恰当地命名lambda参数,例如:

auto attacked_organism = find_if(begin(organism_vector), end(organism_vector),
    [this](const unique_ptr<Organism>& candidate_organism)
    {
        return this->get_coordinates() == candidate_organism->get_coordinates() && this != candidate_organism.get();
    }
);

就此而言,我也不建议将迭代器命名为 attacked_organism。它不是实际的 Organism,它是 Organismiterator,所以更像这样的内容会更具可读性:

auto& organism_vector = world->get_vector();
auto found_iterator = find_if(begin(organism_vector), end(organism_vector),
    [this](const unique_ptr<Organism>& candidate_organism)
    {
        return this->get_coordinates() == candidate_organism->get_coordinates() && this != candidate_organism.get();
    }
);
if (found_iterator != end(organism_vector))
{
    auto &attacked_organism = *found_iterator;
    attacked_organism->get_coordinates();
    ...
}