如何在这种情况下应用 C++ std 算法?

How to apply C++ std algorithms in this context?

我正在学习 C++,我想知道如何改进以下代码:

std::vector<float> distances;
std::for_each(play_->get_emps().begin(), play_->get_emps().end(), [distances, tank] (const auto& e) {
    distances.push_back(math::distance(e.location(), tank->location()));
});

必须有更好的方法来用 std::algorithms 填充向量?

std::transform 是一种算法,它将函数应用于范围(或两个范围)中的每个元素并将结果存储在另一个范围(也可以等于任何输入范围)。

std::vector<float> distances;
std::transform(play_->get_emps().begin(), play_->get_emps().end(), 
               std::back_inserter(distances),
               [tank](const auto& e) {return math::distance(e.location(), tank->location();});

<algorithm> 很酷,但有时在我看来有点过分了。 for 循环会更简单:

std::vector<float> distances;
for(const auto& e: play_) {
    distances.push_back(math::distance(e.location(), tank->location()));
}

正如 Marc Glisse 在评论中指出的那样,两个版本都可以从事先调用 std::vector::reserve 中获益。 push_back 经常使用时效率很低(std::back_inserter 在内部也使用 push_back

std::vector<float> distances;
distances.reserve(play_.size());