Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: C++
Expertise: Intermediate
Nov 12, 1999



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
   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
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