Pages

Wednesday, 17 March 2021

Chapter 20 // Drill 6, 7, 8 - Principles & Practice Using C++

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

Drill 6

Write a simple copy() operation,
template<typename Iter1, typename Iter2>
    // requires Input_iterator<iter1>() && Output_iterator<Iter2>()
Iter2 copy(Iter f1, Iter e1, Iter f2);
that  copies [f1, e1) to [f2, f2+(e1-f1)) and returns f2+(e1 - f1) just like the standard library copy function. Note that if f1==e1 the sequence is empty, so that there is nothing to copy.

Drill 7

Use your copy() to copy the array into the vector and to copy the list into the array.

Drill 8

Use the standard library function find() to see if the vector contains the value 3 and print out its position if it does; use find() to see if the list contains the value 27 and print out it's position if it does. The "position" of the first element  is 0, the position of the second element is 1, etc. Note that if find() returns the end of the sequence, the value wasn't found.

Github: 

In drill 7 I realised he meant to use a std:: array as a normal C array does not have iterators built in, so I changed it.

I did discover some nice std functions in these drills though. Namely distance() which returns the index of an iterator and find. I'm sure I've used find before but now I actually understand what it's doing "under the hood".

No comments:

Post a Comment