user2381422
user2381422

Reputation: 5805

Summing up values by calling a method of objects in a vector in c++

Is there a nicer way to write this code in C++11?

int RawSheet::getNumberOfCities() const
{
    int n = 0;
    for (const auto &c : countries) {
        n += c.getNumberOfCities();
    }
    return n;
}

Thanks

Upvotes: 0

Views: 83

Answers (1)

David G
David G

Reputation: 96800

Use std::accumulate with a lambda callback:

#include <algorithm>

int RawSheet::getNumberOfCities() const
{
    return std::accumulate(countries.begin(), countries.end(), 0, [] (RawSheet const& op1, RawSheet const& op2)
    {
        return op1.getNumberOfCities() + op2.getNumberOfCities();
    });
}

Upvotes: 3

Related Questions