Codiqo

Learn C++ · lesson 26 of 61 · about 7 minutes

Creating Vectors

Pack the hero's bag: store a list of items in a std::vector, and read them by index.

What you'll learn

  • Create a vector with values
  • Read and change items by index
  • Use size(), front() and back()

The hero's bag

The hero has been carrying a torch all along, and now a rope and some bread too. Three separate variables would work until the hero picks up a fourth thing. A std::vector<std::string> called bag holds all of them in order, however many there are, and the adventure can ask it how many items it has and which one is in each slot.

A list that manages itself

std::vector<int> scores = {70, 85, 90}; is a list of ints that can grow and shrink. It needs #include <vector>.

  • scores[0] is the first item; indexes start at 0
  • scores.size() is how many items there are
  • front() and back() are the first and last items
  • scores.at(i) is like scores[i] but throws an error for a bad index instead of reading random memory

Reading and changing items

#include <iostream>
#include <string>
#include <vector>

int main() {
    std::vector<int> scores = {70, 85, 90, 62};
    std::cout << scores[0] << " " << scores.back() << " (" << scores.size() << " scores)\n";
    scores[1] = 88;
    std::cout << "Second is now " << scores.at(1) << "\n";

    std::vector<std::string> islands = {"Console Cove", "Branching Bayou"};
    std::cout << islands.front() << "\n";
}

Output

70 62 (4 scores)
Second is now 88
Console Cove

Tip

The type in angle brackets says what the vector holds: std::vector<double>, std::vector<std::string>, and so on. Every item has that type.

Tip

size() gives a std::size_t, a count that can't be negative. Keeping it in an int, like int items = bag.size();, lets you compare it with a typed int without g++ warning about mixing the two.

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.