Search code examples
c++swap

how to swap arrays without copying elements


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...


Solution

  • 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