Removing Elements
When Aria drinks her last potion, the potion should disappear from her inventory. A value of 0 isn't enough: the key stays in the map, and a loop prints potion: 0. To remove an element, call the method erase() with its key:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> inventory = {
{"bread", 2},
{"potion", 1}
};
inventory["potion"]--;
std::cout << "Different items: " << inventory.size() << std::endl;
inventory.erase("potion");
std::cout << "Different items: " << inventory.size() << std::endl;
return 0;
}This prints:
Different items: 2
Different items: 1After inventory["potion"]--;, the potion is still there, with the value 0. Only erase("potion") removes the key together with its value. When the key isn't in the map, erase() does nothing, and the program goes on without an error.
Watch out: once a key is gone, square brackets add it back. inventory["potion"] after the erase() gives 0, and the potion is in the map again, with the value 0.
Whether a map has no elements at all, you find out with empty(), which you know from strings. It gives true when the map is empty:
inventory.erase("bread");
if (inventory.empty()) {
std::cout << "The bag is empty" << std::endl;
}Added at the end of the program above, these lines remove the bread too and print The bag is empty.
Instructions
- 1
After the fight, the program prints
bread: 0andpotion: 0, but what Aria used up should disappear from her inventory. In the first loop, right after lowering the count, remove the item witherase()when its count is 0. The program then prints onlywater: 1. Keep the lines of the map and the line withusedas they are: the exercise will also try other fights. - 2
At the end of the program, print
The bag is emptywhen nothing is left in the inventory, and otherwise the number of different items in it:Different items: 1.