Kodewick
Start learning →
Mini challenge←→0 / 60

Game backpack

#046Mini challengeClassesMaps7 min

A little game's Bag keeps how many of each thing it holds in items. Write use(item): if there's none of it, return false; otherwise take one away and return true, and when it gets to 0, erase it from the bag.

Examples
bag_after({"potion", "potion", "key"}, {"potion"})→{'key': 1, 'potion': 1}
bag_after({"key"}, {"key"})→{}
The functionmap<string, int> bag_after(const vector<string> &picks, const vector<string> &uses)
main.cpp
#include <map>
#include <string>
#include <vector>
using namespace std;

class Bag {
public:
    map<string, int> items;

    void pick(const string &item) {
        items[item]++;
    }

    bool use(const string &item) {
        // your code here: use up one item
        return false;
    }
};

map<string, int> bag_after(const vector<string> &picks, const vector<string> &uses) {
    Bag b;
    for (const string &p : picks) {
        b.pick(p);
    }
    for (const string &u : uses) {
        b.use(u);
    }
    return b.items;
}
Ctrl + Enter runs too
Result

Run tries the examples. When they look right, Submit.