chunkedseq
container library for large in-memory data sets
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
chunkedseq_1.cpp
Go to the documentation of this file.
1 
15 #include <iostream>
17 
18 #include "chunkedseq.hpp"
19 
21 
22 // moves items which satisfy a given predicate p from src to dst
23 // preserving original order of items in src
24 template <class Predicate_function>
25 void pkeep_if(cbdeque& dst, cbdeque& src, const Predicate_function& p) {
26 
27  const int cutoff = 8096;
28 
29  long sz = src.size();
30 
31  if (sz <= cutoff) {
32 
33  // compute result in a sequential fashion
34  while (sz-- > 0) {
35  long item = src.pop_back();
36  if (p(item))
37  dst.push_front(item);
38  }
39 
40  } else {
41 
42  cbdeque src2;
43  cbdeque dst2;
44 
45  // divide the input evenly in two halves
46  size_t mid = sz / 2;
47  src.split(mid, src2);
48 
49  // recurse on subproblems
50  // calls can execute in parallel
51  pkeep_if(dst, src, p);
52  pkeep_if(dst2, src2, p);
53 
54  // combine results (after parallel calls complete)
55  dst.concat(dst2);
56 
57  }
58 }
59 
60 int main(int argc, const char * argv[]) {
61 
62  cbdeque src;
63  cbdeque dst;
64 
65  const long n = 1000000;
66 
67  // fill the source container with [1, ..., 2n]
68  for (long i = 1; i <= 2*n; i++)
69  src.push_back(i);
70 
71  // leave src empty and dst = [1, 3, 5, ... n-1]
72  pkeep_if(dst, src, [] (long x) { return x%2 == 1; });
73 
74  assert(src.empty());
75  assert(dst.size() == n);
76 
77  // calculate the sum
78  long sum = 0;
79  while (! dst.empty())
80  sum += dst.pop_front();
81 
82  // the sum of n consecutive odd integers starting from 1 equals n^2
83  assert(sum == n*n);
84  std::cout << "sum = " << sum << std::endl;
85 
86  return 0;
87 
88 }
void push_front(const value_type &x)
Adds item at the beginning.
void concat(self_type &other)
Merges with content of another container.
void push_back(const value_type &x)
Adds item at the end.
size_type size() const
Returns size.
void pkeep_if(cbdeque &dst, cbdeque &src, const Predicate_function &p)
value_type pop_front()
Deletes first item.
value_type pop_back()
Deletes last item.
int main(int argc, const char *argv[])
bool split(const Pred &p, reference middle_item, self_type &other)
bool empty() const
Test whether the container is empty.
Chunked-sequence functor.