Monday, 8 March 2021

Chapter 19 // Exercise 16 - Principles & Practice Using C++

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

Chapter 19 // Exercise 16

Sometimes, it is desirable that an empty vector be as small as possible. For example, someone might use vector<vector<vector<int>>>  a lot but have most elements vectors empty. Define a vector so that sizeof(vector<int>) == sizeof(int*), that is, so that the vector itself consists only of a pointer to a representation consisting of the elements, the number of elements, and a space pointer.


I was a bit confused at first due to the wording as I thought he meant to have 2 pointers but it could only be the size of 1 pointer. But, after re-reading the question several times realised he meant for the vector representation to hold all three.

I basically reused the vector created in exercises 8 and 9 but took out the allocator and used new and delete instead. This created an entire evening of nightmares. If I didn't understand the difference between copy/move constructors and copy/move assignment before; I sure as hell do now.

I ended up using the crt debug library to track down the exact new that was causing me problems and I realised that my move assignment was not deleting properly. I've left the crt stuff in the code; it's an extremely useful tool.


I also became a pedantic about my vectors. I wanted the original vector to be a fully functional vector in it's own right and the SmallVector to just rely on all of OriginalVector's functions. I think that's what caused me the headache as I tried to separate in my head what was an allocation and what wasn't. 

Ultimately, a frustrating yet extremely rewarding exercise.

When I ran the code a vector<vector<vector<int>>> reported a size of 16 and my SmallVector<SmallVector<SmallVector<int>>> was 4.

And with that, Chapter 19 is finally over. I started it on the 22nd of December and it was beginning to feel like the chapter that would never end. That said I've been doing about 3000 other projects in-between. I really need to focus on this book more.

No comments:

Post a Comment