STL source code profiling algorithm stl_algo.h -- random_shuffle

Source: Internet
Author: User

STL source code profiling algorithm stl_algo.h -- random_shuffle

 

Random_shuffle

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------------------------------

 

Description: sorts the elements of [first, last) at random.
Ideas:
Must be RandomAccessIterator
1. Traverse intervals
2. Generate a random number rand in [0, I) and exchange * (first + rand) with I.
?? How to prove randomness
Source code:
Template
 
  
Inline void random_shuffle (RandomAccessIterator first, RandomAccessIterator last) {_ random_shuffle (first, last, distance_type (first);} template
  
   
Void random_shuffle (RandomAccessIterator first, RandomAccessIterator last, RandomNumberGenerator & rand) {// The parameter must be referenced here. Because the random number generator has a local state, if (first = last) return; for (RandomAccessIterator I = first + 1; I! = Last; ++ I) iter_swap (I, first + rand (I-first) + 1);} template
   
    
Void _ random_shuffle (RandomAccessIterator first, RandomAccessIterator last, Distance *) {if (first = last) return; for (RandomAccessIterator I = first + 1; I! = Last; ++ I) # ifdef _ STL_NO_DRAND48 iter_swap (I, first + Distance (rand () % (I-first) + 1 ))); # else iter_swap (I, first + Distance (lrand48 () % (I-first) + 1); # endif}
   
  
 

Example:
int main(){vector
 
   vec;for(int ix = 0; ix < 10; ix++)vec.push_back(ix);random_shuffle(vec.begin(), vec.end());copy(vec.begin(), vec.end(), ostream_iterator
  
   (cout,  ));}
  
 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.