Posted By

tkf on 04/18/08


Tagged

random shuffle boost


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

khouser


std::random_shuffle and boost/random.hpp


 / Published in: C++
 

use boost random algolism in std::random_shuffle

  1. #include <iostream>
  2. #include <ctime>
  3. #include <boost/random.hpp>
  4.  
  5. class Random
  6. {
  7. public:
  8. boost::mt19937 gen;
  9. boost::uniform_int<int> dst;
  10. boost::variate_generator< boost::mt19937, boost::uniform_int<int> > rand;
  11. Random( int N ):// call instance:
  12. gen( static_cast<unsigned long>(std::time(0)) ), dst( 0, N ), rand( gen, dst ) {
  13. }
  14. std::ptrdiff_t operator()( std::ptrdiff_t arg ) {
  15. return static_cast< std::ptrdiff_t >( rand() );
  16. }
  17. };
  18.  
  19. int main () {
  20. srand ( unsigned ( time (NULL) ) );
  21. std::vector<int> myvector;
  22. std::vector<int>::iterator it;
  23. Random rnd( 10 );
  24.  
  25. // set some values:
  26. for (int i=0; i<10; ++i) myvector.push_back(i); // 0 1 2 3 4 5 6 7 8 9
  27.  
  28. // using built-in random generator:
  29. std::random_shuffle ( myvector.begin(), myvector.end() );
  30.  
  31. // using myrandom:
  32. std::random_shuffle ( myvector.begin(), myvector.end(), rnd);
  33.  
  34. // print out content:
  35. std::cout << "myvector contains:";
  36. for (it=myvector.begin(); it!=myvector.end(); ++it)
  37. std::cout << " " << *it;
  38.  
  39. std::cout << std::endl;
  40. return 0;
  41. }

Report this snippet  

You need to login to post a comment.