C++ Algorithm generate ()

C++ Algorithm generate() function is used to assign the value generated by a function object to each element in a range.

The generator function is defined by the user and it is called successively for assigning the numbers.

Syntax

Parameter

first: A forward iterator pointing the position of the first element in the range to which values are to be assigned.

last: A forward iterator pointing the position one past the final element in the range to which values are to be assigned.

gen: A function object with no arguments that is used to generate the values to be assigned to each of the elements in the range.

Return value

None

Complexity

Complexity is linear in the range [first, last). It calls gen and performs an assignment for each element.

Data races

The object in the range [first ,last) are modified. Each object is accessed exactly once.

Exception safety

This function throws an exception if the any of gen, element assignments or the operation on an iterator throws an exception.

Please note that invalid parameters cause an undefined behavior.

Example 1

Let's see the simple example to demonstrate the use of generate ():

Output:

1,2,4,8,16,32,64,128,256,512,

Example 2

Let's see another simple example:

Output:

1 2 3 4 5 6 7 8 9 10  

Example 3

Let's see another simple example:

Output:

Vector v1 is ( 1804289383 846930886 1681692777 1714636915 1957747793 ).
Deque deq1 is ( 424238335 719885386 1649760492 596516649 1189641421 ).

Example 4

Let's see another simple example:

Output:

myvector contains: 93 16 77 25 39 52 56 19
myvector contains: 1 2 3 4 5 6 7 8

Next TopicC++ Algorithm




Latest Courses