generate_n


Generate a specified number of items.

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

Library

Standards<ToolKit>

Declaration


#include <algorithm>

template< class OutputIterator, class Size, class Generator >
void generate_n( OutputIterator first, Size n, Generator gen );

Complexity

Time complexity is linear, as gen is executed n times. Space complexity is constant.

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

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

  generate_n( v1.begin(), v1.size(), rand );

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

346 130 10982 1090 11656 7117 17595 6415 22948 31126
Example <ospace/osstd/examples/genern2.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_n( v1.begin(), v1.size(), 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.