I try to implement that summing up all elements of a vector<vector<int>>
in a non-loop ways.
I have checked some relevant questions before, How to sum up elements of a C++ vector?.
So I try to use std::accumulate
to implement it but I find it is hard for me to overload a Binary Operator
in std::accumulate
and implement it.
So I am confused about how to implement it with std::accumulate
or is there a better way?
If not mind could anyone help me?
Thanks in advance.
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.
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.
You need to use std::accumulate
twice, once for the outer vector
with a binary operator that knows how to sum the inner vector
using an additional call to std::accumulate
:
int sum = std::accumulate(
vec.begin(), vec.end(), // iterators for the outer vector
0, // initial value for summation - 0
[](int init, const std::vector<int>& intvec){ // binaryOp that sums a single vector<int>
return std::accumulate(
intvec.begin(), intvec.end(), // iterators for the inner vector
init); // current sum
// use the default binaryOp here
}
);
In this case, I do not suggest using std::accumulate
as it would greatly impair readability. Moreover, this function use loops internally, so you would not save anything. Just compare the following loop-based solution with the other answers that use std::accumulate
:
int result = 0 ;
for (auto const & subvector : your_vector)
for (int element : subvector)
result += element;
Does using a combination of iterators, STL functions, and lambda functions makes your code easier to understand and faster? For me, the answer is clear. Loops are not evil, especially for such simple application.
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