10#include <unordered_map>
31template <
typename T >
36 : _history_size( history_size )
37 , _last_stable_value( 0 )
40 throw std::runtime_error(
"history size must be > 0" );
49 const std::lock_guard< std::mutex > lock( _mutex );
52 _last_stable_value = val;
53 _last_stable_percentage = 100.f;
54 _values.push_back( val );
58 if( _values.size() >= _history_size )
60 _last_stable_percentage = 0.f;
61 _values.push_back( val );
65 T
get(
float stabilization_percent = 0.75f )
const
67 if( stabilization_percent <= 0.f || stabilization_percent > 1.f )
68 throw std::runtime_error(
"illegal stabilization percentage "
69 + std::to_string( stabilization_percent ));
71 std::lock_guard< std::mutex > lock( _mutex );
74 throw std::runtime_error(
"history is empty; no stable value" );
76 if( _last_stable_percentage != stabilization_percent )
78 _last_stable_percentage = stabilization_percent;
79 std::unordered_map< T, int > values_count_map;
80 std::pair< T, int > most_stable_value = { 0.f, 0 };
81 for( T val : _values )
83 auto current_val = ++values_count_map[val];
85 if( most_stable_value.second < current_val )
87 most_stable_value.first = val;
88 most_stable_value.second = current_val;
92 auto new_value_percentage
93 = most_stable_value.second /
static_cast< float >( _values.size() );
99 if( new_value_percentage >= _last_stable_percentage
100 || values_count_map.find( _last_stable_value ) == values_count_map.end() )
102 _last_stable_value = most_stable_value.first;
106 return _last_stable_value;
111 const std::lock_guard< std::mutex > lock( _mutex );
117 const std::lock_guard< std::mutex > lock( _mutex );
118 return _values.empty();
122 std::deque< T > _values;
123 const size_t _history_size;
124 mutable T _last_stable_value;
125 mutable float _last_stable_percentage;
126 mutable std::mutex _mutex;
Definition: stabilized-value.h:33
stabilized_value()=delete
void clear()
Definition: stabilized-value.h:109
stabilized_value(const stabilized_value &)=delete
bool empty() const
Definition: stabilized-value.h:115
stabilized_value(size_t history_size)
Definition: stabilized-value.h:35
T get(float stabilization_percent=0.75f) const
Definition: stabilized-value.h:65
void add(T val)
Definition: stabilized-value.h:47
Definition: stabilized-value.h:12