std::generate in C++

std::generate, as the name suggests 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.

Template function:



void generate (ForwardIterator first, ForwardIterator last, Generator gen);

first: Forward iterator pointing to the first element of the container.
last: Forward iterator pointing to the last element of the container.
gen: A generator function, based upon which values will be assigned.

Returns: none
Since, it has a void return type, so it does not return any value.
filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to demonstrate the use of std::generate
#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
    std::generate(v1.begin(), v1.end(), gen);
  
    vector<int>::iterator i1;
    for (i1 = v1.begin(); i1 != v1.end(); ++i1) {
        cout << *i1 << " ";
    }
    return 0;
}

chevron_right


Output:

1 2 3 4 5 6 7 8 9 10

Next: std::generate_n in C++

This article is contributed by Mrigendra Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.



My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.