The C++ function std::algorithm::generate_n() assigns the value returned by successive calls to gen to the first n elements of the sequence pointed by the first.
DeclarationFollowing is the declaration for std::algorithm::generate_n() function form std::algorithm header.
C++11template <class OutputIterator, class Size, class Generator> OutputIterator generate_n (OutputIterator first, Size n, Generator gen);Parameters
first − Output iterator to the initial position.
n − Number of values to generate.
gen − Generator function that is called with no arguments and returns some value.
Returns an an iterator which points to the element that follows the last element whose value has been generated.
ExceptionsThrows exception if either gen function or the element assignment or an operation on an iterator throws exception.
Please note that invalid parameters cause undefined behavior.
Time complexityLinear.
ExampleThe following example shows the usage of std::algorithm::generate_n() function.
#include <iostream> #include <algorithm> using namespace std; int main(void) { int arr[10] = {0, 0, 0, 0, 0, -100}; /* assign value to only first 5 elements */ auto it = generate_n(arr, 5, rand); cout << "First five random numbers are" << endl; for (int i = 0; i < 10; ++i) cout << arr[i] << endl; cout << endl; cout << "Iterator points to " << *it << endl; return 0; }
Let us compile and run the above program, this will produce the following result −
First five random numbers are 1804289383 846930886 1681692777 1714636915 1957747793 -100 0 0 0 0 Iterator points to -100
algorithm.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4