In-Class Exercise
11. Practice¶

Task zero!
Before solving the tasks, download the initial codebase; we will extend this code during the exercise.
Initial code
-
In the initial code, you will find a vector storing cows, along with the global
printfunction that prints a cow to the standard output.- Print all cows stored in the vector using the
for_eachSTL algorithm. - Following the example of the
printfunction, write a new function calledgraze_allthat calls thegrazemethod on each cow lighter than 20.
- Print all cows stored in the vector using the
-
Implement the
printandgraze_allfunctions using lambdas. -
In the initial code, you will also find the
numbersvector that stores integers. Sum the stored numbers usingstd::accumulate. -
Instead of summing, multiply the elements of the
numbersvector usingstd::accumulate.- Implement this using a lambda expression.
- Instead of your own lambda, use
std::multiplies.
-
Using
max_element, find the heaviest cow in the cow array.- Do this with your own lambda.
- Instead of your own lambda, use
std::less. This may require extending the Cow struct. - Parameterize
max_elementso that it finds the cow with the minimal weight. (Hint:std::greater)
-
Copy the elements of the
numbersvector into another vector in reverse order usingstd::copy.- Reserve the required capacity for the destination vector in advance.
- Use
back_inserterfor insertion.
-
Copy all cows heavier than 20 into a new vector using
copy_if. Count how many cows were not copied. Print both the count and the names of these cows to the standard output. -
Read a string from the input. Create a vector of strings based on the cow vector using
std::transformso that the input string is appended to each cow’s name. The extended cow names should form the elements of the new vector. -
Sort the vector created in task 8 lexicographically using
std::sort.
Got stuck or had trouble keeping up during the session? Or do you simply want to review the material? A possible solution to the exercises is available.
In-class exercise solution
Created: 2025-11-27