[英]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]
. 而且,我很想知道
std::swap
如何在类似于Arr[10][10]
的2D数组上工作。
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'. 我可以理解如果我们的数据类型是交换两个“行”,比如说像
int** Arr2D
类的指针的指针,然后与std::swap(Arr2D[2], Arr2D[5])
因为我们不需要知道在这里的长度,我们只需要交换两个指针,就指向“一维数组”。
But how does std::swap
work with Arr[y][x]
? 但是
std::swap
如何与Arr[y][x]
?
Is it using a loop maybe, to swap all elements within x
length? 是否使用循环交换
x
长度内的所有元素?
std::swap
has an overload for arrays that effectively swaps each two elements, again, using std::swap
. std::swap
的数组有一个重载 ,可以使用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
. 至于大小信息,它嵌入在数组类型内(
Arr[i]
为int[x]
),因此编译器知道将T2
推导为int
并将N
推导为10
。
OT: Why aren't variable-length arrays part of the C++ standard? OT: 为什么可变长度数组不是C ++标准的一部分? ( but this particular case is OK )
( 但这种情况可以 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.