STL way to access more elements at the same time in a loop over a container

The most STLish way I can imagine:

std::partial_sum(std::begin(v), std::end(v),
                 std::begin(v), std::multiplies<double>());

Example:

#include <iostream>
#include <vector>
#include <iterator>
#include <numeric>
#include <functional>

int main()
{
    std::vector<double> v{ 1.0, 2.0, 3.0, 4.0 };

    std::partial_sum(std::begin(v), std::end(v),
                     std::begin(v), std::multiplies<double>());

    std::copy(std::begin(v), std::end(v),
                             std::ostream_iterator<double>(std::cout, " "));
}

Output:

1 2 6 24 

Live demo link.

Leave a Comment

tech