Map
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