Map

9.4 - Map basic 4


To check whether an element exists inside a map or not, we can use the find method. The find method takes a key as the argument and returns an iterator. The iterator points to the element if the key exists in the map, but it points to the map's end if the key does not exist. For example we can search for the value with the key "Tom" in grades by doing this:

auto search = grades.find("Tom");

We can check if "Tom" is in grades by comparing search with grades.end():

if (search != grades.end()) {
    // "Tom" exists in grades, we can access the element's value by using the arrow (->) operator
    // The second member of the element is its value
    std::cout << "Tom's grade is " << search->second << std::endl;
}
else {
    // If search equals to the end of grades, then the element with the key "Tom" does not exist
    std::cout << "There is no one called Tom here" << std::endl;
}

Your task is to extend the starting code to take a name and check if a character with that name exists in power_level or not. If it exists, print out:

<name>'s power level is <power>

If it does not, print out:

No one called <name> is found
#include <map> #include <iostream> #include <string> int main() { // Create the map power_level std::map<std::string, int> power_level; // Insert the characters and their power level power_level.insert({"Raditz", 1500}); power_level.insert({"Nappa", 4000}); power_level.insert({"Goku", 9000}); power_level.insert({"Vegeta", 18000}); // Write your code after this line! }