Skip to content

Instantly share code, notes, and snippets.

@Gydo194
Created June 5, 2018 14:53
Show Gist options
  • Save Gydo194/7a2d3df656eb5ac9bd543cf74fdd9128 to your computer and use it in GitHub Desktop.
Save Gydo194/7a2d3df656eb5ac9bd543cf74fdd9128 to your computer and use it in GitHub Desktop.
STL map utilities
/*
* map_utils.hpp
* Utilities for accessing STL maps
* original work by: Gydo194
*/
#ifndef MAP_GET_H
#define MAP_GET_H
#include <map>
using namespace std;
template<class K, class V>
bool map_get(map<K,V> *src_map, K *key_source, V *dest_var) {
try
{
*dest_var = src_map->at(*key_source);
return true;
}
catch(out_of_range oor)
{
return false;
}
}
/*
* copies a value from the map into the variable pointed to, leaves the mem. loc and pointer
* untouched when the key is not in the map
*/
template<class K, class V>
bool map_get(map<K,V> *src_map, const K key_source, V *dest_var) {
try
{
*dest_var = src_map->at(key_source);
return true;
}
catch(out_of_range oor)
{
return false;
}
}
/*
* allocates an new NULL value on the specified key in the map
*/
template<class K, class V>
bool map_allocate_empty(map<K,V> *dest_map, const K key)
{
V empty_val;
pair<K,V> ins = pair<K,V>(key,empty_val);
dest_map->insert(ins);
return true;
}
template<class K, class V>
bool map_contains(map<K,V> *src_map, const K key)
{
return 1 == src_map->count(key);
}
/*
* updates a value in the map.
*/
template<class K, class V>
bool map_set(map<K,V> *dest_map, const K key, V *value)
{
try
{
dest_map->at(key) = *value;
return true;
}
catch(out_of_range oor)
{
return false;
}
}
/*
* inserts a new value into the map
*/
template<class K, class V>
bool map_insert(map<K,V> *dest_map, K key, V value)
{
return dest_map->insert(pair<K,V>(key,value)).second;
}
/*
* map_access returns a reference to the value from the map.
* the benefit of this is the ability to actually set the value from the result of this function.
* this function should be avoided in its current state, as it will return an invalid reference
* in case of an out_of_range.
*/
template<class K, class V>
V& map_access(map<K,V> *src_map, const K *key)
{
try
{
return src_map->at(*key);
}
catch(out_of_range oor)
{
//cout << "map_access caught OOR\n";
//map_allocate_empty<K,V>(src_map,
}
}
#endif //MAP_GET_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment