# Generator function in C++

In this tutorial, we will learn about the **generator function in C++**. A generator function is used to produce values having a particular sequence called a series. The series is produced based on a generator function which is defined by the programmer or user. Here we will see two generator functions one for generating even numbers and another for Fibonacci numbers.

## Generators and Iterators in C++ STL

In the STL library of C++, generate and iterate algorithms are defined. Here, we will discuss the use of both algorithms. You have to include the algorithm header file before using these.

### std::generate

It is an STL algorithm that you can use to generate numbers on the basis of a user-defined generator function. After generating the values, it assigns these values to the elements in the container. It calls the generator function to produce a value. The format of the generate() function is given below. The first point to the first element of the container. The last point to the last element of the container. And the generator function defines the basis by which values are produced.

*void generate(Forward_Iterator first, Forward_Iterator last, Generator generator_function); *

### std::iterator

It is an STL algorithm that points at a memory address of the container. And it contains many functions to perform different operations on the container.

**1. begin() –** It returns the beginning index of the container.

**2. end() –** It returns the ending position of the container.

**3. next() –** It returns a new iterator which points to the container at which the iterator will point after incrementing.

**4. prev() –** It returns a new iterator which points to the container at which the iterator will point after decrementing.

*vector<data_type>::iterator iterator_name;*

## Generator function defined by the user

The generate STL algorithm uses a user-defined generator function to produce the values. So the user defines this function as per the sequence or series the user wants to generate. In this tutorial, we will see two examples of a generator function.

### User-defined generator function for even number series

To produce even numbers, we have to start with initial value 0 and increment by 2 in each function call. So, the function for even number is as follows –

int generator_function() { static int i=0; return (i=i+2); }

In this function, we return ‘i’ after incrementing it by 2 to get the desirable sequence.

### User-defined generator function for Fibonacci series

A Fibonacci series is – 0 1 1 2 3 5 8 13… and so on.

To generate such a sequence using STL algorithms we have to define a generator function.

int generator_function() { static int i=0,flag=0; if(i==0) { i++; return 0; } else if(i==1 && flag==0) { flag++; return 1; } else { i=arr[0]+arr[1]; arr[0]=arr[1]; arr[1]=i; return i; } }

This function will return 0 at first call, 1 at the second call. And from the third call onwards it will return the sum of the previous two elements. So, we get the Fibonacci series.

## C++ program to generate even number series

By now, we know how to define a generator function for even number sequence. In the program, we will take the number of terms in the series by the user. The program for generating even numbers is –

#include <iostream> #include <vector> #include <algorithm> int generator_function() { static int i=0; return (i=i+2); } using namespace std; int main() { int num; cout<<"\nENTER NUMBER OF TERMS IN SERIES : "; cin>>num; vector<int> series(num); std::generate(series.begin(),series.end(),generator_function); vector<int>::iterator i; for (i=series.begin();i!=series.end();++i) cout<<*i<<" "; return 0; }

So, in the program, we take the total number of terms in ‘num’. Then we create a container of name series which will store integer values. And the generate function generates the complete series and assigns the values in the element of the container. The iterator points to the container and displays the contents i.e. series onto the screen.

The output of this program is –

[email protected]:~/cpp$ g++ generate.cpp [email protected]:~/cpp$ ./a.out ENTER NUMBER OF TERMS IN SERIES : 10 2 4 6 8 10 12 14 16 18 20 [email protected]:~/cpp$

So, we get a series of even numbers with total terms 10.

## C++ program to generate Fibonacci series

We have already discussed the generator function for the Fibonacci series. Thus the program for generating Fibonacci series is –

#include <iostream> #include <vector> #include <algorithm> int arr[]={0,1}; int generator_function() { static int i=0,flag=0; if(i==0) { i++; return 0; } else if(i==1 && flag==0) { flag++; return 1; } else { i=arr[0]+arr[1]; arr[0]=arr[1]; arr[1]=i; return i; } } using namespace std; int main() { int num; cout<<"\nENTER NUMBER OF TERMS IN SERIES : "; cin>>num; vector<int> series(num); std::generate(series.begin(),series.end(),generator_function); vector<int>::iterator i; for (i=series.begin();i!=series.end();++i) cout<<*i<<" "; return 0; }

So, in the program the generate function uses the generator_function() for producing the values of the sequence. And then assigns these values to the element in the container. The iterator then reads the container from the beginning and displays the series.

The output of this program is –

[email protected]:~/cpp$ g++ generate1.cpp [email protected]:~/cpp$ ./a.out ENTER NUMBER OF TERMS IN SERIES : 10 0 1 1 2 3 5 8 13 21 34 [email protected]:~/cpp$

Thus this program generates the Fibonacci series.

Also read: Inline Function in C++ with example

Hello

Do you have an example of generating vector names?

In your example, the vector name “series” is hardcoded.

But I read that one can generate a function to create

a vector name. They don’t give the code though.

#include

#include

#include

#include

using std::cout;

using std::end;

using std::string;

using std::generate_n;

string uniqueName(){

auto randchar = []() -> char{

const char charset[] = “0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz”;

const size_t max_index = (sizeof(charset) – 1);

return charset[ rand() % max_index ];

};

string str(4,0);

std::generate_n( str.begin(), 4, randchar );

return str;

}

string generator_vector_with_custom_name(string Name){

/*….*/

//return VectorName;

}

int main(){

/*Random name*/

string Name = uniqueName();

/*call fonction to generate a vector name*/

//static vectorgenerator_vector_with_custom_name(Name){};

/*

to generate a vector with a custom name

staticVjk{};

staticRdl{};

staticNEs{};

….

*/

}

Can you help me create this C++ code?