在C ++中访问多维数组的整行 [英] Accessing an entire row of a multidimensional array in C++
问题描述
一个人如何访问多维数组的整个行? 例如:
How would one access an entire row of a multidimensional array? For example:
int logic[4][9] = {
{0,1,8,8,8,8,8,1,1},
{1,0,1,1,8,8,8,1,1},
{8,1,0,1,8,8,8,8,1},
{8,1,1,0,1,1,8,8,1}
};
// I want everything in row 2. So I try...
int temp[9] = logic[2];
我的尝试引发了错误:
数组初始化需要花括号
array initialization needs curly braces
我知道我可以使用FOR循环来检索行,但是我很好奇是否有更明显的解决方案.
I know I can retrieve the row using a FOR loop, however I'm curious if there was a more obvious solution.
推荐答案
这不是数组/指针在C ++中的工作方式.
That's not how arrays/pointers work in C++.
该数组存储在内存中的某个位置.为了引用相同的数据,您需要一个指向数组开头的指针:
That array is stored somewhere in memory. In order to reference the same data, you'll want a pointer that points to the the beginning of the array:
int* temp = logic[2];
或者,如果您需要该阵列的副本,则必须分配更多的空间.
Or if you need a copy of that array, you'll have to allocate more space.
通常:
int temp[9];
for (int i = 0; i < 9; i++) {
temp[i] = logic[2][i];
}
动态地:
// allocate
int* temp = new int(9);
for (int i = 0; i < 9; i++) {
temp[i] = logic[2][i];
}
// when you're done with it, deallocate
delete [] temp;
或者由于使用的是C ++,如果您不想担心所有这些内存和指针,那么对于动态大小的数组应使用std::vector<int>
,对于静态大小的数组应使用std::array<int>
.
Or since you're using C++, if you want to not worry about all this memory stuff and pointers, then you should use std::vector<int>
for dynamically sized arrays and std::array<int>
for statically sized arrays.
#include <array>
using namespace std;
array<array<int, 9>, 4> logic = {
{0,1,8,8,8,8,8,1,1},
{1,0,1,1,8,8,8,1,1},
{8,1,0,1,8,8,8,8,1},
{8,1,1,0,1,1,8,8,1}
}};
array<int, 9> temp = logic[2];
这篇关于在C ++中访问多维数组的整行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!