TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
 Specialized Dev Zones Research Center eBook Library .NET Java C++ Web Dev Architecture Database Security Open Source Enterprise Mobile Special Reports 10-Minute Solutions DevXtra Blogs Slideshow

 Home » Tip Bank » Visual Basic » Windows
Language: C++
Expertise: Intermediate
Nov 12, 1999

### WEBINAR:On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning

# Using the random_shuffle Algorithm

STL includes the random_shuffle() algorithm. As the name suggests, this algorithm randomly shuffles the elements of a sequence. It takes two arguments, the first of which is an iterator that points to the first element of the sequence. The second argument is an iterator that points one position past the last element of the sequence. The following program instantiates a vector of characters, fills it with four consecutive elements and displays the elements. Then, the random_shuffle() algorithm is called to shuffle the elements of the vector. Finally, the elements are displayed:
``````
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main()
{
vector<char> vc;
vc.push_back('a'); //fill vector
vc.push_back('b');
vc.push_back('c');
vc.push_back('d');
cout<<vc[0]<<vc[1]<<vc[2]<<vc[3]<<endl; /* display all elements */

random_shuffle(vc.begin(), vc.end()); /* shuffle elements */

cout<<vc[0]<<vc[1]<<vc[2]<<vc[3]<<endl; /* display shuffled elements */
}
``````
As you can see, random_shffle() changed the order of the elements. You can use random_shuffle() with built-in arrays too:
``````
int n[4] = {0,1,2,3};
random_shuffle(n, n+4);
``````
Danny Kalev

 Submit a Tip Browse "Visual Basic" Tips Browse All Tips
Comment and Contribute

(Maximum characters: 1200). You have 1200 characters left.

Thanks for your registration, follow us on our social networks to keep up-to-date