Export (0) Print
Expand All

generate_n

Assigns the values generated by a function object to a specified number of elements in a range and returns to the position one past the last assigned value.

template<class OutputIterator, class Diff, class Generator>
void generate_n( OutputIterator First, Diff Count, Generator Gen);

First

An output iterator addressing the position of first element in the range to which values are to be assigned.

Count

A signed or unsigned integer type specifying the number of elements to be assigned a value by the generator function.

Gen

A function object that is called with no arguments that is used to generate the values to be assigned to each of the elements in the range.

The function object is invoked for each element in the range and does not need to return the same value each time it is called. It may, for example, read from a file or refer to and modify a local state. The generator's result type must be convertible to the value type of the forward iterators for the range.

The range referenced must be valid; all pointers must be dereferenceable and, within the sequence, the last position must be reachable from the first by incrementation.

The complexity is linear, with exactly Count calls to the generator being required.

// cl.exe /EHsc /nologo /W4 /MTd
#include <vector>
#include <deque>
#include <iostream>
#include <string>
#include <algorithm>
#include <random>

using namespace std;

template <typename C> void print(const string& s, const C& c) {
    cout << s;

    for (const auto& e : c) {
        cout << e << " ";
    }

    cout << endl;
}

int main()
{
    const int elemcount = 5;
    vector<int> v(elemcount);
    deque<int> dq(elemcount);

    // Set up random number distribution
    random_device rd;
    mt19937 engine(rd());
    uniform_int_distribution<int> dist(-9, 9);

    // Call generate_n, using a lambda for the third parameter
    generate_n(v.begin(), elemcount, [&](){ return dist(engine); });
    print("vector v is: ", v);

    generate_n(dq.begin(), elemcount, [&](){ return dist(engine); });
    print("deque dq is: ", dq);
}

vector v is: 1 -9 -3 2 -9
deque dq is: -9 7 -2 4 8

Header: <algorithm>

Namespace: std

Show:
© 2014 Microsoft