C++ Maps

Maps can be used in C++ to store data in key, value pairs which can then be indexed by the key. Initialize a map as follows:

map<int,bool> myMap;

Here we have initialized a map to contain pairs of data where the key is an int and the value is a bool. The container is defined with no size, similar to a vector and we can add data as follows:

int firstkey = 5;
int secondkey = 1;

myMap[firstkey] = true;
myMap[secondkey] = false;

Any datatype can be used for either the key or the value, and the order of the data does not matter, so here we have added the key value 5 before the key value 1.

Retrieving Values

We can get data out of a map by providing a key value in the same manner as if it was a vector. In this example we have our key values stored in a vector, Keys and we can retrieve the corresponding value for each key, regardless of the order of insertion or retrieval:

for (int w = 0; w < int(Keys.size()); ++w){
  cout << "The value for key: " << Keys[w] << " is " << myMap[Keys[w]] << endl;
}

This is a very brief overview of how to get started with maps, for more detail check the docs.