VOOZH about

URL: https://www.geeksforgeeks.org/cpp/shuffle-an-array-using-stl-in-c/

⇱ Shuffle an Array using STL in C++ - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Shuffle an Array using STL in C++

Last Updated : 11 Jul, 2025

Given an array, the task is to shuffle the whole array and print it.
Example 
 

Input  (1, 2, 3, 4, 5, 6, 7}
Output  {3, 1, 6, 7, 2, 4, 5}

Input  (1, 2, 3}
Output  {3, 1, 2}


 


STL contains two methods which can be used to get a shuffled array. These are namely shuffle() and random_shuffle().
 

shuffle


This method rearranges the elements in the range [first, last) randomly, using g as a uniform random number generator. It swaps the value of each element with that of some other randomly picked element. It determines the element picked by calling g().
Template 
 

template 
 void shuffle (RandomAccessIterator first, 
 RandomAccessIterator last, 
 URNG&& g)
{
 for (auto i=(last-first)-1; i>0; --i) {
 std::uniform_int_distribution d(0, i);
 swap (first[i], first[d(g)]);
 }
}


Implementation
 


Output: 
30 10 20 40

 

Note: Output may differ each time because of the random function used in the program.
 

random_shuffle


This function randomly rearranges elements in the range [first, last). It swaps the value of each element with some other randomly picked element. When provided, the function gen determines which element is picked in every case. Otherwise, the function uses some unspecified source of randomness.
Template 
 

template 
 void random_shuffle (RandomAccessIterator first, 
 RandomAccessIterator last,
 RandomNumberGenerator& gen)
{
 iterator_traits::difference_type i, n;
 n = (last-first);
 for (i=n-1; i>0; --i) {
 swap (first[i], first[gen(i+1)]);
 }
}


Implementation
 


Output: 
10 40 20 30

 

Note: Output may differ each time because of the random function used in the program.
 

Which is better?


 

  • shuffle introduced after C11++, uses functions which are better than rand() which random_shuffle uses.
  • shuffle is an improvement over random_shuffle, and we should prefer using the former for better results.
  • If we don't pass our random generating function in random_shuffle then it uses its unspecified random values due to which all successive values are correlated.


 

Comment
Article Tags:
Article Tags: