C++ Algorithm Library - generate() Function



Description

The C++ function std::algorithm::generate() assigns the value returned by successive calls to gen to the elements in the range of first to last.

Declaration

Following is the declaration for std::algorithm::generate() function form std::algorithm header.

C++98

template <class ForwardIterator, class Generator>
void generate (ForwardIterator first, ForwardIterator last, Generator gen);

Parameters

  • first − Forward iterator to the initial position.

  • last − Forward iterator to the final position.

  • gen − Generator function that is called with no arguments and returns some value

Return value

None

Exceptions

Throws exception if either gen function or an operation on an iterator throws exception.

Please note that invalid parameters cause undefined behavior.

Time complexity

Linear.

Example

The following example shows the usage of std::algorithm::generate() function.

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(void) {
   vector<int> v(5);

   generate(v.begin(), v.end(), rand);

   cout << "Vector contains following random numbers" << endl;

   for (auto it = v.begin(); it != v.end(); ++it)
      cout << *it << endl;

   return 0;
}

Let us compile and run the above program, this will produce the following result −

Vector contains following random numbers
1804289383
846930886
1681692777
1714636915
1957747793
algorithm.htm
Advertisements
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy