Illustrating the generic generate algorithm: Fill vector1 with 1, 4, 9, 16, ..., 100 : generate « STL Algorithms Modifying sequence operations « C++






Illustrating the generic generate algorithm: Fill vector1 with 1, 4, 9, 16, ..., 100

  
 


#include <iostream>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;

template <typename T>
class calc_square {
  T i;
 public:
  calc_square(): i(0) {}
  T operator()() { ++i; return i * i; }
};

int main()
{
  vector<int> vector1(10);

  generate(vector1.begin(), vector1.end(), calc_square<int>());

  for (int j = 0; j < 10; ++j)
    cout << vector1[j] << " ";

  return 0;
}

/* 
1 4 9 16 25 36 49 64 81 100 
 */        
    
  








Related examples in the same category

1.Provide predicate for std::generate
2.Use std::generate to fill elements in a vector
3.Int sequence
4.Use generate to insert five random numbers into a list
5.Generate a sequence.