casper
casper

Reputation: 289

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}

Upvotes: 3

Views: 1009

Answers (2)

Brother Wei
Brother Wei

Reputation: 13

you just need to change the value of two pointer,so the parameter is the address of pointer(int **).

int main(int argc, char *argv[])
{
     int * pA = new int[10];
     int * pB = new int[5];
     if(NULL != pA && NULL != pB)
     {
         for (int i = 0; i < 10; i++)
         {
            a[i] = i + 1;
         }
         for (int i = 0; i < 5; i++) 
         {
             b[i] = i + 1;
         }
         swap(&pA,&pB);
         for (int i = 0; i < 5; i++)
         {
            cout << a[i] << " ";
         }
         cout << endl;
         for (int i = 0; i < 5; i++) 
         {
            cout << b[i] << " ";
         }
     }
 }

 void swap(int**pA, int **pB)
 {
     int *pTemp = *pA;
     *pA = *pB;
     *pB = pTemp;
 }

Upvotes: -1

Blaze
Blaze

Reputation: 16876

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.

Upvotes: 4

Related Questions