C ++ Multiplying Elements in Vector

I was looking for a better solution for the next one and I can not find it.

Let's say I have a vector:

std::vector<double> vars = {1, 2, 3}

I want to execute. 1 * 2 * 3I know that I can do the following:

int multi = 1;

for(int i = 0; (i < vars.size()-1); i++)
{
    multi *= vars[i];
}

But is there a "C ++ 11" way? I really wanted to do this with lambdaand so that I could calculate the multiplication (product) of a vector without having another function inside the class, I would prefer it to be computed inside the function.

+4
source share
2 answers

Yes, as usual, there is an algorithm (although this one is in <numeric>), std::accumulate( live example ):

using std::begin;
using std::end;
auto multi = std::accumulate(begin(vars), end(vars), 1, std::multiplies<double>());

std::multiplies <functional>. std::accumulate std::plus, , operator(). std::multiplies - , .

++ 14 std::multiplies<double> std::multiplies<>, operator(), . , Eric Niebler Ranges, , vars | accumulate(1, std::multiplies<>()), .

+18

, , :

std::vector<double> vars = {1, 2, 3}
int multi = 1;

for (const auto& e: vars)
    multi *= e;
+3

All Articles