Codiqo

Learn C++ · lesson 37 of 61 · about 10 minutes

Project: Inventory

Fill the treasure vault: keep each treasure in a vector of unique_ptrs, throw out the worthless ones, and look for the crown.

What you'll learn

  • Store unique_ptrs in a vector
  • Find and remove items
  • Let destruction happen automatically

The treasure vault

At the bottom of the dungeon is the vault. The hero types each treasure as a name and a value, like crown 50, until done. Each one becomes a Treasure owned by a std::unique_ptr, kept in std::vector<std::unique_ptr<Treasure>> vault. Rags and cursed things are worth 0 or less, so they're thrown out with vault.erase(std::remove_if(...), vault.end()), and each is destroyed the moment it's erased. Then the adventure adds up what's left and looks for the crown with std::find_if.

The design

Each Item is created with make_unique and stored in a std::vector<std::unique_ptr<Item>>. The vector owns them all:

  • adding pushes a new unique_ptr
  • removing erases it, and the item is destroyed automatically
  • when the inventory goes away, every item is cleaned up

The inventory

#include <algorithm>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

struct Item {
    std::string name;
    int value;
};

int main() {
    std::vector<std::unique_ptr<Item>> bag;
    bag.push_back(std::make_unique<Item>(Item{"torch", 15}));
    bag.push_back(std::make_unique<Item>(Item{"map", 40}));
    bag.push_back(std::make_unique<Item>(Item{"apple", 2}));

    auto it = std::find_if(bag.begin(), bag.end(), [](const auto& i) { return i->name == "map"; });
    if (it != bag.end()) std::cout << "Found " << (*it)->name << " worth " << (*it)->value << "\n";

    bag.erase(std::remove_if(bag.begin(), bag.end(), [](const auto& i) { return i->value < 5; }), bag.end());

    int total = 0;
    for (const auto& item : bag) total += item->value;
    std::cout << bag.size() << " items worth " << total << "\n";
}

Output

Found map worth 40
2 items worth 55

Tip

erase(remove_if(...), end()) is the standard way to delete every item matching a condition from a vector.

Tip

Loop over a vector of unique_ptrs with const auto&. Plain auto would try to copy each unique_ptr, and that doesn't compile.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.