【问题标题】:Searching a two dimensional array using Length property使用 Length 属性搜索二维数组
【发布时间】:2017-09-12 13:22:05
【问题描述】:

好的,我正在尝试使用 Length 属性搜索二维数组(我必须使用它,否则我只使用 GetLength() )。该数组随机填充一组行数和列数。它会询问用户要搜索的数字,然后它将搜索数组并返回真或假,如果找到该数字,则返回行和列的索引。

我对我为正确设置 for 循环所做的研究中的代码相当有信心,但目前我收到一条错误消息,提示“[] 内的索引数量错误;预期为 2”尝试搜索数组的列。

我查看了这个错误,发现这应该是正确的设置。所以,我不确定这个循环的问题出在哪里,有人可以看看让我知道我错过了什么步骤吗?

谢谢!

int [,] math;
math = new int[3, 5]; //So you can see my array that is declared in main

static bool SearchArray(int search, int [,] array, out int row, out int coln)
    {
        row = -1;
        coln = -1;
        // search parameter is given from another method where it asks the user for a number to search for in the array.

        for (int x = 0; x < array.Length; x++)
        {
            for (int y = 0; y < array[x].Length; y++) //error is here with the array[x] and continues to any reference I try to make similarly.
            {
                if (array[x][y] == search)
                {
                    row = array[x];
                    coln = array[y];
                    return true;
                }
            }
        }
        return false

【问题讨论】:

    标签: c# arrays loops search multidimensional-array


    【解决方案1】:

    请参阅this question,详细了解多维数组(如您在此处使用的)和交错数组(数组的数组)之间的区别。

    如果你像这样声明一个多维数组:

    int [,] math = new int[3, 5];
    

    您必须像这样访问其中的值:

    int value = math[1,2];
    

    如果你声明一个交错数组,像这样:

    int[][] math = new int[3][];
    math[0] = new int[5];
    math[1] = new int[5];
    math[2] = new int[5];
    

    (虽然通常子数组的大小会有所不同 - 因此呈锯齿状。) 然后您访问这些值:

    int value = math[1][2];
    

    对于您的特定问题,如果使用多维数组,您还需要使用“Array.GetLength”,如:

    for (int x = 0; x < array.GetLength(0); x++)
    

    获取零件的各个尺寸(如this question)。在您的示例中,“.Length”为您提供数组的 total 大小,而不是第一个维度的长度。

    【讨论】:

      【解决方案2】:

      您将锯齿状数组与多维数组(实际上是二维数组)混合在一起。两个暗淡的解决方案。数组会是这样的:

      static bool SearchArray(int search, int [,] array, out int row, out int coln) 
      { 
          row = -1; 
          coln = -1;
          for (int x = 0; x < array.GetLength(0); x++)
          { 
              for (int y = 0; y < array.GetLength(1); y++)
              { 
                  if (array[x,y] == search) 
                  { 
                      row = x; 
                      coln = y; 
                      return true; 
                  } 
              } 
          } 
          return false
      }
      

      【讨论】:

      • 澄清一下,我必须使用 GetLength() 来搜索,没有其他选项可以代替 GetLength() 吗?
      • 是的。 GetLength 方法获取所选等级的长度。 Length 属性仅返回数组中的总项目大小。这是最精确的方式。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 2014-03-04
      • 2022-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多