Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sum up a vector of vector int in C++ without loops

Tags:

c++

stdvector

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.

like image 832
Bowen Peng Avatar asked Nov 03 '19 14:11

Bowen Peng


People also ask

How do you add all elements to 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.

Which function can be used to find the sum of the vector container?

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.


Video Answer


2 Answers

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
    }
);
like image 137
Shloim Avatar answered Nov 14 '22 09:11

Shloim


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.

like image 23
Gilles-Philippe Paillé Avatar answered Nov 14 '22 09:11

Gilles-Philippe Paillé