A list becomes useful when one operation can visit all its values. A range-based for loop walks from the first element to the last without requiring you to manage an index.
#include <vector>
#include <iostream>
int main() {
std::vector<int> minutes{10, 15, 5};
int total = 0;
for (int duration : minutes) {
total += duration;
}
std::cout << total << '\n';
}
Read for (int duration : minutes) as “for each integer value in minutes.” On each visit, duration receives a copy of that element. The total starts at zero and grows to thirty. Changing duration would change the copy, not the vector. This by-value form is a good starting point when you only need to read small values.
Sometimes you need a position as well as its value. Then use the counted loop you already know, with std::size_t from <cstddef> as the index type:
#include <cstddef>
#include <vector>
#include <iostream>
int main() {
std::vector<int> rooms{2, 4};
for (std::size_t i = 0; i < rooms.size(); ++i) {
std::cout << i << ": " << rooms[i] << '\n';
}
}
std::size_t is unsigned: it represents nonnegative sizes and indices. The strict < stops before the invalid index rooms.size(). Do not use <=. These forward loops also work for empty vectors: they simply make no visits. Avoid subtracting one from a possibly zero unsigned size; there is no need for that in either loop above.
Both loop headers are supplied in the starter. In the first body, units is already the current value, so add it directly to the running total. In the second body, i is a position: read stock[i] to decide whether to increase the bin count. Keep the counters outside their loops so they retain earlier updates.
units value to total inside the range-based loop. Expect Units: 22.largeBins only when stock[i] > 5. Expect Large bins: 2.Edit main.cpp, then select Run to inspect the Console. Select Submit to check your completed tasks.