How can I use an array as map value?

You can’t copy arrays by value like that. Here are several solutions, but I recommend #4 for your needs: Use an std::vector instead of an array. Use a map of pointers to arrays of 3 elements: int red[3] = {1,0,0}; int green[3] = {0,1,0}; int blue[3] = {0,0,1}; std::map<int,int(*)[3]> colours; colours.insert(std::pair<int,int(*)[3]>(GLUT_LEFT_BUTTON,&red)); colours.insert(std::pair<int,int(*)[3]>(GLUT_MIDDLE_BUTTON,&blue)); colours.insert(std::pair<int,int(*)[3]>(GLUT_RIGHT_BUTTON,&green)); // Watch … Read more

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

How can I create my own comparator for a map?

std::map takes up to four template type arguments, the third one being a comparator. E.g.: struct cmpByStringLength { bool operator()(const std::string& a, const std::string& b) const { return a.length() < b.length(); } }; // … std::map<std::string, std::string, cmpByStringLength> myMap; Alternatively you could also pass a comparator to maps constructor. Note however that when comparing by … Read more

Using char* as a key in std::map

You need to give a comparison functor to the map otherwise it’s comparing the pointer, not the null-terminated string it points to. In general, this is the case anytime you want your map key to be a pointer. For example: struct cmp_str { bool operator()(char const *a, char const *b) const { return std::strcmp(a, b) … Read more