You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // histogram.hpp
  2. // Copyright (C) 2006 - 2009 MicroNeil Research Corporation
  3. // Class to capture a histogram of events using a <set>
  4. #ifndef mn_histogram_included
  5. #define mn_histogram_included
  6. #include <set>
  7. using namespace std;
  8. /** The Histogram class is managed set of HistogramRecords.
  9. *** We play some naughty tricks with pointers to break the rules and
  10. *** directly manipulate the counts of HistogramRecords stored in the
  11. *** set - thus saving space, complexity, and cycles. The set allows us
  12. *** to add new records as needed and locate existing records quickly.
  13. *** At any point in time, the set contains all of the event (hit) counts
  14. *** ordered by key.
  15. **/
  16. class HistogramRecord { // A record to assocate a key and count.
  17. public:
  18. int Key; // Here is the key.
  19. int Count; // Here is the count.
  20. HistogramRecord(const int NewKey) : // We must have a key to make one.
  21. Key(NewKey), Count(0) {} // and a new one starts at count 0.
  22. bool operator<(const HistogramRecord& Right) const { // To live in a set we need to <
  23. return (Key < Right.Key); // properly based on the key.
  24. }
  25. };
  26. class Histogram : public set<HistogramRecord> { // A Histogram is a set of HistogramRecords
  27. private: // and a private hit counter...
  28. int HitCount;
  29. public:
  30. Histogram() : HitCount(0) {}
  31. // with a few extra public functions. The
  32. int hit(const int EventKey, const int Adjustment = 1) { // hit() method increments a specific count.
  33. HistogramRecord E(EventKey); // First, make a record for the event key.
  34. insert(E); // Insert the new record (if it's not there).
  35. set<HistogramRecord>::iterator iE = // Find either the pre-existing or the new
  36. find(E); // record for this key.
  37. int* C; // Play naughty pointer games to access
  38. C = const_cast<int*>(&((*iE).Count)); // the Count for this record inside the
  39. (*C) += Adjustment; // set and add our Adjustment to it.
  40. HitCount += Adjustment; // Accumulate the adjustments overall.
  41. return(*C); // Return the count for this key.
  42. }
  43. int Hits() { return HitCount; } // Return the sum of hits so far.
  44. void reset() { // Reset the histogram to zero.
  45. HitCount = 0; // That means no counts, and
  46. clear(); // an empty set of records.
  47. }
  48. };
  49. #endif