Opening the reading…
Opening the reading…
PROGRAMMING FUNDAMENTALS › C++ FUNDAMENTALS
A vector stores elements in order and lets you access them by index, like an array. Unlike a fixed array length, a vector's current number of elements can change while your program runs. To use vector, include its standard library header, then write the element type inside angle brackets.
#include <vector>
std::vector<int> values = {4, 2, 7};
std::cout << values.size(); // 3Here, values has the type vector<int>, so every element is an int. The braces initialize its three current elements in order: 4 at index 0, 2 at index 1, and 7 at index 2. size() returns the number of current elements, so values.size() is 3. It does not return the largest valid index.
What does values.size() return immediately after vector<int> values = {4, 2, 7};?
Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
You can read or replace an element at an index that already exists. In the running vector, values[1] reads 2 because index 1 holds the second element. Assigning 6 to that same index replaces 2, giving [4, 6, 7]. The vector still has three elements, so its size has not changed.
std::vector<int> values = {4, 2, 7};
int middle = values[1]; // middle is 2
values[1] = 6; // values is now [4, 6, 7]
std::cout << values.size(); // 3When values.size() is 3, the valid indices are 0, 1, and 2. Index 3 is the next position outside the vector, not an empty fourth element waiting to be filled. Writing values[3] = 1 does not append anything. Through operator[], that out-of-range access causes undefined behavior, so the program cannot safely rely on what happens.
Replace the invalid assignment with the operation that safely creates the fourth element.
values[3] = 1;Checkpoints are not graded. They are here so you catch yourself before the quiz does — stuck, ask the tutor on the right.
Use push_back when you want to create a new last element. Starting with [4, 6, 7], values.push_back(1) changes the vector to [4, 6, 7, 1]. Its size becomes 4, and index 3 now refers to the new 1. The operation changes both the contents and the set of valid indices.
std::vector<int> values = {4, 2, 7};
values[1] = 6; // [4, 6, 7], size 3
values.push_back(1); // [4, 6, 7, 1], size 4
std::cout << values.size();
values.pop_back(); // [4, 6, 7], size 3
std::cout << values.size();Use pop_back to remove the current last element. It removes 1 from [4, 6, 7, 1], returning the vector to [4, 6, 7] and reducing the size from 4 to 3. pop_back does not return the removed value. After removal, index 3 is outside the vector again. Calling pop_back on an empty vector causes undefined behavior.