fork download
  1. #include <utility>
  2. #include <cstddef>
  3. #include <vector>
  4.  
  5. using std::size_t;
  6.  
  7. namespace details {
  8. template<typename Lambda>
  9. void for_each_multiset_combo_worker( std::vector<size_t> const& counts, Lambda&& lambda, size_t depth, std::vector<size_t>& current )
  10. {
  11. if (depth >= counts.size()) {
  12. lambda( current );
  13. return;
  14. }
  15. for (size_t i = 0; i <= counts[depth]; ++i) {
  16. current.push_back(i);
  17. for_each_multiset_combo_worker( counts, lambda, depth+1, current );
  18. current.pop_back();
  19. }
  20. }
  21. }
  22. template<typename Lambda>
  23. void for_each_multiset_combo( std::vector<size_t> const& counts, Lambda&& lambda )
  24. {
  25. std::vector<size_t> current;
  26. current.reserve( counts.size() );
  27. details::for_each_multiset_combo_worker( counts, std::forward<Lambda>(lambda), 0, current );
  28. }
  29. #include <iostream>
  30.  
  31. int main() {
  32. std::vector<size_t> multiset = {3, 2, 1, 1};
  33. size_t counter = 0;
  34. for_each_multiset_combo( multiset, [&]( std::vector<size_t> const& counts ){
  35. std::cout << counter << ": [";
  36. for(auto it = counts.begin(); it != counts.end(); ++it) {
  37. if (it != counts.begin()) {
  38. std::cout << ", ";
  39. }
  40. std::cout << *it;
  41. }
  42. std::cout << "]\n";
  43. ++counter;
  44. });
  45. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
0: [0, 0, 0, 0]
1: [0, 0, 0, 1]
2: [0, 0, 1, 0]
3: [0, 0, 1, 1]
4: [0, 1, 0, 0]
5: [0, 1, 0, 1]
6: [0, 1, 1, 0]
7: [0, 1, 1, 1]
8: [0, 2, 0, 0]
9: [0, 2, 0, 1]
10: [0, 2, 1, 0]
11: [0, 2, 1, 1]
12: [1, 0, 0, 0]
13: [1, 0, 0, 1]
14: [1, 0, 1, 0]
15: [1, 0, 1, 1]
16: [1, 1, 0, 0]
17: [1, 1, 0, 1]
18: [1, 1, 1, 0]
19: [1, 1, 1, 1]
20: [1, 2, 0, 0]
21: [1, 2, 0, 1]
22: [1, 2, 1, 0]
23: [1, 2, 1, 1]
24: [2, 0, 0, 0]
25: [2, 0, 0, 1]
26: [2, 0, 1, 0]
27: [2, 0, 1, 1]
28: [2, 1, 0, 0]
29: [2, 1, 0, 1]
30: [2, 1, 1, 0]
31: [2, 1, 1, 1]
32: [2, 2, 0, 0]
33: [2, 2, 0, 1]
34: [2, 2, 1, 0]
35: [2, 2, 1, 1]
36: [3, 0, 0, 0]
37: [3, 0, 0, 1]
38: [3, 0, 1, 0]
39: [3, 0, 1, 1]
40: [3, 1, 0, 0]
41: [3, 1, 0, 1]
42: [3, 1, 1, 0]
43: [3, 1, 1, 1]
44: [3, 2, 0, 0]
45: [3, 2, 0, 1]
46: [3, 2, 1, 0]
47: [3, 2, 1, 1]