SHARE
TWEET

Untitled

a guest Aug 17th, 2019 83 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include "test_runner.h"
  2.  
  3. #include <numeric>
  4. #include <iostream>
  5. #include <vector>
  6. #include <string>
  7. #include <algorithm>
  8. using namespace std;
  9.  
  10. template <typename Iterator>
  11. struct IteratorRange {
  12.   Iterator first_;
  13.   Iterator last_;
  14.  
  15.   Iterator begin() {
  16.     return first_;
  17.   }
  18.  
  19.   Iterator end() {
  20.     return last_;
  21.   }
  22. };
  23.  
  24. template <typename Iterator>
  25. class Paginator {
  26. public:
  27.   Paginator(Iterator begin, Iterator end, size_t page_size)
  28.     : begin_(begin)
  29.     , end_(end)
  30.     , page_size_(page_size) {}
  31.  
  32.   IteratorRange<Iterator> begin() {
  33.     size_t offset = min<size_t>(end_ - begin_, page_size_);
  34.     return {begin_, begin_ + offset};
  35.   }
  36.  
  37.   IteratorRange<Iterator> end() {
  38.     return {end_, end_};
  39.   }
  40.  
  41.   void operator++() {
  42.     page_size_++;
  43.   }
  44.  
  45.   size_t size() const {
  46.     size_t size = (end_ - begin_) / page_size_;
  47.     if ((end_ - begin_) % page_size_ != 0) {
  48.       size++;
  49.     }
  50.     return size;
  51.   }
  52.  
  53. private:
  54.   Iterator begin_;
  55.   Iterator end_;
  56.   size_t page_size_;
  57.   size_t curr_;
  58. };
  59.  
  60. template <typename C>
  61. Paginator<typename C::iterator> Paginate(C& c, size_t page_size) {
  62.   auto p = Paginator<typename C::iterator>(c.begin(), c.end(), page_size);
  63.   return p;
  64. }
  65.  
  66. void TestPageCounts() {
  67.   vector<int> v(15);
  68.  
  69.   ASSERT_EQUAL(Paginate(v, 1).size(), v.size());
  70.   ASSERT_EQUAL(Paginate(v, 3).size(), 5u);
  71.   ASSERT_EQUAL(Paginate(v, 5).size(), 3u);
  72.   ASSERT_EQUAL(Paginate(v, 4).size(), 4u);
  73.   ASSERT_EQUAL(Paginate(v, 15).size(), 1u);
  74.   ASSERT_EQUAL(Paginate(v, 150).size(), 1u);
  75.   ASSERT_EQUAL(Paginate(v, 14).size(), 2u);
  76. }
  77.  
  78. void TestLooping() {
  79.   vector<int> v(15);
  80.   iota(begin(v), end(v), 1);
  81.  
  82.   Paginator<vector<int>::iterator> paginate_v(v.begin(), v.end(), 6);
  83.   ostringstream os;
  84.   for (const auto& page : paginate_v) {
  85.     for (int x : page) {
  86.       os << x << ' ';
  87.     }
  88.     os << '\n';
  89.   }
  90.  
  91.   ASSERT_EQUAL(os.str(), "1 2 3 4 5 6 \n7 8 9 10 11 12 \n13 14 15 \n");
  92. }
  93.  
  94. int main() {
  95.   TestRunner tr;
  96.   RUN_TEST(tr, TestPageCounts);
  97.   RUN_TEST(tr, TestLooping);
  98. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top