Open In App
Related Articles

std::generate_n in C++

Improve Article
Improve
Save Article
Save
Like Article
Like

std::generate is an STL algorithm, which is used to generate numbers based upon a generator function, and then, it assigns those values to the elements in the container in the range [first, last).

The generator function has to be defined by the user, and it is called successively for assigning the numbers.
Now, there can be a scenario, where we want to assign values only to the first n elements, for that we have another STL algorithm std::generate_n, which has the following syntax:
Template function:

OutputIterator generate_n (OutputIterator first, Size n, Generator gen);

first: Output iterator pointing to the beginning of the container.
n: No. of elements to be assigned a value, using generator function.
gen: A generator function for generating the values.

Returns: 
It doesnot have a void return type like std::generate, but, in fact, 
it returns an iterator pointing to the element that follows the last element 
whose value has been generated.




// C++ program to demonstrate the use of std::generate_n
#include <iostream>
#include <vector>
#include <algorithm>
  
// Defining the generator function
int gen()
{
    static int i = 0;
    return ++i;
}
  
using namespace std;
int main()
{
    int i;
  
    // Declaring a vector of size 10
    vector<int> v1(10);
  
    // using std::generate_n
    std::generate_n(v1.begin(), 10, gen);
  
    vector<int>::iterator i1;
    for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
        cout << *i1 << " ";
    }
    return 0;
}


Output:

1 2 3 4 5 6 7 8 9 10

If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 21 Jul, 2017
Like Article
Save Article
Previous
Next
Similar Reads