Saturday 25 September 2021

Chapter 21 // Drill 1 - 1, 2, 3, 4, 5, 6, 7 - 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 21 // Drill 1.1

Define struct Item { string name; int iid; double value; /* ... */};, make a vector<Item>, vi, and fill it with ten items from a file.

Chapter 21 // Drill 1.2

Sort vi by name.

Chapter 21 // Drill 1.3

Sort vi by iid.

Chapter 21 // Drill 1.4

Sort vi by value; print it in order of decreasing value (i.e., largest value first).

Chapter 21 // Drill 1.5

Insert Item{"horse shoe", 99, 12.34} and Item{"Canon S400", 9988, 499.95}.

Chapter 21 // Drill 1.6

Remove (erase) two Items identified by name from vi.

Chapter 21 // Drill 1.7

Remove (erase) two Items identified by iid from vi.

Github: 

New things all around in this exercise. I used the code from page 791 to start with and added operator>> to Item so I didn't have to modify it. This worked perfectly and vector happily constructed 10 Items using the data from the text file thanks to the operator overload. The input code is a bit hardcoded however it allows Items to have spaces in the name value as it uses getline().

For the second drill I tried my hand at creating a function object to sort the name. They are very easy to use.

For sorting by value I allowed a bool to passed to the function object which allows it to switch between increasing/decreasing order.

Whilst doing Drill 6 I also found out that std::remove_if will erase a member of a custom object when passed a predicate to find that member; very cool.

No comments:

Post a Comment