std::generate_n

Header: <algorithm>

  1. Assigns values, generated by given function object g, to the first count elements in the range beginning at first, if count > 0. Does nothing otherwise.

# Declarations

template< class OutputIt, class Size, class Generator >
OutputIt generate_n( OutputIt first, Size count, Generator g );

(constexpr since C++20)

template< class ExecutionPolicy,
class ForwardIt, class Size, class Generator >
ForwardIt generate_n( ExecutionPolicy&& policy,
ForwardIt first, Size count, Generator g );

(since C++17)

# Parameters

# Return value

Iterator one past the last element assigned if count > 0, first otherwise.

# Example

#include <algorithm>
#include <functional>
#include <iostream>
#include <iterator>
#include <random>
 
int main()
{
    std::mt19937 rng; // default constructed, seeded with fixed seed
    std::generate_n(std::ostream_iterator<std::mt19937::result_type>(std::cout, " "),
                    5, std::ref(rng));
    std::cout << '\n';
}

# Defect reports

DRApplied toBehavior as publishedCorrect behavior
LWG 426C++98the complexity requirement was “exactly count invocationsor assignments”, which is broken if count is negativeno invocation or assignmentif count is non-positive
LWG 865C++98the location of the first element followingthe generation range was not returnedreturned

# See also