Lesson 6 of 10

Vectors

Goal

std::vector and the range-based for loop

01

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.

02

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
  1. maxOf returns the largest element
  2. maxOf works with only negative numbers and returns 0 for an empty vector
  3. evens keeps the even numbers in their order
  4. evens is correct with negative numbers, zero and an empty vector
  5. healAll raises every element in the vector itself and never goes over 100
  6. "Number of scores: 5" and then "Highest: 100" were printed
03

Hints

0/3
Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.

main.cpp
OutputC++17 (GCC 9, Judge0)

Compiling and running your code on the server.

–/6

Compiling and running your code on the server.

6 checks listed under “Your task”.

Track lessons0 of 10 done

C++ is the language behind game engines, browsers and operating systems, because it's fast and gives you full control.

Beginner level, 10 lessons, 2 hours in total.