fork(51) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <random>
  4. #include <functional> //for std::function
  5. #include <algorithm> //for std::generate_n
  6.  
  7. typedef std::vector<char> char_array;
  8.  
  9. //we don't want a global. That's ugly.
  10. //This will get optimized at compile time anyway
  11. //http://e...content-available-to-author-only...a.org/wiki/Return_value_optimization
  12. char_array charset()
  13. {
  14. //Change this to suit
  15. return char_array(
  16. {'0','1','2','3','4',
  17. '5','6','7','8','9',
  18. 'A','B','C','D','E','F',
  19. 'G','H','I','J','K',
  20. 'L','M','N','O','P',
  21. 'Q','R','S','T','U',
  22. 'V','W','X','Y','Z',
  23. 'a','b','c','d','e','f',
  24. 'g','h','i','j','k',
  25. 'l','m','n','o','p',
  26. 'q','r','s','t','u',
  27. 'v','w','x','y','z'
  28. });
  29. };
  30.  
  31. std::string random_string( size_t length, std::function<char(void)> rand_char )
  32. {
  33. std::string str(length,0);
  34. std::generate_n( str.begin(), length, rand_char );
  35. return str;
  36. }
  37.  
  38. int main()
  39. {
  40. //Independent of character set,
  41. //Distribution can be changed
  42. //Output is non-deterministic
  43. const auto ch_set = charset();
  44. std::default_random_engine rng(std::random_device{}());
  45. std::uniform_int_distribution<> dist(0, ch_set.size()-1);
  46. auto randchar = [ ch_set,&dist,&rng ](){return ch_set[ dist(rng) ];};
  47. auto length = 5;
  48. std::cout<<random_string(length,randchar)<<std::endl;
  49. return 0;
  50. }
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
GBgSi