22

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 = {1,2,3,4,5};

Now if I give the start index and end index of the array a it should get copied to another array.

Like if I give start index as 1 and end index as 3, the elements 2, 3, 4 should get copied in the new array.

In C# it is done as following

     int[] b = new int[3];
    Array.Copy(a, 1, b, 0, 3);

Is there any simple way like this to do the same task in C++?

  • 3
    Even better, use `std::vector` instead of the arrays in the first place. It has a constructor that does what you're doing, among many other great features. – chris Jun 19 '12 at 13:37

6 Answers6

24

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);
Increasingly Idiotic
  • 5,700
  • 5
  • 35
  • 73
6

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.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

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.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

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!

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
1

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
}
jpalecek
  • 47,058
  • 7
  • 102
  • 144
0

If you are using vector in CPP, you can do it this way -

Suppose you want to copy elements from arr from index A to index B, you can do it this way -

vector<int>nums(arr.begin()+A, arr.begin()+B+1);

Note - nums will be created as A[start, end) so we need to add extra 1

Gaurav
  • 19
  • 4