algorithm - STL C++

generate()

Declaration

template <class ForwardIterator, class Generator>
void generate(
	ForwardIterator xFirst,
	ForwardIterator xLast,
	Generator xGenerator
);

Description

This function applies the function "xGenerator" to each item in the range starting from "xFirst" up to the entry before "xLast" to generate a value that is put into each location.

Header Include

#include <algorithm>

Example

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

char Generate() {
	return (char)((rand() % 26) + 'a');
}

int main()
{
	using namespace std;

	// Create a vector instance
	vector<char> qV;
	qV.push_back('X');
	qV.push_back('o');
	qV.push_back('a');
	qV.push_back('X');
	qV.push_back('.');
	qV.push_back('n');
	qV.push_back('e');
	qV.push_back('t');

	vector<char>::iterator qIter;
	// Output the vector
	cout << "Original: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Generate values for the last four entries
	generate(qV.begin() + 4, qV.end(), Generate);

	// Output the vector after generating char values
	cout << "Generated: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Keep the window open
	cin.get();
	return 0;
}

Output

generate() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.