Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

(C++) Answer of exercise #9: No for-loops #9

 

This is the answer of Exercise #9: No for-loops.

 

Question #9: Product of std::vector<int>

 

Replace the for-loop. You will need:

  • std::accumulate

  • std::multiplies

     

     

     

    #include <vector>

     

    const int Product(const std::vector<int>& v)

    {

    const int sz = v.size();

    const int product = 1;

    for (int i=0; i!=sz; ++i)

    {

    product*=v[i];

    }

    return product;

    }

     

     

    Answer

     

     

    #include <vector>

    #include <algorithm>

    #include <numeric>

     

    const int Product(const std::vector<int>& v)

    {

    return std::accumulate(v.begin(),v.end(),1,std::multiplies<int>());

    }

     

     

     

     

     

    Go back to Richel Bilderbeek's C++ page.

    Go back to Richel Bilderbeek's homepage.