2

I'm mostly just documenting this question as someone may stumble upon it, and may find it useful. And also, I'm very curios with, how does std::swap works on a 2D array like: Arr[10][10].

My question arised because as to my understanding an array like this is just a 1D array with some reindexing.
For reference: How are 2-Dimensional Arrays stored in memory?

int main()
{
    const int x = 10;
    const int y = 10;
    int Arr[y][x];
    // fill the array with some elements...
    for (int i = 0; i < x*y; i++)
    {
        Arr[i / y][i % x] = i;
    }

    // swap 'row 5 & 2'
    // ??? how does swap know how many elements to swap?
    // if it is in fact stored in a 1D array, just the
    // compiler will reindex it for us
    std::swap(Arr[5], Arr[2]);

    return 0;
}

I could understand swapping two 'rows' if our data type is, say a pointer to a pointer like int** Arr2D then swap with std::swap(Arr2D[2], Arr2D[5]) as we do not need to know the length here, we just need to swap the two pointers, pointing to '1D arrays'.
But how does std::swap work with Arr[y][x]?
Is it using a loop maybe, to swap all elements within x length?

skyzip
  • 237
  • 2
  • 11
  • 1
    The short answer is `type` is king. A 2D array decays to a pointer to the first 1D array on access. (in your case a *pointer-to-array of int [10]*) `std::swap` is required to know the size of what it must swap and by dereferencing the pointer-to-array by using `[...]` leaves the type as `int[10]` which `std::swap` can deal with. You are swapping two `int[10]` arrays. – David C. Rankin Aug 15 '19 at 20:50
  • For the basis in the standards (both applicable), see [C Standard - 6.3.2.1(p3)](http://port70.net/~nsz/c/c11/n1570.html#6.3.2.1p3) incorporated for fundamental types and extended in [C++ Standard - 7.3.2 Array-to-pointer conversion](https://en.cppreference.com/w/cpp/language/value_category) – David C. Rankin Aug 15 '19 at 20:59

1 Answers1

4

std::swap has an overload for arrays that effectively swaps each two elements, again, using std::swap.

As for the size information, it is embedded within the array type (Arr[i] is int[x]), so the compiler knows to deduce T2 as int and N as 10.

OT: Why aren't variable-length arrays part of the C++ standard? (but this particular case is OK)

LogicStuff
  • 19,397
  • 6
  • 54
  • 74