brians | 343bc11 | 2013-02-10 01:53:46 +0000 | [diff] [blame] | 1 | #ifndef AOS_MAP_UTILS_H_ |
| 2 | #define AOS_MAP_UTILS_H_ |
| 3 | |
| 4 | // TODO(aschuh): Template std::map as well. |
| 5 | // Maps the key to the value, inserting it if it isn't there, or replacing it if |
| 6 | // it is. Returns true if the key was added and false if it was replaced. |
| 7 | template <typename K, typename V> |
| 8 | bool InsertIntoMap(std::map<K, V> *my_map, const K &key, const V &new_value) { |
| 9 | std::pair<typename std::map<K, V>::iterator, bool> element; |
| 10 | element = my_map->insert(std::pair<K,V>(key, new_value)); |
| 11 | if (element.second == false) { |
| 12 | element.first->second = new_value; |
| 13 | } |
| 14 | return element.second; |
| 15 | } |
| 16 | |
| 17 | // Gets the value for the key from the map. |
| 18 | // Returns true if the key was found and then populates *value with the value. |
| 19 | // Otherwise, leaves value alone and returns false. |
| 20 | template <typename K, typename V> |
| 21 | bool GetFromMap(const std::map<K, V> &my_map, const K &key, V *value) { |
| 22 | typename std::map<K, V>::const_iterator element = my_map.find(key); |
| 23 | if (element != my_map.end()) { |
| 24 | *value = element->second; |
| 25 | return true; |
| 26 | } |
| 27 | return false; |
| 28 | } |
| 29 | |
| 30 | #endif // AOS_MAP_UTILS_H_ |