Skip to content

Instantly share code, notes, and snippets.

@jjfiv
Created March 1, 2013 22:15
Show Gist options
  • Select an option

  • Save jjfiv/5068356 to your computer and use it in GitHub Desktop.

Select an option

Save jjfiv/5068356 to your computer and use it in GitHub Desktop.
Generic update or insert of a key within a C++ map, efficiently
#include <map>
#include <functional> // C++11
// general method stolen from: http://stackoverflow.com/questions/97050/stdmap-insert-or-stdmap-find
template <class K, class V>
void setOrUpdate(map<K, V> &tree, const K& key, const V& amount, function<void (V&)> updater) {
auto ptr = tree.lower_bound(key);
if(ptr != tree.end() && ptr->first == key) {
// key already exists
updater(ptr->second);
} else {
// C++11 pair syntax is the bomb!
tree.insert(ptr, {key, amount});
}
}
template <class T>
map<T, int> counts(const vector<T> &input) {
map<T, int> results;
for(const T& x : input) {
setOrUpdate<T,int>(results, x, 1,
[](int &prev) { prev++; });
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment