Day 1's report used one variable per session: first, second, third. That works for three sessions, but a planner does not know in advance how many tasks someone will enter. You cannot declare fourth while the program runs. You need one variable that holds any number of values, can grow, and can be visited in a loop. In C++ that is std::vector.
std::vector<int> owns a sequence of integers. Include <vector>. The type in angle brackets chooses the element type, so std::vector<int> holds int values and std::vector<std::string> holds strings. An initializer list in braces supplies the starting elements, and push_back appends one more element at the end. size() reports how many elements exist right now.
Predict and run
#include <iostream>
#include <vector>
int main() {
std::vector<int> minutes{25, 10};
minutes.push_back(15);
int total = 0;
for (int value : minutes) {
total += value;
}
std::cout << minutes.size() << " " << total << "\n";
return 0;
}Check your prediction
3 50The range-based for loop, for (int value : minutes), visits each element in order and gives it to you as value. You did not calculate a single index. Remove the starting values so the vector begins empty, keep the push_back, and predict the new size and total.
The vector owns its elements
The vector stores its elements in memory it manages itself. When you push_back and there is no room left, it finds a larger block, moves the elements there, and releases the old block. When the vector variable reaches the end of its scope, it releases its memory automatically. You never write new or delete for it. This pattern, where an object acquires a resource and its destructor releases it at the end of its scope, is called RAII, and it is why std::string and std::vector are safe defaults.
Ownership also explains copying. Assigning one vector to another copies every element, so the two vectors are independent:
#include <iostream>
#include <vector>
int main() {
std::vector<int> plan{25, 10};
std::vector<int> backup = plan;
plan.push_back(40);
plan[0] = 30;
std::cout << plan.size() << " " << plan[0] << "\n";
std::cout << backup.size() << " " << backup[0] << "\n";
return 0;
}3 30
2 25backup received its own copy of the two elements. Growing and changing plan afterward did nothing to it. This is value semantics again, the same rule you saw with int on Day 3, now applied to a whole collection.
Indexes start at zero, and must stay inside
plan[0] names the first element and plan[plan.size() - 1] names the last. Valid indexes run from 0 up to, but not including, size(). Using [] with an index outside that range is undefined behavior: C++ does not check it, there is no error message, and the program may print garbage, crash, or appear to work and then fail later.
std::vector<int> plan{25, 10};
std::cout << plan[2]; // undefined behavior: valid indexes are 0 and 1
std::vector<int> empty;
std::cout << empty[0]; // undefined behavior: there is no element 0The safest habit is to avoid indexes when you do not need them: the range-based loop never goes out of bounds. When you do need an index, check it first: if (index < plan.size()). For an empty vector, size() is 0, so no index passes, which is exactly right. The standard library also has plan.at(index), which checks for you, but it reports failure with an exception, and this course's browser compiler does not support exceptions, so we check explicitly instead.
size() returns an unsigned type, std::size_t, which can never be negative. Comparing it with a signed int triggers a warning with -Wall -Wextra (an error in a local build with -Werror; the browser editor builds without those flags), so an index loop uses std::size_t i = 0; i < plan.size(); ++i.
Practice
Your turn
Start with a vector holding 25, 10 and 40, then append 15. Print exactly:
Sessions: 4Total: 90First: 25Last: 15
Calculate the total with a range-based loop. Read the first and last elements by index, but only inside a check that the vector is not empty.
#include <iostream>
#include <vector>
int main() {
// Write your solution here.
return 0;
}Hint 1: the idea
The last valid index is one less than the size. On an empty vector there is no first or last element at all, so guard both reads with !sessions.empty().
Hint 2: a first step
Write std::vector<int> sessions{25, 10, 40}; and sessions.push_back(15);, print sessions.size(), and run before adding the total.
Show one solution
#include <iostream>
#include <vector>
int main() {
std::vector<int> sessions{25, 10, 40};
sessions.push_back(15);
int total = 0;
for (int minutes : sessions) {
total += minutes;
}
std::cout << "Sessions: " << sessions.size() << "\n";
std::cout << "Total: " << total << "\n";
if (!sessions.empty()) {
std::cout << "First: " << sessions[0] << "\n";
std::cout << "Last: " << sessions[sessions.size() - 1] << "\n";
}
return 0;
}Sessions: 4
Total: 90
First: 25
Last: 15The range-based loop cannot go out of bounds, so the total needs no guard. The two indexed reads can, so they sit inside !sessions.empty(). That guard matters most for the last element: on an empty vector, size() - 1 is not -1 but a huge unsigned number, and indexing with it would be undefined behavior. Next you will apply the same size and index rules to the characters of a std::string.
Completion is saved in this browser only. It does not measure mastery.