Let's say I have the following object:
struct Foo
{
int size() { return 2; }
};
What's the best way (most maintainable, readable, etc.) to get the total size
of all objects in a vector<Foo>
? I'll post my solution but I'm interested in better ideas.
Update:
So far we have:
Are there any other workable solutions? Can you make something maintainable using boost::bind
or std::bind1st/2nd
?
Which function can be used to find the sum of a vector container? Explanation: STL provides accumulate() function to find the sum of a vector.
Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.
If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column. If A is a multidimensional array, then sum(A) operates along the first array dimension whose size does not equal 1, treating the elements as vectors.
1) accumulate(): This function returns the sum of all the values lying in a range between [first, last) with the variable sum.
In addition to your own suggestion, if your compiler supports C++0x lambda expressions, you can use this shorter version:
std::vector<Foo> vf;
// do something to populate vf
int totalSize = std::accumulate(vf.begin(),
vf.end(),
0,
[](int sum, const Foo& elem){ return sum + elem.size();});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With