简体   繁体   中英

Swap rows in a 2D array with std::swap. How does it work?

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?

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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM