/* This is identical to histogram_map.cpp, except we're using an unordered map. Because of that, we have to sort the values when we call get_data. */ #include #include #include #include #include #include #include #include "histogram.hpp" using namespace std; /* This is my internal definition of a map version of the histogram class. */ class Histo_UMap { public: unordered_map Elts; double Bin_Size; }; /* The constructor / destructor, etc are all the same as for the vector, except they use the Histo_UMap class rather than Histo_Vector. */ Histogram::Histogram() { Histo_UMap *hv; hv = new Histo_UMap; hv->Bin_Size = -1; state = (void *) hv; } Histogram::~Histogram() { Histo_UMap *hv; hv = (Histo_UMap *) state; delete hv; } Histogram::Histogram(const Histogram &h) { Histo_UMap *hv; hv = new Histo_UMap; state = (void *) hv; *this = h; } Histogram& Histogram::operator= (const Histogram &h) { Histo_UMap *hv_original, *hv_copy; hv_original = (Histo_UMap *) h.state; hv_copy = (Histo_UMap *) state; *hv_copy = *hv_original; return *this; } void Histogram::Clear() { Histo_UMap *hv; hv = (Histo_UMap *) state; hv->Elts.clear(); } bool Histogram::Set_Bin_Size(double bs) { Histo_UMap *hv; hv = (Histo_UMap *) state; if (hv->Elts.size() != 0) return false; if (bs <= 0) return false; hv->Bin_Size = bs; return true; } double Histogram::Get_Bin_Size() const { Histo_UMap *hv; hv = (Histo_UMap *) state; return hv->Bin_Size; } bool Histogram::Add_Value(double d) { Histo_UMap *hv; int bin; hv = (Histo_UMap *) state; if (d < 0) return false; if (hv->Bin_Size < 0) return false; bin = (int) floor(d/hv->Bin_Size); hv->Elts[bin]++; return true; } bool Histogram::Get_Data(vector &bin_ids, vector &num_elts) const { Histo_UMap *hv; size_t i; unordered_map ::iterator mit; hv = (Histo_UMap *) state; if (hv->Bin_Size < 0) return false; bin_ids.clear(); num_elts.clear(); /* Create the bins array and sort it. */ for (mit = hv->Elts.begin(); mit != hv->Elts.end(); mit++) { bin_ids.push_back(mit->first); } sort(bin_ids.begin(), bin_ids.end()); for (i = 0; i < bin_ids.size(); i++) { mit = hv->Elts.find(bin_ids[i]); num_elts.push_back(mit->second); } return true; };