I was reading following question:
How to sum up elements of a C++ vector?, and I wanted to use second method (sum_of_elems =std::accumulate(vector.begin(),vector.end(),0);//#include <numeric>
).
However, I don't have std::vector<int>
, but std::vector<struct packet>
. The packet
is defined as following:
struct packet {
/// ...
int length() const;
///
}
and I want sum of packet lengths.
This is what I tried:
std::vector<packet> packets;
...
std::accumulate(packets.begin(), packets.end(), 0, [](const packet& a, const packet& b){return a.length() + b.length();});
but it doesn't work. In C#, I'd write something like
packet[] p;
p.Select(x => p.length()).Sum();
Is it possible to do something like that in C++? I can write method for iterating through the vector and doing it on my own, but I prefer the functional approach where possible.