00001 /* $Id: map_utils.hpp 54015 2012-04-29 14:15:54Z mordante $ */ 00002 /* 00003 Copyright (C) 2007 - 2012 by David White <dave.net> 00004 Part of the Silver Tree Project 00005 00006 This program is free software; you can redistribute it and/or modify 00007 it under the terms of the GNU General Public License as published by or later. 00008 This program is distributed in the hope that it will be useful, 00009 but WITHOUT ANY WARRANTY. 00010 00011 See the COPYING file for more details. 00012 */ 00013 00014 #ifndef MAP_UTILS_HPP_INCLUDED 00015 #define MAP_UTILS_HPP_INCLUDED 00016 00017 #include <map> 00018 #include <stdexcept> 00019 00020 template<typename K, typename V> 00021 const V& map_get_value_default(const std::map<K,V>& m, const K& key, const V& val) { 00022 typename std::map<K,V>::const_iterator i = m.find(key); 00023 if(i != m.end()) { 00024 return i->second; 00025 } else { 00026 return val; 00027 } 00028 } 00029 00030 /** 00031 * Emulation for C++11's std::map::at(). 00032 * 00033 * Acts like return map[key], but can be used on const map, and if the key 00034 * doesn't exist will throw an exception instead of adding the key. 00035 * 00036 * A non-official reference can be found here: 00037 * http://en.cppreference.com/w/cpp/container/map/at 00038 * 00039 * @note Didn't use template<class K, class V> since that has a problem when 00040 * deducting the type when the key is a std::string and the type send is a 00041 * charater string, e.g. "foo". Letting the map deduct the K and V types works. 00042 * 00043 * @throw std::out_of_range When the key is not in the map. 00044 * 00045 * @param map The map search into. 00046 * @param key The key to search for. 00047 * 00048 * @returns A copy of the value of key. @note C++11 uses 00049 * a reference, but it's not possible to create 00050 * a reference from an iterator. 00051 */ 00052 template<class M> 00053 inline typename M::mapped_type at( 00054 const M& map 00055 , const typename M::key_type& key) 00056 { 00057 typename M::const_iterator itor = map.find(key); 00058 if(itor == map.end()) { 00059 throw std::out_of_range("Key »" + key + "« doesn't exist."); 00060 } 00061 00062 return itor->second; 00063 } 00064 00065 #endif
| Generated by doxygen 1.7.1 on Fri May 25 2012 01:03:05 for The Battle for Wesnoth | Gna! | Forum | Wiki | CIA | devdocs |