algorithm - STL C++

random_shuffle()

Declaration

template <class RandomAccessIterator>
void random_shuffle(
	RandomAccessIterator xFirst,
	RandomAccessIterator xLast
);

Description

This function randomizes the order of the elements in the range "xFirst" up through the one before "xLast." The randomization depends on the seed passed into srand(). The overloaded version uses the random number generator "xRand," instead of rand() to shuffle the entries.

Header Include

#include <algorithm>

Overloads

template <class RandomAccessIterator, class RandomGen>
void random_shuffle(
	RandomAccessIterator xFirst,
	RandomAccessIterator xLast,
	RandomGen& xRand
);

Example

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

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 Vector: ";
	for (qIter = qV.begin(); qIter != qV.end(); ++qIter) {
		cout << *qIter;
	}
	cout << endl;

	// Randomly shuffle the entries
	random_shuffle(qV.begin(), qV.end());

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

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

Output

random_shuffle() Output
 

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