3

How can I copy dynamic array like that: Copy all elements of array, but start in second array not from 0 index, but from first.

//We have array x, which have 5 elements, and array y, which have 6 elements;
y[1]=x[0];
y[2]=x[1];
//etc...

P.S. Don't want copy element by element, can I use in that way std::copy or memcpy ??

EDIT: Is it more efficient way to reallocate an array than this?

int* arr = new int[20];
...
//wanna resize to 25?
int* temp = new int[25];
std::copy(arr, arr+20, temp);
delete [] arr;
arr = temp;
... //now arr has 25 elements

But without using vector or other stl objects.

bingo157
  • 113
  • 1
  • 2
  • 12
  • Since we don't know what is *in* your arrays, its hard to say whether `std::copy`, `memcpy`, both, or *neither* is appropriate for your task. `std::copy` would *likely* work, but that assumes whatever type these are is at-least assignable. – WhozCraig Apr 27 '15 at 06:51
  • it has `uint8_t` variables – bingo157 Apr 27 '15 at 06:58
  • ok, i have it, thanks a lot for help ;) – bingo157 Apr 27 '15 at 07:37

2 Answers2

4

std::copy uses iterators, so you can increment the destination iterator by one:

for fixed size arrays and c++11, this should work:

std::copy( std::begin(x), std::end(x), std::begin(y)+1 )

for dynamic arrays, std::end does not work, but pointer arithmetics can be used:

std::copy( x, x+5, y+1 )
meddle0106
  • 1,292
  • 1
  • 11
  • 22
1

You can use either std::copy or any of the appropriate memory copy/move functions (memcpy, memmove if regions overlap) for your situation, the latter because your object type (uint8_t) is trivially-copy-assignable.

You should also know std::copy will likely do the latter for you if your type is trivially copy assignable (and uint8_t is so). This is not a requirement (at least none that I'm aware of, I'm sure I'll hear about it if it is) but each vendor I've seen provides a SFINAE solution for trivially-copy-assignable objects to simply perform a memmove in the interest of efficiency.

In short, you will likely get what you want with std::copy

std::copy(x, x+x_len, y+1);

and make sure y has at least x_len+1 slots available.

WhozCraig
  • 65,258
  • 11
  • 75
  • 141