std::map default value

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 … Read more

What is the preferred/idiomatic way to insert into a map?

As of C++11, you have two major additional options. First, you can use insert() with list initialization syntax: function.insert({0, 42}); This is functionally equivalent to function.insert(std::map<int, int>::value_type(0, 42)); but much more concise and readable. As other answers have noted, this has several advantages over the other forms: The operator[] approach requires the mapped type to … Read more

In STL maps, is it better to use map::insert than []?

When you write map[key] = value; there’s no way to tell if you replaced the value for key, or if you created a new key with value. map::insert() will only create: using std::cout; using std::endl; typedef std::map<int, std::string> MyMap; MyMap map; // … std::pair<MyMap::iterator, bool> res = map.insert(MyMap::value_type(key,value)); if ( ! res.second ) { cout … Read more

Initializing a static std::map in C++

Using C++11: #include <map> using namespace std; map<int, char> m = {{1, ‘a’}, {3, ‘b’}, {5, ‘c’}, {7, ‘d’}}; Using Boost.Assign: #include <map> #include “boost/assign.hpp” using namespace std; using namespace boost::assign; map<int, char> m = map_list_of (1, ‘a’) (3, ‘b’) (5, ‘c’) (7, ‘d’);