generate


Fill a sequence using a generator function.

Traverse the sequence [ first ... last ), assigning to each element the result of executing gen .

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class ForwardIterator, class Generator >
void generate
  (
  ForwardIterator first,
  ForwardIterator last,
  Generator gen
  );
  

Complexity

Time complexity is linear, as gen is executed ( last - first ) times. Space complexity is constant.

Example <ospace/osstd/examples/gener1.cpp>
#include <iostream>
#include <stdlib.h>
#include <algorithm>

void
main()
  {
  int numbers[ 10 ];

  generate( numbers, numbers + 10, rand );

  for ( int i = 0; i < 10; ++i )
    cout << numbers[ i ] << ` `;
  cout << "\n";
  }

346 130 10982 1090 11656 7117 17595 6415 22948 31126
Example <ospace/osstd/examples/gener2.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

class Fibonacci
  {
  public:
    Fibonacci() : v1( 0 ), v2( 1 ) {}
    int operator()();
  private:
    int v1;
    int v2;
  };

int
Fibonacci::operator()()
  {
  int r = v1 + v2;
  v1 = v2;
  v2 = r;
  return v1;
  }

void
main()
  {
  vector< int > v1( 10 );
  Fibonacci generator;

  generate( v1.begin(), v1.end(), generator );

  ostream_iterator< int > iter( cout, " " );
  copy( v1.begin(), v1.end(), iter );
  cout << "\n";
  }

1 1 2 3 5 8 13 21 34 55

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.