Vectors

An array has a fixed size. But often you do not know how many values will come, for example when a user types numbers until they stop. For this, C++ has the vector. A vector is like an array that can grow. In everyday C++ code, a vector is the usual choice for a list of values.

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> scores = {70, 85};
    cout << "Size: " << scores.size() << "\n";

    scores.push_back(92);
    cout << "Size: " << scores.size() << "\n";
    cout << scores[2] << "\n";
    return 0;
}

Output:

Size: 2
Size: 3
92

To use vectors, add #include <vector> at the top. In vector<int>, the type in angle brackets < > is the type of the values. vector<int> holds int values, and vector<string> would hold strings.

size() tells you how many values the vector has right now.

push_back(value) adds a value at the end, and the vector grows by one. The vector started with 2 values and has 3 after the push_back. An array cannot do this.

Square brackets work like in an array. Indexes start at 0, so scores[2] is the third value, 92. And just like with arrays, C++ does not check this index. Vectors also have scores.at(2), which does check it. With a bad index, at stops the program with an error instead of reading the wrong memory. The Exceptions lesson shows this.

Start empty, then add

A vector can start with no values at all. Then you add values as they come:

vector<string> names;
names.push_back("Alice");
names.push_back("Bob");
names.push_back("Emma");
cout << names.size() << " names" << "\n";

Output:

3 names

The range-based for loop

You can visit every value with a normal for loop and an index, from 0 up to size(). But C++ has a shorter loop for this, the range-based for loop:

for (string name : names) {
    cout << "Hello, " << name << "\n";
}

Output:

Hello, Alice
Hello, Bob
Hello, Emma

Read for (string name : names) as "for each name in names". The loop runs once for every value, in order. Each time, name holds the current value. There is no index to count, so you cannot go past the end by mistake. The same loop also works with arrays and strings. Use it when you need every value and do not need its index.

In the exercise, numbers come in until a 0 appears, and you do not know how many there are. Add each one to a vector with push_back.