Sunday, 9 April 2023

Chapter 26 // Exercise 2 - Principles & Practice Using C++

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

Chapter 26 // Exercise 2

Modify the testing of binary_search to deal with arbitrary element types. Then test it with string sequences and floating-point sequences.

I decided on the rule that you can't have tests that included wildly different types like string and floats. Binary search requires that your elements are sorted, if one element is "cheese" and the other "3.4", how do you sort that?

I then tried to do it so the the same file could read in string tests, followed by int tests or floats. But doing compile time checks on what type the stringstream was reading into became a bit long winded, so I just created 3 seperate text files and fed them into the code.

Then it was just a matter of slightly modifying operator>> overload so it could handle any type. I did this by just reading everything into a string. If it hit '}', I put that character back into the stream then converted the string into the necessary type via istringstream.

No comments:

Post a Comment