Octavian Niculescu
Octavian Niculescu

Reputation: 83

How to use swap() in C++ when the parameters must be 2D arrays using pointers

First of all, I want to make sure that I do access array members properly when using pointers.

Is this equivalent?

for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cin >> a[i][j];
        }
    }

with

for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            cin >> *(*(a + i) + j);
        }
    }

This is how I personally read into arrays when using pointers. If that's fine (I'm asking that because I might be doing it wrong) how should I use the swap function?

I've tried to do it like this:

swap(*(*(a + i) + j), *(*(a + j) + i));

but nothing happens, while doing it this way

int aux = *(*(a + i) + j);
                *(*(a + i) + j) = *(*(a + j) + i);
                *(*(a + j) + i) = *(*(a + i) + j);

makes it work.

Here's the whole function

void parcugereMatrice(int n, int**& a)
{
    for (int i = 0; i < n; i++)
    {
        for (int j = 0; j < n; j++)
        {
            if (paritate(*(*(a+i)+j)) == paritate(*(*(a + j) + i)))
            {
                /*int aux = *(*(a + i) + j);
                *(*(a + i) + j) = *(*(a + j) + i);
                *(*(a + j) + i) = *(*(a + i) + j);*/
                swap(*(*(a + i) + j), *(*(a + j) + i));
            }
        }
    }
}

I think that I'd need to pass the values by reference into the swap function in order to work, but I don't know how. Right now, I think that the values are passed by value, so there will be no changes outside this function (please correct me if I'm wrong).

If that's the answer, how should the parameters look like?

Thanks.

Upvotes: 1

Views: 63

Answers (1)

Kostas
Kostas

Reputation: 4176

You can use std::swap_ranges.

If your pointers are decayed 2D arrays:

void swap(int* a[N], int* b[N], int) {
  if (a != b)
    std::swap_ranges(&a[0][0], &a[N][N], &b[0][0]);
}

If your pointers are decayed arrays of pointers to arrays:

void swap(int** a, int** b, int n) {
  if (a != b)
    std::swap_ranges(&a[0], &a[n], &b[0]);
}

If your pointers are not decayed (but rather dynamically allocated):

void swap(int** a, int** b, int) {
  std::swap(a, b);
}

Upvotes: 4

Related Questions