-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCounter.h
79 lines (68 loc) · 1.94 KB
/
Counter.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
76
77
78
79
#ifndef CH1_COUNTER_H
#define CH1_COUNTER_H
#include <string>
#include <ostream>
using std::string;
using std::to_string;
using std::ostream;
/**
* The {@code Counter} class is a mutable data type to encapsulate a counter.
* <p>
* For additional documentation,
* see <a href="https://algs4.cs.princeton.edu/12oop">Section 1.2</a> of
* <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
*
* @author Robert Sedgewick
* @author Kevin Wayne
*/
class Counter {
public:
/**
* Initializes a new counter starting at 0, with the given id.
* @param id the name of the counter
*/
Counter(string id) : name(id), count(0) {}
/**
* Increments the counter by 1.
*/
void increment() {
count++;
}
/**
* Returns the current value of this counter.
*
* @return the current value of this counter
*/
int tally() const {
return count;
}
/**
* Returns a string representation of this counter.
*
* @return a string representation of this counter
*/
friend ostream &operator<<(ostream &stream, const Counter &item);
/**
* Compares this counter to the specified counter.
*
* @param that the other counter
* @return {@code 0} if the value of this counter equals
* the value of that counter; a negative integer if
* the value of this counter is less than the value of
* that counter; and a positive integer if the value
* of this counter is greater than the value of that
* counter
*/
friend bool operator<(Counter &a1, Counter &a2);
private:
const string name; // counter name
int count; // current value
};
ostream &operator<<(ostream &stream, const Counter &item) {
stream << item.count << " " << item.name;
return stream;
}
bool operator<(Counter &a1, Counter &a2) {
return a1.count < a2.count;
}
#endif //CH1_COUNTER_H