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 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
|
#ifndef __COUNTER_H_INCLUDED__
#define __COUNTER_H_INCLUDED__
//======================
// INCLUDED DEPENDENCIES
#include <iostream>
#include <map>
//======================
//======================
// INTERFACE
template <class Key, class Val>
class Counter
{
protected:
std::map<Key, Val> counter;
Val sum;
public:
Counter();
Val& operator[] (Key);
void increment_count(Key,Val);
void increment_all(Val);
void normalize();
void print();
Key argmax();
};
//======================
template<class Key, class Val>
Counter<Key,Val>::Counter()
{
sum = Val();
}
template <class Key, class Val>
Val& Counter<Key,Val>::operator[] (Key x)
{
if (counter.find(x) != counter.end())
return counter[x];
else
{
counter.insert(std::pair<Key,Val>(x, Val()));
return counter[x];
}
}
template <class Key, class Val>
void Counter<Key,Val>::increment_count(Key key, Val incrementVal)
{
if (counter.find(key) != counter.end())
{
counter[key]+=incrementVal;
sum+=incrementVal;
}
else
{
counter.insert(std::pair<Key,Val>(key,incrementVal));
sum+=incrementVal;
}
}
template <class Key, class Val>
void Counter<Key,Val>::increment_all(Val incrementVal=1)
{
for (std::map<Key, Val>::iterator it = counter.begin(); it != counter.end(); it++)
{
it->second += incrementVal;
sum+= incrementVal;
}
}
template <class Key, class Val>
void Counter<Key,Val>::normalize()
{
for (std::map<Key, Val>::iterator it = counter.begin(); it != counter.end(); it++)
it->second/=sum;
}
template<class Key, class Val>
void Counter<Key,Val>::print()
{
std::cout << "{";
std::map<Key, Val>::iterator it = counter.begin();
if (it != counter.end())
{
std::cout << it->first << ": " << it->second;
it++;
}
for (it; it != counter.end(); it++)
std::cout << ", " << it->first << ": " << it->second ;
std::cout << "}\n";
}
template<class Key, class Val>
Key Counter<Key,Val>::argmax()
{
std::map<Key, Val>::iterator it = counter.begin();
Val max = it->second;
Key argmax = it->first;
for (it; it != counter.end(); it++)
if (it->second > max)
{
max = it->second;
argmax = it->first;
}
return argmax;
}
#endif
|