Code Snippets

  

C++ Source Code


Welcome to Dream.In.Code
Become a C++ Expert!

Join 149,631 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 2,085 people online right now. Registration is fast and FREE... Join Now!





Usage of std::random_shuffle ( )

In this random_shuffle() function randomly re-orders the elements and gives random ordering on every run by making use of srand() and rand() function.

Submitted By: Xing
Actions:
Rating:
Views: 3,099

Language: C++

Last Modified: October 6, 2006

Snippet


  1. //Headers
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <cstdlib>
  5. #include <ctime>
  6.  
  7. // Random number generator
  8. int Random(int n)
  9. {
  10.     return rand() % n ;
  11. }
  12.  
  13. int main(){
  14.      
  15.         //Seeding random number generator
  16.         std::srand(std::time(0));
  17.      
  18.         //Numbers to be shuffled
  19.         int Numbers[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  20.      
  21.         //Shuffling the numbers
  22.         std::random_shuffle(Numbers, Numbers + 10, Random);
  23.  
  24.         //Displaying the shuffled numbers
  25.         for(int i=0;i<10;++i)
  26.           std::cout<<Numbers[i]<<"  ";
  27.          
  28.         return 0;
  29. }
  30.  

Copy & Paste


Comments


There are currently no comments for this snippet. Be the first to comment!

Add comment


You must be registered and logged on to </dream.in.code> to leave comments.




Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month