C++ Tutorial/STL Algorithms Helper/multiply

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Using the generic accumulate algorithm to compute a product by using a function object

<source lang="cpp">#include <iostream>

  1. include <vector>
  2. include <cassert>
  3. include <numeric> // For accumulate

using namespace std; class multiply {

public:
 int operator()(int x, int y) const { return x * y; }

}; int main() {

 int x[5] = {2, 3, 5, 7, 11};
 vector<int> vector1(&x[0], &x[5]); 
 
 int product = accumulate(vector1.begin(), vector1.end(),
                          1, multiply());
   
 cout << product << endl;
 return 0;

}</source>

2310

Using the generic accumulate algorithm to compute a product by using multiplies

<source lang="cpp">#include <iostream>

  1. include <vector>
  2. include <cassert>
  3. include <numeric> // For accumulate
  4. include <functional> // For multiplies

using namespace std; int main() {

 int x[5] = {2, 3, 5, 7, 11};
 vector<int> vector1(&x[0], &x[5]); 
 
 int product = accumulate(vector1.begin(), vector1.end(),1, multiplies<int>());
   
 cout << product << endl;
 return 0;

}</source>

2310