Wednesday, 7 April 2021

Chapter 20 // 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 20 // Exercise 1

If you haven't already, do all the Try this exercises in the chapter.


pg714
The one on p714 is subjective but personally I would just change 
vector<double>* jill_data 
to 
vector<double>& jill_data
incidentally, this is exactly what he does in the next section.

pg715
Here, double* high is a local variable and it is returning a pointer to a local variable. This will cause a dangling pointer as you can't return pointers to locals.  I am so dumb. After spending an evening battling with heap corruption because I thought this function was leaking memory I realised it's returning a pointer to something we already have on the stack and does not need to be newed up. GAH. I have a feeling he wanted us to discover that...

Also, the function only works with doubles and relies on values being contiguous in memory. Therefore containers like array and vector must be used. A list wouldn't work as the pointers can be anywhere in memory.

A little annoying as I couldn't use any subscripting.

pg724
The only thing I can think of is that high() is a returning a copy of the iterators into pointers? But it's creating a value on the stack due to it being a copy....I honestly don't know for this one. It ran fine when I recreated it.

push_front on a vector would be very expensive as it then needs to modify the position of everything else in the vector; what if you have a vector of 1000+ items? That's a lot of wasted cycles. A vector does have insert() which allows you to put an element anywhere in the vector and it will re-organise everything after the insertion, so you could use it to "push something to the front" if you wanted.

For the implementation, I'm lazy and rather than go get the vector I created in previous exercises I simply added push_front to the actual std::vector via Bjarne's std_lib_facilities header file and used insert().

This felt too easy....

This one is a bit confusing as I'm not sure if meant to use 1 function to compare all 4 or a separate one for each. Also, should we have passed it in as a string? Eventually I decided on 2 separate functions due to char* not being as flexible as the others.

This one was so annoying.

1 comment: