Maps and Functions
A map goes into a function the way a vector does. Passed by value, the function gets a copy of the whole map, with all its elements. So pass it by const reference when the function only reads it, and by reference when the function changes it:
#include <iostream>
#include <map>
#include <string>
// Prints every item with its count
void printInventory(const std::map<std::string, int>& inventory) {
for (const auto& [item, count] : inventory) {
std::cout << item << ": " << count << std::endl;
}
}
// Adds an amount of an item to the inventory
void addItem(std::map<std::string, int>& inventory, const std::string& item, int amount) {
inventory[item] += amount;
}
int main() {
std::map<std::string, int> inventory = {
{"potion", 1}
};
addItem(inventory, "potion", 2);
addItem(inventory, "bread", 1);
printInventory(inventory);
return 0;
}This prints:
bread: 1
potion: 3There's one trap. In a function that gets a const map, square brackets don't compile, not even for reading:
int priceOf(const std::map<std::string, int>& prices, const std::string& item) {
return prices[item];
}main.cpp:6:18: error: no viable overloaded operator[] for type 'const std::map<std::string, int>' (aka 'const std::map<basic_string<char>, int>')Remember what square brackets do with a missing key: they add it. That would change the map. The square brackets are a method of the map, called operator[] in the message, and it isn't a const method. So you can't call it through a const reference, just as a function that got a const Hero& couldn't call takeDamage in the lesson on classes. The notes below the error say it too: … but method is not marked const. Read the values of a const map with at(), which never adds anything. count() works on it too:
int priceOf(const std::map<std::string, int>& prices, const std::string& item) {
if (prices.count(item) == 0) {
return 0;
}
return prices.at(item);
}Whoever reads the first line of a function then knows from the const that the function doesn't change the map, not even by adding a key by mistake.
Instructions
- 1
The program doesn't compile:
cartTotalgets the prices as a const map and reads them with square brackets. Keep the parameterconst, and read the prices withat()instead. The program then prints the price list andTotal: 33. - 2
Aria has become famous, and the shopkeeper raises every price by 5. Below
cartTotal, write a functionraisePriceswith two parameters: the mapprices, which the function changes, and the numberamount. The function addsamountto every price in the map. At the end ofmain(beforereturn 0;), callraisePrices(prices, 5), and then print the price list and the total once more, with the same two lines as above. The program prints:bread: 3 helmet: 40 potion: 15 Total: 33 bread: 8 helmet: 45 potion: 20 Total: 48Keep the lines of the map as they are: the exercise will also try other prices.