Home > Blockchain >  how to swap arrays without copying elements
how to swap arrays without copying elements

Time:06-01

I'd like to swap two integer arrays without copying their elements :

int  Z1[10],Z2[10];
std::swap(Z1,Z2);  // works
//int *tmp;*tmp=*Z1;*Z1=*Z2;*Z2=*tmp; // doesn't work
[ expressions involving Z1,Z2 ]

In the third line I commented out what I tried and didn't work Is there a way to do this by swapping pointers instead...

CodePudding user response:

how to swap arrays without copying elements

By virtue of what swapping is, and what arrays are, it isn't possible to swap arrays without copying elements (to be precise, std::swap swaps each element and a swap is conceptually a shallow copy).

What you can do is introduce a layer of indirection. Point to the arrays with pointers. Then, swapping the pointers will swap what arrays are being pointed without copying elements:

int* ptr1 = Z1;
int* ptr2 = Z2;
std::swap(ptr1, ptr2); // now ptr1 -> Z2, ptr2 -> Z1

CodePudding user response:

You could do what you attempted, but using dynamically allocated arrays:

int* tmp;
int* Z1 = new int[10];
int* Z2 = new int[10];

// do something...

tmp = Z2; 
Z2 = Z1; 
Z1 = tmp;
  • Related