Hello again! In this video, we are going to look at copying algorithms. A copying algorithm
does what you might expect.
It will copy elements from one iterator range into another one.
The main use for this is for populating sequential containers.
So we have one container with some data in it, and we can use that data to populate an empty container.
The basic algorithm is called copy().
We give
it the iterator range of the container that we are copying from.
And then an iterator range in the container where we want to copy the data to.
This assumes that the vector is the right size, or that you are using an insert
iterator.
So here is some code for printing that out.
We have a vector that we are going to copy, and then we have our call to copy().
So the first version with a vector of the correct size.
Then we have another attempt with a insert iterator.
And then finally, we use a handwritten loop.
So these should all give the same answers.
Okay.
There's also a copy_n() algorithm, which will copy the first "n" elements from the range.
So we can have copy_n(), the start of the iterator range,
and then the number of elements that we want to copy.
So that is equivalent to just leaping over the first two elements of the vector.
And then, using the same vector again, we call copy_n() to copy two elements, and
we also have the handwritten equivalent.
So there we are.
We only get the first two elements of the vector copied. And the final algorithm is
copy_if(). So, this is a version of copy(), which will only do the copy if a predicate returns true.
So we call this with the same arguments and a callable object.
We are going to use our favourite lambda expression, which returns true for odd numbers and false for
even numbers.
And this will only copy the odd numbers from "vec" into "vec2". The even numbers will be ignored.
And there is our call to copy_if(). And if we were doing this by hand, then we would have an if statement
which does the same thing.
So we get the odd numbers copied, but the even number is ignored.
So you can think of copy_if() as acting as a kind of filter between the two vectors.
So we have the data in "vec" and it gets passed into "vec2", but only if it meets this criterion.
If it does not meet the criterion, it gets filtered out.
So here, we are filtering out the even numbers, but you could do anything you want to really. So
you can apply whatever filter is needed for your problem.
Okay, so that is it for this video.
I'll see you next time, but until then, keep coding!