Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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: 3

There'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. 1

    The program doesn't compile: cartTotal gets the prices as a const map and reads them with square brackets. Keep the parameter const, and read the prices with at() instead. The program then prints the price list and Total: 33.

  2. 2

    Aria has become famous, and the shopkeeper raises every price by 5. Below cartTotal, write a function raisePrices with two parameters: the map prices, which the function changes, and the number amount. The function adds amount to every price in the map. At the end of main (before return 0;), call raisePrices(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: 48

    Keep the lines of the map as they are: the exercise will also try other prices.

Back

8/12

  1. 1. What Is a Map?
  2. 2. Adding and Changing Values
  3. 3. Looping over a Map
  4. 4. Missing Keys
  5. 5. Counting with a Map
  6. 6. Quiz: Counting Loot
  7. 7. Removing Elements
  8. 8. Maps and Functions
  9. 9. Quiz: Restocking
  10. 10. Structs as Values
  11. 11. Unordered Maps
  12. 12. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.