C++ Multiplying elements in a vector

前端 未结 2 2060
执笔经年
执笔经年 2021-01-01 20:59

I have been looking for a more optimal solution to the following and I cannot seem to find one.

Let\'s say I have a vector:

std::vector v

相关标签:
2条回答
  • 2021-01-01 21:31

    Yes, as usual, there is an algorithm (though this one's 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 is in <functional>, too. By default, std::accumulate uses std::plus, which adds two values given to operator(). std::multiplies is a functor that multiplies them instead.

    In C++14, you can replace std::multiplies<double> with std::multiplies<>, whose operator() is templated and will figure out the type. Based on what I've seen with Eric Niebler's Ranges proposal, it could possibly later look like vars | accumulate(1, std::multiplies<>()), but take that with a grain of salt.

    0 讨论(0)
  • 2021-01-01 21:39

    You can use a ranged based for loop like:

    std::vector<double> vars = {1, 2, 3}
    int multi = 1;
    
    for (const auto& e: vars)
        multi *= e;
    
    0 讨论(0)
提交回复
热议问题