dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


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
 
Comment and Contribute

 

 

 

 

 


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

 

 

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