C++ Multiplying elements in a vector

前端 未结 2 2083
执笔经年
执笔经年 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 ), std::accumulate (live example):

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

    std::multiplies is in , 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 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.

提交回复
热议问题