@@ -12,58 +12,83 @@ class binary_counter
1212
1313public:
1414 // Constructor. Input arguments: op and zero.
15- binary_counter (const Op& op, const T& zero) :
16- op (op), zero(zero) {
17- counter.reserve (24 );
15+ binary_counter (const Op & op, const T & zero) : op(op), zero(zero)
16+ {
17+ counter.reserve (24 );
1818 }
1919
20+ void print ()
21+ {
22+ auto first = counter.begin ();
23+ auto last = counter.end ();
24+
25+ while (first != last)
26+ {
27+ auto it = *first;
28+ std::cout << *it << " ," ;
29+ ++first;
30+ }
31+ std::cout << std::endl;
32+ }
2033 // add
21- void add (T x) {
34+ void add (T x)
35+ {
2236 x = add_to_counter (counter.begin (), counter.end (), op, zero, x);
23- if (x != zero) counter.push_back (x);
37+ if (x != zero)
38+ counter.push_back (x);
2439 }
2540
2641 // reduce
2742 // returns: value of the counter
28- T reduce () {
43+ T reduce ()
44+ {
2945 return reduce_counter (counter.begin (), counter.end (), op, zero);
3046 }
3147};
3248
3349template <typename T, typename I, typename Op>
3450// requires Op is BinaryOperation(T)
35- // and Op is associative
51+ // and Op is associative
3652// and I is ForwardIterator and ValueType(I) == T
37- T add_to_counter (I first, I last, Op op, const T& zero, T carry) {
38- // precondition: carry != zero
39- while (first != last) {
40- if (* first == zero) {
41- *first = carry;
42- return zero;
43- }
44- carry = op ( *first, carry) ;
45- *first = zero;
46- ++first ;
53+ T add_to_counter (I first, I last, Op op, const T & zero, T carry)
54+ {
55+ // precondition: carry != zero
56+ while ( first != last)
57+ {
58+ if (*first == zero)
59+ {
60+ *first = carry;
61+ std::cout << " add_to_counter returning carry: zero" << std::endl ;
62+ return zero ;
4763 }
48- return carry;
64+ carry = op (*first, carry);
65+ *first = zero;
66+ ++first;
67+ }
68+ std::cout << " add_to_counter returning carry: " << *carry << std::endl;
69+ return carry;
4970}
5071
5172template <typename T, typename I, typename Op>
5273// requires Op is BinaryOperation(T)
53- // and Op is associative
74+ // and Op is associative
5475// and I is ForwardIterator and ValueType(I) == T
55- T reduce_counter (I first, I last, Op op, const T& zero) {
56- while (first != last && *first == zero) {
57- ++first;
58- }
59- if (first == last) return zero;
76+ T reduce_counter (I first, I last, Op op, const T &zero)
77+ {
78+ while (first != last && *first == zero)
79+ {
80+ ++first;
81+ }
82+ if (first == last)
83+ return zero;
6084
61- T result = *first;
62- while (++first != last) {
63- if (*first != zero) {
64- result = op (*first, result);
65- }
85+ T result = *first;
86+ while (++first != last)
87+ {
88+ if (*first != zero)
89+ {
90+ result = op (*first, result);
6691 }
67- return result;
68- }
69-
92+ }
93+ return result;
94+ }
0 commit comments