fork(2) download
  1. #include <set>
  2. #include <vector>
  3. #include <functional>
  4. #include <algorithm>
  5.  
  6. // take a set of values and pairs them up at random, without repeats.
  7. template < typename T >
  8. std::vector< std::pair<T,T> > make_unique_pairs( const std::set<T>& set )
  9. {
  10. std::vector< std::pair<T,T> > result ;
  11.  
  12. // make a vector of references to elements in the set
  13. std::vector< std::reference_wrapper< const T > > seq( set.begin(), set.end() ) ;
  14.  
  15. // make a random permutation of the references
  16. std::random_shuffle( std::begin(seq), std::end(seq) ) ;
  17.  
  18. // make pairs and place them into the result
  19. for( std::size_t i = 0 ; i < seq.size() - 1 ; i += 2 )
  20. result.emplace_back( seq[i], seq[i+1] ) ;
  21.  
  22. return result ;
  23. }
  24.  
  25. #include <cstdlib>
  26. #include <ctime>
  27. #include <iostream>
  28.  
  29. int main()
  30. {
  31. std::srand( std::time(nullptr) ) ;
  32.  
  33. const std::set<int> values { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } ;
  34.  
  35. for( auto pair : make_unique_pairs(values) )
  36. std::cout << pair.first << ',' << pair.second << '\n' ;
  37. }
  38.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
3,12
4,7
9,11
0,6
15,13
8,5
10,2
14,1