Lesson 6 of 10
Vectors
- 13 min
- 6 checks
- 3 hints
- Go to task
Goal
std::vector and the range-based for loop
Explanation
A vector is a list that can change size, like std::vector<int> scores = {72, 95, 64};. It comes from <vector>, and the type between <> is the type of its elements. push_back(88) adds an element at the end, size() returns how many elements it has, empty() tells you whether it's empty, and scores[0] is the first element, because counting starts at zero.
A range-based for loop goes through every element without a counter, as in for (int s : scores), where s is a copy of the element. If you want to modify the elements themselves, make it a reference: for (int& s : scores) { s += 5; }. And when you pass a vector to a function that only reads it, pass it as const std::vector<int>&, or the whole list gets copied on every call.
Be careful: [] doesn't check that the position is inside the list, so scores[10] on a list of three elements reads memory that doesn't belong to it, giving you a garbage value or crashing the program without a clear message, while scores.at(10) checks and throws an exception. An empty list has no [0] at all, so ask empty() before you read from it.
Your task
Complete int maxOf(const std::vector<int>& v) so it returns the largest element, or 0 if the vector is empty. It has to work correctly even when every element is negative. Complete std::vector<int> evens(const std::vector<int>& v) so it returns a new vector holding only the even numbers, in their original order, and void healAll(std::vector<int>& hps, int amount) so it raises each player's health in the vector itself by amount, without going over 100. Then, in main, add the number 100 to scores with push_back and print two lines: Number of scores: 5 from size(), then Highest: 100 from maxOf.
Checks
6 checks- maxOf returns the largest element
- maxOf works with only negative numbers and returns 0 for an empty vector
- evens keeps the even numbers in their order
- evens is correct with negative numbers, zero and an empty vector
- healAll raises every element in the vector itself and never goes over 100
- "Number of scores: 5" and then "Highest: 100" were printed