首页 > 解决方案 > 使用嵌套的 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

标签: c++while-loopnested-loops

解决方案


做到这一点的一种方法可能是根本不循环!更改用作数组的类型。如果不是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
     }
}

推荐阅读