How can I copy a part of an array to another array in C++?
Assuming you want a dynamically-allocated array as in the C# example, the simplest way is:
std::vector<int> b(a.begin() + 1, a.begin() + 4);
This also has the advantage that it will automatically release the allocated memory when it's destroyed; if you use new
yourself, then you'll also need to use delete
to avoid memory leaks.
Yes, use std::copy
:
std::copy(a + src_begin_index,
a + src_begin_index + elements_to_copy,
b + dest_begin_index);
The equivalent of your C# example would be:
std::copy(a + 1, a + 4, b);