c++ - 使用嵌套的 while 循环查找二维数组的数组长度
问题描述
我似乎无法通过嵌套的 while 循环获得数组长度。rows 和 cols 可以是任何值,但我需要验证它们是否等于数组长度。数组长度 = 行*列
嵌套的 for 循环对我没有帮助,因为我不知道输入的数组可能有多长。
void add(char arr[][SIZE], int rows, int cols, int val) {
int arrayStorage = 0;
int arrayStorage2 = 0;
while (arr[arrayStorage][arrayStorage2] != 0 && (isalpha(arr[arrayStorage][arrayStorage2]) || isdigit(arr[arrayStorage][arrayStorage2]) || arr[arrayStorage][arrayStorage2] == ' ') && (isprint(arr[arrayStorage][arrayStorage2]) || !(iscntrl(arr[arrayStorage][arrayStorage2]))))
{
arrayStorage2 = 0;
while (arr[arrayStorage][arrayStorage2] != 0 && (isalpha(arr[arrayStorage][arrayStorage2]) || isdigit(arr[arrayStorage][arrayStorage2]) || arr[arrayStorage][arrayStorage2] == ' ') && (isprint(arr[arrayStorage][arrayStorage2]) || !(iscntrl(arr[arrayStorage][arrayStorage2]))))
{
arrayStorage2++;
}
arrayStorage2--;
arrayStorage++;
}
int storage3 = (arrayStorage2) * arrayStorage;
cout << storage3;
char addVal = (char)val;
if (( storage3 == (rows * cols)) && rows > 0 && rows <= SIZE && cols > 0 && cols <= SIZE)
{
// do stuff
}
}
int main()
{
char arr4 [][SIZE] = {{'a','b','c',' ',' '}, {'d','e','f',' ',' '}, {'g','r','o','w','n'}, {'n','o','w',' ',' '}};
add(arr4,4,5,5);
return 0;
}
storage3 数组长度应该是 20 时是 5
解决方案
做到这一点的一种方法可能是根本不循环!更改用作数组的类型。如果不是char arr[][]
您定义一个环绕数组并公开其维度的类型。就像是:
template <int tRows, int tCols>
class Array2d
{
public:
static constexpr int sRows = tRows;
static constexpr int sCols = tCols;
char mArr[tRows][tCols]
};
然后您可以使您的添加功能成为模板功能并在您的支票中使用公开的尺寸
template <class Array_t>
void add(Array_t& arr, int rows, int cols)
{
int storage3 = Array_t::sRows * Array_t::sCols;
if (( storage3 == (rows * cols)) && rows > 0 && rows <= SIZE && cols > 0 && cols <= SIZE)
{
// do stuff
}
}
推荐阅读
- c++ - 为什么在这段代码中,当“swap”函数写在 int main() 之后而不是在它之前时,会发生交换?
- ios - Swift - 解决方法/替代 M3u8 播放 mp4 片段或将片段合并到 mp4
- sql - 如何在 BigQuery 中进行分区外连接
- docker - 使用 CircleCI 的预建镜像与拉取私有镜像之间的权衡是什么?
- android - styles.xml 未按预期应用
- docker - Docker容器到容器连接:连接被拒绝
- java - 如何通过在 java-sql 应用程序上输入所有列数据来过滤搜索?
- c - 如何在 C 代码中使用单精度浮点实现 FIR 滤波器?
- tcp - 使用 netstat -s 在 Solaris 10 中计算 TCP 重传
- python - 读取超时。向 node.js API 发送 POST 请求时出错