This is the same question asked in C# but i need for C++
How can I copy a part of an array to another array?
Consider I\'m having
int[] a = {
Yes, using st standard library algorithm copy
:
#include <algorithm>
int main()
{
int array[5] = { 1,2,3,4,5 }; // note: no int[] array
int *b = new int[3];
std::copy(array+1, array+4, b);
// copies elements 1 (inclusive) to 4 (exclusive), ie. values 2,3,4
}
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);
For simple C-style arrays you can use memcpy
:
memcpy(b, &a[1], sizeof(int) * 3);
This line copies sizeof(int) * 3
bytes (i.e. 12 bytes) from index 1 of a
, with b
as a destination.
There is the C
memcpy command, which you can use like this:
memcpy(destinationArray, sourceArray, sizeof(*destinationArray) * elementsToCopy);
There is also std::copy, which is a more C++
way of doing it:
std::copy(source, source + elementsInSource, destination);
Note that neither of these functions check to make sure that enough memory has been allocated, so use at your own risk!