-
Notifications
You must be signed in to change notification settings - Fork 0
/
paginator.h
75 lines (61 loc) · 1.62 KB
/
paginator.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#pragma once
#include <ostream>
#include <iterator>
#include <algorithm>
#include <vector>
template <typename Iterator>
class IteratorRange {
public:
IteratorRange(const Iterator& begin, const Iterator& end)
: first_(begin)
, last_(end)
, size_(std::distance(first_, last_)) {
}
Iterator begin() const {
return first_;
}
Iterator end() const {
return last_;
}
size_t size() const {
return size_;
}
private:
Iterator first_, last_;
size_t size_;
};
template <typename Iterator>
std::ostream& operator<<(std::ostream& out, const IteratorRange<Iterator>& range) {
for (Iterator it = range.begin(); it != range.end(); ++it) {
out << *it;
}
return out;
}
template <typename Iterator>
class Paginator {
public:
Paginator(const Iterator& begin, const Iterator& end, size_t page_size) {
for (size_t left = std::distance(begin, end); left > 0;) {
const size_t current_page_size = std::min(page_size, left);
const Iterator current_page_end = std::next(begin, current_page_size);
pages_.push_back({begin, current_page_end});
left -= current_page_size;
begin = current_page_end;
}
}
auto begin() const {
return pages_.begin();
}
auto end() const {
return pages_.end();
}
size_t size() const {
return pages_.size();
}
private:
std::vector<IteratorRange<Iterator>> pages_;
};
template <typename Container>
auto Paginate(const Container& c, size_t page_size) {
return Paginator(begin(c), end(c), page_size);
}