Wednesday, 19 July 2023

Chapter 26 // Exercise 12, 13, 14 - 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 12

Write a program that generates random floating-point numbers and sort them using std::sort. Measure the time used to sort 500,000 doubles and 5,000,000 doubles.

This was a fun little task and taught me how to create a function to create random doubles.


Chapter 26 // Exercise 13

Repeat the experiment in the previous exercise, but with random strings of lengths in the [0:100) range.

I'd already created a randString function many exercises earlier and added it to std_lib_facilities. So you can find that in the link at the top of the post. Creating the vectors took almost as much time as sorting them. Especially the second one. I watched the memory used jump to 1.1GB and it took a good 120 seconds to create the strings.


Chapter 26 // Exercise 14

Repeat the previous exercise, except using a map rather than a vector so that we don't need to sort.

I had to add an arbitrary value for each map entry. As its added sorted though, I timed creating the map. I found it weird though that sometimes, my strings would all start with a number; especially with 500000 strings created.

I also found it interesting that the map.size() was reporting 487,784 elements added when 500,000 were inserted. This meant that randString() created almost 13,000 duplicate strings; which is wild.

I could've used a container like Set, which only stores keys but the exercise said map. I also could've stored the strings as value and then sorted by value but then that defeats the purpose of a map.


This was much faster than the vector though, as it took 120 seconds to create the vector then the extra 80 to sort. However, I am missing a chunk of data due to keys being the same.

...

And with that, I'm done with Chapter 26! I honestly can't believe there's only 1 chapter left. It feels like a chapter of my life is coming to an end and I don't think I'm ready.

No comments:

Post a Comment