Difference in performance: std::accumulate vs std::inner_product vs Loop

后端 未结 1 571
花落未央
花落未央 2021-01-12 07:13

Today, I want to share something that was blowing my mind when I tried to implement this simple operation:

I found different ways to perform the same operat

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-12 07:57

    If I am accumulating elements of an array, I am expecting to get the same type as a result.

    Your expectation is wrong (though it is not quite clear what "same type as result" means), as you can clearly see from std::accumulate documentation:

    template< class InputIt, class T >
    T accumulate( InputIt first, InputIt last, T init );
    
    template< class InputIt, class T, class BinaryOperation >
    T accumulate( InputIt first, InputIt last, T init,
                  BinaryOperation op );
    

    return type is exactly the same type you use for initial value. The same effect you can have on the loop:

    auto result = 0; // vs auto result = 0.0;
    for (auto i = 0; i < input.size(); ++i) {
      result += input[i] * input[i];
    }
    

    Why did the standard decide to perform it in this way?

    Because this way you can decide what type you use to aggregate. Note std::accumulate can be used for left fold and cases when T not equal to std::iterator_traits::value_type not less often (probably even more) than when they match.

    0 讨论(0)
提交回复
热议问题