fork download
  1. #include <iostream>
  2. #include <iterator>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <queue>
  6. #include <cassert>
  7.  
  8.  
  9. template<typename Iterator, typename Operation>
  10. void iterate_ranges (Iterator from, Iterator to, Operation op) {
  11. using R = typename std::iterator_traits<Iterator>::value_type;
  12. using N = typename std::decay<decltype(std::declval<R>().first)>::type;
  13. using P = std::pair<N, R>;
  14. auto compare = [](P const & left, P const & right) {
  15. return left.first > right.first;};
  16.  
  17. std::priority_queue<P, std::vector<P>, decltype(compare)> queue(compare);
  18.  
  19. auto push = [& queue] (P p) {
  20. if (p.first < p.second.last) queue.push(p); };
  21. auto next = [](P const & p) -> P {
  22. assert(p.second.step > 0);
  23. return {p.first + p.second.step, p.second}; };
  24. auto init = [&push] (R const & r) {
  25. push({r.first, r}); };
  26.  
  27. std::for_each(from, to, init);
  28.  
  29. if (queue.empty()) return;
  30.  
  31. N last = queue.top().first;
  32. push(next(queue.top()));
  33. queue.pop();
  34. op(last);
  35.  
  36. while (! queue.empty()) {
  37. P current = queue.top();
  38. queue.pop();
  39. if (current.first != last) {
  40. op(current.first);
  41. last = current.first;
  42. }
  43. push(next(current));
  44. }
  45. }
  46.  
  47. struct Range {
  48. int first;
  49. int last;
  50. int step;
  51. };
  52.  
  53.  
  54. int main() {
  55. Range ranges [] = {
  56. {1, 10, 2},
  57. {2, 50, 5}};
  58.  
  59. auto print = [](auto n) { std::cout << n << std::endl; };
  60.  
  61. iterate_ranges(std::begin(ranges), std::end(ranges), print);
  62. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
1
2
3
5
7
9
12
17
22
27
32
37
42
47