devxlogo

Using the random_shuffle Algorithm

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   #include   #include   using namespace std;  int main()  {   vector vc;   vc.push_back('a'); //fill vector   vc.push_back('b');   vc.push_back('c');   vc.push_back('d');   cout<

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);  
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist