Data Bundles

In C++, you borrow bundles from the Standard Library.


1. The growing line of boxes: vector

The most common dynamic array is std::vector.

#include <vector>

std::vector<std::string> shoppingList = {"apple", "banana"};

// Add (push_back)
shoppingList.push_back("grape");

// Update (index)
shoppingList[0] = "strawberry";

// Remove (deleting in one line is a bit more complex, but clearing is easy)
// shoppingList.pop_back(); // remove the last item

Translation:

Prepare a vector bundle called shoppingList that holds strings
Push "grape" to the back
Change box 0 to "strawberry"

2. The labeled dictionary: map

Look up values by name tag. Use std::map.

#include <map>

std::map<std::string, int> myStats;

// Add & update
myStats["attack"] = 100;
myStats["defense"] = 50;

// Remove
myStats.erase("defense");

std::cout << "Current attack: " << myStats["attack"] << std::endl;

Translation:

Prepare a number bundle with string labels
Write 100 under the "attack" label
Erase the "defense" label

In C++, it is important to include the right toolbox header (#include) up front.