Is there a way to specify the default value std::map 's operator[] returns when an key does not exist?
Thanks!
Is there a way to specify the default value std::map 's operator[] returns when an key does not exist?
Thanks!
There is no way to specify the default value - it is always valeu constructed by the default (zero parameter constructor).
In fact operator[] probably does more than you expect as if a value does not exist for the given key in the map it will insert a new one with the value from the default constructor.
Maybe you can give a custom allocator who allocate with a default value you want.
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key,T> > > class map;
The C++ standard (23.3.1.2) specifies that the newly inserted value is default constructed, so map
itself doesn't provide a way of doing it. Your choices are:
operator[]
to insert that default.No, there isn't. The simplest solution is to write your own free template function to do this. Something like:
#include <string>
#include <map>
using namespace std;
template <typename K, typename V>
V GetWithDef(const std::map <K,V> & m, const K & key, const V & defval ) {
typename std::map<K,V>::const_iterator it = m.find( key );
if ( it == m.end() ) {
return defval;
}
else {
return it->second;
}
}
int main() {
map <string,int> x;
...
int i = GetWithDef( x, string("foo"), 42 );
}