使用 std::swap 交换二维数组中的行。它是如何工作的?
Swap rows in a 2D array with std::swap. How does it work?
我主要只是记录这个问题,因为有人可能会偶然发现它,并且可能会发现它很有用。而且,我非常好奇 std::swap
如何在二维数组上工作,例如:Arr[10][10]
.
出现我的问题是因为根据我的理解,这样的数组只是一个带有一些重新索引的一维数组。
以供参考:
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;
}
我可以理解交换两个 'rows' 如果我们的数据类型是指向指针的指针,例如 int** Arr2D
然后与 std::swap(Arr2D[2], Arr2D[5])
交换,因为我们不需要知道长度在这里,我们只需要交换两个指针,指向'一维数组'。
但是 std::swap
如何与 Arr[y][x]
一起工作?
是否可能使用循环来交换 x
长度内的所有元素?
std::swap
has an overload for arrays 再次使用 std::swap
.
有效交换每两个元素
至于大小信息,它嵌入在数组类型中(Arr[i]
是 int[x]
),因此编译器知道要 推导 T2
作为 int
和 N
作为 10
.
加时赛:Why aren't variable-length arrays part of the C++ standard? (but this particular case is OK)
我主要只是记录这个问题,因为有人可能会偶然发现它,并且可能会发现它很有用。而且,我非常好奇 std::swap
如何在二维数组上工作,例如:Arr[10][10]
.
出现我的问题是因为根据我的理解,这样的数组只是一个带有一些重新索引的一维数组。
以供参考:
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;
}
我可以理解交换两个 'rows' 如果我们的数据类型是指向指针的指针,例如 int** Arr2D
然后与 std::swap(Arr2D[2], Arr2D[5])
交换,因为我们不需要知道长度在这里,我们只需要交换两个指针,指向'一维数组'。
但是 std::swap
如何与 Arr[y][x]
一起工作?
是否可能使用循环来交换 x
长度内的所有元素?
std::swap
has an overload for arrays 再次使用 std::swap
.
至于大小信息,它嵌入在数组类型中(Arr[i]
是 int[x]
),因此编译器知道要 推导 T2
作为 int
和 N
作为 10
.
加时赛:Why aren't variable-length arrays part of the C++ standard? (but this particular case is OK)