cplusplus.com cplusplus.com
cplusplus.com   C++ : Reference : STL Algorithms : generate_n
 
- -
C++
Information
Documentation
Reference
Articles
Sourcecode
Forum
Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
STL Algorithms
algorithm:
· adjacent_find
· binary_search
· copy
· copy_backward
· count
· count_if
· equal
· equal_range
· fill
· fill_n
· find
· find_end
· find_first_of
· find_if
· for_each
· generate
· generate_n
· includes
· inplace_merge
· iter_swap
· lexicographical_compare
· lower_bound
· make_heap
· max
· max_element
· merge
· min
· min_element
· mismatch
· next_permutation
· nth_element
· partial_sort
· partial_sort_copy
· partition
· pop_heap
· prev_permutation
· push_heap
· random_shuffle
· remove
· remove_copy
· remove_copy_if
· remove_if
· replace
· replace_copy
· replace_copy_if
· replace_if
· reverse
· reverse_copy
· rotate
· rotate_copy
· search
· search_n
· set_difference
· set_intersection
· set_symmetric_difference
· set_union
· sort
· sort_heap
· stable_partition
· stable_sort
· swap
· swap_ranges
· transform
· unique
· unique_copy
· upper_bound

-

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

Generate values for sequence with function

Sets the value of the first n elements in the sequence pointed by first to the value returned by successive calls to gen.

The behavior of this function template is equivalent to:

template <class OutputIterator, class Size, class Generator>
  void generate ( OutputIterator first, Size n, Generator gen )
{
  for (; n>0; --n)  *first++ = gen();
}

Parameters

first
Output iterators to the initial positions in a sequence of at least n elements.
n
Number of elements to set value to.
Its type is an integral type or some other type convertible to it.
gen
Generator function that takes no arguments and returns some value to be stored as element value. This can either be a pointer to a function or an object whose class overloads operator().

Return value

none

Example

// generate_n example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int current(0);
int UniqueNumber () { return ++current; }

int main () {
  vector<int> myvector (9);
  vector<int>::iterator it;

  generate (myvector.begin(), myvector.end(), UniqueNumber);

  cout << "myvector contains:";
  for (it=myvector.begin(); it!=myvector.end(); ++it)
    cout << " " << *it;

  cout << endl;
 
  return 0;
}

A possible output:

myvector contains: 1 2 3 4 5 6 7 8 9

Complexity

Linear: Invokes gen and assigns that value, n times.

See also

generate Generate values for range with function (function template)
fill_n Fill sequence with value (function template)
for_each Apply function to range (template function)

© The C++ Resources Network, 2000-2007 - All rights reserved
Spotted an error? - contact us