如何在C++中找到2D数组的大小?是否有任何预定义函数sizeof来确定数组的大小?
此外,任何人都可以告诉我如何getvalue在尝试获取未设置的值时检测数组方法中的错误?
Sri*_*tha 27
假设您只允许使用数组,那么您可以通过以下方式找到二维数组的大小.
int ary[][5] = { {1, 2, 3, 4, 5},
{6, 7, 8, 9, 0}
};
int rows = sizeof ary / sizeof ary[0]; // 2 rows
int cols = sizeof ary[0] / sizeof(int); // 5 cols
Run Code Online (Sandbox Code Playgroud)
App*_*ker 12
用一个std::vector.
std::vector< std::vector<int> > my_array; /* 2D Array */
my_array.size(); /* size of y */
my_array[0].size(); /* size of x */
Run Code Online (Sandbox Code Playgroud)
或者,如果你只能使用一个好的阵列,你可以使用sizeof.
sizeof( my_array ); /* y size */
sizeof( my_array[0] ); /* x size */
Run Code Online (Sandbox Code Playgroud)
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char const *argv[])
{
int arr[6][5] = {
{1,2,3,4,5},
{1,2,3,4,5},
{1,2,3,4,5},
{1,2,3,4,5},
{1,2,3,4,5},
{1,2,3,4,5}
};
int rows = sizeof(arr)/sizeof(arr[0]);
int cols = sizeof(arr[0])/sizeof(arr[0][0]);
cout<<rows<<" "<<cols<<endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:6 5
小智 5
int rows = sizeof(arr)/sizeof(arr[0]);
int cols = sizeof(arr[0])/sizeof(arr[0][0]);
Run Code Online (Sandbox Code Playgroud)