### Exponential Moving Average with std:: map

hey guys,
i want to use exponential moving average with std::map. Actually what i have to do is whenever the duplicate key arrives during run time the mapped value of that key should be replace or update by the average value.
for example:
in map there are two pairs:
("a",4) and("b",8)
and when again the key value pair ("a",6) comes
the value in the map should become ("a",5) which is the average of 4 and 6 and same thing for key "b". And for this i need to use exponential moving average and i am confused with that. Please help me.. Thanks in advance...
I don't know your situation, but could you use a std::multimap? You could store each occurrence in the multimap, then do the exponential average when needed and convert to a std::map in one function.
i can't use multimap my mentor told me to use map only he don't want that we store duplcate values...
Provided that `M[key]` exists
`M[key] = (M[key] + new_value)/2;`
I played around a bit.

 ``1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374`` ``````#include #include #include #include typedef std::map map_type ; const double smoothingFactor = .5 ; double addDataPoint(map_type & m, map_type::value_type data) { map_type::iterator it = m.find(data.first) ; if ( it == m.end() ) { m[data.first] = data.second ; return data.second ; } return it->second = smoothingFactor * data.second + (1-smoothingFactor) * it->second ; } double getAverage(const map_type& m, const map_type::key_type & key ) { map_type::const_iterator it = m.find(key) ; if ( it == m.end() ) throw std::logic_error( "getAverage called for non-existent key: \"" + key + '"') ; return it->second ; } std::ostream& operator<<(std::ostream& os, const map_type & map ) { map_type::const_iterator it ; for ( it = map.begin(); it != map.end(); ++it ) os << it->first << ": " << it->second << '\n' ; return os ; } int main() { map_type emaMap ; try { std::cout << "addDataPoint(\"a\", 4)\n" ; addDataPoint(emaMap, std::make_pair("a", 4)) ; std::cout << emaMap << '\n' ; std::cout << "addDataPoint(\"b\", 8)\n" ; addDataPoint(emaMap, std::make_pair("b", 8)) ; std::cout << emaMap << '\n' ; std::cout << "addDataPoint(\"a\", 6)\n" ; addDataPoint(emaMap, std::make_pair("a", 6)) ; std::cout << emaMap << '\n' ; std::cout << "addDataPoint(\"b\", 12)\n" ; addDataPoint(emaMap, std::make_pair("b", 12)) ; std::cout << emaMap << '\n' ; std::cout << "getAverage(\"a\")\n" ; std::cout << getAverage(emaMap, "a") << "\n\n" ; std::cout << "getAverage(\"b\")\n" ; std::cout << getAverage(emaMap, "b") << "\n\n" ; std::cout << "getAverage(\"c\")\n" ; std::cout << getAverage(emaMap, "c") << "\n\n" ; } catch (std::exception& ex) { std::cout << ex.what() << '\n' ; } }``````

http://ideone.com/XXD34x

(Not sure what this has to do with UNIX/Linux programming!)
Topic archived. No new replies allowed.