Copy from One Iterator to Another
Learn to copy from one iterator to another.
We'll cover the following...
The copy algorithms are generally used to copy from and to containers, but in fact, they work with iterators, which is far more flexible.
How to do it
In this recipe, we will experiment with std::copy
and std::copy_n
to get a good understanding of how they work:
Let's start with a function to print a container:
void printc(auto& c, string_view s = "") {if(s.size()) cout << format("{}: ", s);for(auto e : c) cout << format("[{}] ", e);cout << '\n';}
In
main()
, we define a vector and print it withprintc()
:
int main() {vector<string> v1{ "alpha", "beta", "gamma", "delta","epsilon" };printc(v1);}
We get this output:
v1: [alpha] [beta] [gamma] [delta] [epsilon]
Now, let's create a second
vector
with enough space to copy the firstvector
:
vector<string> v2(v1.size());
We can copy
v1
...