Frogical
Frogical

Reputation: 185

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

I'm learning c++ and I would like to know how I can improve the following code:

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()));
});

There must be a better way to fill a vector with std::algorithms?

Upvotes: 2

Views: 66

Answers (1)

Yksisarvinen
Yksisarvinen

Reputation: 22176

std::transform is an algorithm which applies a function to each element in range (or two ranges) and stores result in another range (can be equal to any input range as well).

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> is all cool, but sometimes it's an overkill IMO. for loop would be even simpler:

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

As noted by Marc Glisse in comments, both versions would benefit from call to std::vector::reserve beforehand. push_back is quite inefficient when used frequently (std::back_inserter uses push_back internally as well)

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

Upvotes: 4

Related Questions