Skip to content

In-Class Exercise

11. Practice

motto


Task zero!

Before solving the tasks, download the initial codebase; we will extend this code during the exercise.

Initial code

starter.cpp


  1. In the initial code, you will find a vector storing cows, along with the global print function that prints a cow to the standard output.

    • Print all cows stored in the vector using the for_each STL algorithm.
    • Following the example of the print function, write a new function called graze_all that calls the graze method on each cow lighter than 20.
  2. Implement the print and graze_all functions using lambdas.

  3. In the initial code, you will also find the numbers vector that stores integers. Sum the stored numbers using std::accumulate.

  4. Instead of summing, multiply the elements of the numbers vector using std::accumulate.

    • Implement this using a lambda expression.
    • Instead of your own lambda, use std::multiplies.
  5. 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_element so that it finds the cow with the minimal weight. (Hint: std::greater)
  6. Copy the elements of the numbers vector into another vector in reverse order using std::copy.

    • Reserve the required capacity for the destination vector in advance.
    • Use back_inserter for insertion.
  7. 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.

  8. Read a string from the input. Create a vector of strings based on the cow vector using std::transform so that the input string is appended to each cow’s name. The extended cow names should form the elements of the new vector.

  9. 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

solution.cpp



Last update: 2025-11-27
Created: 2025-11-27