8.1 — vector: a list that grows
Read one box at a time. No rush.
Many values in one box#
What if you have 100 test scores? 100 variables would be silly. Use a vector: one name, many values.
C++▶ Run
#include <iostream>#include <vector> int main(){ std::vector<int> scores { 90, 72, 85 }; std::cout << scores[0] << '\n'; // 90 std::cout << scores[2] << '\n'; // 85 return 0;}std::vector<int>= a list ofints.{ 90, 72, 85 }= the starting values.scores[0]= the first item.
Counting starts at 0#
Each item has a position number called an index. The first index is 0, not 1.
| Index | 0 | 1 | 2 |
|---|---|---|---|
| Value | 90 | 72 | 85 |
Key idea
A list with 3 items has indexes 0, 1, 2. The last index is always size - 1.
Changing and growing#
C++
std::vector<std::string> names { "Ana", "Ben" }; names[1] = "Bob"; // change an itemnames.push_back("Cleo"); // add to the end std::cout << names.size(); // 3Going out of bounds#
C++ — wrong ✗
std::vector<int> v { 1, 2, 3 };std::cout << v[3]; // there is no index 3! undefined behaviorWatch out
v[i] does not check if i is valid. Use v.at(i) while learning — it stops the program with a clear error if i is out of range.
Tip: press ← / → to move between lessons, / to search.