std::map default value for build-in type

This is defined in the standard, yes. map is performing “default initialization” in this case. As you say, for class types, that calls a no-arguments constructor. For built-in types, in the ’98 standard, see section 8.5, “Initializers”: To default-initialize an object of type T means: if T is a non-POD … if T is an … Read more

Does std::map::iterator return a copy of value or a value itself?

I want to add a follow up answer to this question for people using C++11 iterators… The following code: std::map<std::string, std::string> m({{“a”,”b”},{“c”,”d”}}); for (auto i : m) { std::cout << i.first << “: ” << i.second << std::endl; } does copy the key and value since “auto” is a value by default, not a const … Read more

Why use std::less as the default functor to compare keys in std::map and std::set?

I decided to ask Alexander Stepanov (designer of the STL) about this. I’m allowed to quote him as follows: Originally, I proposed 3-way comparisons. The standard committee asked me to change to standard comparison operators. I did what I was told. I have been advocating adding 3-way components to the standard for over 20 years. … Read more

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 thread-safety

The C++11 standard guarantees that const method access to containers is safe from different threads (ie, both use const methods). In addition, [container.requirements.dataraces] states implementations are required to avoid data races when the contents of the contained object in different elements in the same sequence, excepting vector<bool> In other words, except for vector<bool> modifying distinct … Read more

How can I traverse/iterate an STL map?

Yes, you can traverse a Standard Library map. This is the basic method used to traverse a map, and serves as guidance to traverse any Standard Library collection: C++03/C++11: #include <cstdlib> #include <map> #include <string> using namespace std; int main() { typedef map<int,string> MyMap; MyMap my_map; // … magic for( MyMap::const_iterator it = my_map.begin(); it … Read more