Search code examples
c++arraysswap

Swapping arrays


Is there some library fucntion to swap the values in two dynamically allocated arrays.
Suppose i declare and initialize my arrays like:

int * a = new int[10];
int * b = new int[5];
for(int i = 0; i < 10; i++){
a[i] = i + 1;   //stores a[10] = {1,2,3,4,5,6,7,8,9,10}
}  
for(int i = 0; i < 5; i++){
b[i] = i + 1;   //stores b[5] = {1,2,3,4,5}
}  
swap(a,b);  

And i expect the a to store: {1, 2, 3, 4, 5}
And array b should store: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}


Solution

  • All you need to do is swapping the pointers. You can use std::swap for this.

    #include <algorithm>
    
    int main(int argc, char *argv[])
    {
        int * a = new int[10];
        int * b = new int[5];
        for (int i = 0; i < 10; i++) {
            a[i] = i + 1;   //stores a[10] = {1,2,3,4,5,6,7,8,9,10}
        }
        for (int i = 0; i < 5; i++) {
            b[i] = i + 1;   //stores b[5] = {1,2,3,4,5}
        }
    
        std::swap(a, b);
        for (int i = 0; i < 5; i++)
            std::cout << a[i] << " ";
        std::cout << endl;
        for (int i = 0; i < 10; i++)
            std::cout << b[i] << " ";
    }
    

    Output:

    1 2 3 4 5
    1 2 3 4 5 6 7 8 9 10
    

    The dynamically allocated memory isn't touched this way, the only thing that changes are the values of the pointers a and b.