fork(1) download
  1. #include <iostream>
  2. #include <cstdint>
  3. #include <random> // http://e...content-available-to-author-only...e.com/w/cpp/numeric/random
  4. #include <ctime>
  5. #include <stdexcept>
  6.  
  7. int main()
  8. {
  9. constexpr std::size_t NSEEDS = 5 ;
  10. std::uint32_t seeds[NSEEDS] = { 0 } ;
  11.  
  12. // see: http://w...content-available-to-author-only...s.com/forum/beginner/103051/#msg554829
  13. try
  14. {
  15. std::random_device rdev ;
  16. // if( rdev.entropy() < 0.05 ) throw std::runtime_error( "not a random device" ) ;
  17. // commented out because GCC reports zero entropy even for a true std::random_device
  18. for( auto& s : seeds ) s = rdev() ;
  19. std::cout << "seeds generated with a random device\n" ;
  20. }
  21. catch( const std::exception& )
  22. {
  23. std::cout << "no random device / bogus random device / random device has no entropy\n" ;
  24. auto t = std::time(nullptr) ;
  25. for( std::size_t i = 0 ; i < NSEEDS ; ++i )
  26. if( seeds[i] == 0 ) seeds[i] = t * (i+3) ;
  27. }
  28.  
  29. std::seed_seq seed_seq( seeds, seeds+NSEEDS ) ;
  30. std::mt19937 twister(seed_seq) ;
  31. std::uniform_int_distribution<int> dist( 1, 1000000 ) ;
  32.  
  33. for( int i = 0 ; i < 10 ; ++i ) std::cout << dist(twister) << ' ' ;
  34. std::cout << '\n' ;
  35. }
  36.  
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
seeds generated with a random device
811479 64016 360491 298008 779442 293644 673381 467266 522115 134440