11 #ifndef __RunningMedian_h
12 #define __RunningMedian_h
38 template<
typename T,
typename Compare = std::less<T> >
41 mutable std::multiset<T,Compare> lowerHalf, upperHalf;
48 void set_nth (
unsigned n) { nth = n; }
49 unsigned get_nth ()
const {
return nth; }
52 void clear () { lowerHalf.clear(); upperHalf.clear(); }
55 void insert (
const T& element)
58 std::cerr <<
"insert sizes lt=" << lowerHalf.size()
59 <<
" gt=" << upperHalf.size()
60 <<
" element=" << element <<
" low=" << *upperHalf.begin()
64 if (upperHalf.size() && lt( element, *upperHalf.begin() ))
65 lowerHalf.insert( element );
67 upperHalf.insert( element );
70 std::cerr <<
"insert. sizes lt=" << lowerHalf.size()
71 <<
" gt=" << upperHalf.size() << std::endl;
76 void erase (
const T& element)
79 std::cerr <<
"erase sizes lt=" << lowerHalf.size()
80 <<
" gt=" << upperHalf.size()
81 <<
" element=" << element <<
" low=" << *upperHalf.begin()
85 if (lt(element, *upperHalf.begin()))
86 lowerHalf.erase( lowerHalf.find( element ) );
88 upperHalf.erase( upperHalf.find( element ) );
91 std::cerr <<
"erase. sizes lt=" << lowerHalf.size()
92 <<
" gt=" << upperHalf.size() << std::endl;
100 std::cerr <<
"median nth=" << nth <<
" sizes lt=" << lowerHalf.size()
101 <<
" gt=" << upperHalf.size() <<
" low=" << *upperHalf.begin()
105 while (upperHalf.size() > nth+1)
106 lowerHalf.insert( popFirstElement( upperHalf ));
108 while (lowerHalf.size() > nth)
109 upperHalf.insert( popLastElement( lowerHalf ));
111 return *upperHalf.begin();
118 static T popFirstElement (std::multiset<T,Compare>& S)
120 T result = *(S.begin());
121 S.erase( S.begin() );
125 static T popLastElement (std::multiset<T,Compare>& S)
127 typename std::multiset<T>::iterator it = S.end();