Consider I have this:
std::map<int, int> intMap;
intMap[11] = 21;
intMap[12] = 22;
intMap[13] = 23;
intMap[14] = 24;
int val = 0;
When I want to find the value of map[11], if exists, and put it into val
I'm using:
std::map<int, int>::iterator it = intMap.find(11);
if(it != intMap.end())
val = it->second;
Is there a way of doing this without using an iterator? I mean, a shorter way.
int val = intMap[11]
isn't an option for me since it adds 11 as a key to intMap if it wasn't there yet, something I'm not interested in. see here.
In c++11 map
has a new method called at(Key)
which will return a reference to the mapped value or throw an exception if the Key
is not present at the map.
In c++ you will need to have an intermediary iterator.
André already mentions the new at()
function. In other circumstances, the following might be useful:
template <typename Map, typename K, typename T>
T get(Map &map, const K &key, T def) {
typename Map::const_iterator it = map.find(key);
return (it == map.end() ? def : it->second);
}
Use it like:
int val = get(intMap, 11, 0);
You can also have a const
version, with the advantage of returning a reference (the non-const version returns a value, because returning a reference to a default is rather limiting):
template <typename Map, typename K, typename T>
const T& get(const Map &map, const K &key, const T &def) {
typename Map::const_iterator it = map.find(key);
return (it == map.end() ? def : it->second);
}
Just for fun, this code is concise but it might lose for clarity. It does what you say in a comment below: nothing in the case where 11
is not in the map:
BOOST_FOREACH(const std::pair<int,int> &newval, intMap.equal_range(11)) {
val = newval.second;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With