Tuesday, 7 June 2022

Chapter 24 // Exercise 1 - Principles & Practice Using C++

In this exercise I am using Visual Studio 2019 and a modified version of the std_lib_facilities header found here.

Chapter 24 // Exercise 1

The function arguments f for a.apply(f) and apply(f,a) are different. Write a triple() function for each and use each to triple the elements of an array { 1 2 3 4 5 }. Define a single triple() function that can be used for both a.apply(triple) and apply(triple, a). Explain why it could be a bad idea to write every function to be used by apply() that way.


I read this exercise and immediately thought "what the fuck?"

After re-reading section 24.5.2 I realised that apply() basically takes in a pointer to a function and then calls that function on each element in the container. So after some messing around the difference is that a.apply() modifies the elements, apply returns a copy. 

Therefore the single triple function needs to both modify the argument and return a value. This is a bad idea as you don't always want function modifying your containers. Giving users the option is always better.




No comments:

Post a Comment