Map

9.1 - Map basic 1


Map is an associative container. It means that it has both key and value, which form a pair. Each value in the map is associated to a unique key, instead to its position like in a vector.

For example, we can have a map called grades with string as the key (the student's name) and float as the value (the student's grade). We could write this to create that map:

std::map<std::string, float> grades;

Since the keys are unique, each student can only have one grade (i.e. Tom can't have both 90 and 80). However, two students might have a same grade (i.e. Temmie and Timmie both have 75).

Your task is to define a map called power_level with string as the key and int as the value.

#include <map> #include <iostream> #include <string> int main() { // Create your map after this line // This code puts new key and value pairs inside map // We will learn this in the next lesson power_level.insert({"Raditz", 1500}); // Here we access the previously inserted pair // We will learn this later too std::cout << "Raditz's power level is " << power_level.at("Raditz") << std::endl; }