fork download
  1. #include <vector>
  2. #include <stdexcept>
  3. #include <algorithm>
  4.  
  5. template<class iterator_type>
  6. class combination_generator {
  7. iterator_type first, last;
  8. std::vector<bool> use;
  9. unsigned r;
  10. typedef typename std::iterator_traits<iterator_type>::value_type element_type;
  11. public:
  12. combination_generator(iterator_type first_, iterator_type last_, unsigned r_) : first(first_), last(last_) , r(r_)
  13. {
  14. use.resize(std::distance(first, last), false);
  15. if (r > use.size())
  16. throw std::domain_error("can't select more elements than exist for combination");
  17. std::fill(use.end()-r, use.end(), true);
  18. }
  19. template<class output_iterator>
  20. bool operator()(output_iterator result)
  21. {
  22. iterator_type c=first;
  23. for (unsigned i = 0; i<use.size(); ++i,++c) {
  24. if (use[i])
  25. *result++ = *c;
  26. }
  27. return std::next_permutation(use.begin(), use.end());
  28. }
  29. };
  30. template<class iterator_type>
  31. combination_generator<iterator_type> make_combination_generator(iterator_type first, iterator_type last, unsigned r)
  32. {return combination_generator<iterator_type>(first, last, r);}
  33.  
  34. #include <string>
  35. #include <iostream>
  36. #include <iterator>
  37.  
  38. int main() {
  39. std::string data[] = {"HELLO", "WORLD", "ALPHA", "BET"};
  40. auto generator = make_combination_generator(data, data+4, 2);
  41. std::ostream_iterator<std::string> it(std::cout, " ");
  42. while(generator(it))
  43. std::cout << '\n';
  44. return 0;
  45. }
  46.  
Success #stdin #stdout 0s 3432KB
stdin
Standard input is empty
stdout
ALPHA BET 
WORLD BET 
WORLD ALPHA 
HELLO BET 
HELLO ALPHA 
HELLO WORLD