在遵循代码的和平,我试图找到另一个对象,具有相同的坐标作为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;
});
另一件事,当我终于设法得到这个迭代器,如何引用攻击有机体类方法?
*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()
返回的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
,它是iterator
到Organism
,所以更像这样的东西会更容易读:
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();
...
}