gpt4 book ai didi

c# - 为什么我的数组索引在此算法中越界?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:11:17 26 4
gpt4 key购买 nike

所以我在下面的注释代码中做了一些不言自明的练习

using System;
using System.Collections.Generic;
using System.Linq;

public class Program
{

public static int[,] GetPairs ( int [] arr )
{
// given an array arr of unique integers, returns all the pairs
// e.g. GetPairs(new int [] { 1, 2, 3, 4, 5 }) would return
// { {1, 2}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}, {3, 4}, {3, 5}, {4, 5} }

int n = (arr.Length * (arr.Length - 1))/2; // number of pairs unique pairs in an array of unique ints
if ( n < 1 ) return new int[0,2] {}; // if array is empty or length 1
int[,] pairs = new int[n,2]; // array to store unique pairs
// populate the pairs array:
for ( int i = 0, j = 0; i < arr.Length; ++i )
{
for ( int k = i + 1; k < arr.Length; ++k )
{
pairs[j,0] = arr[i];
pairs[j,1] = arr[k];
++j;
}
}
return pairs;
}

public static void Main()
{
int [] OneThroughFour = new int [4] { 1, 2, 3, 4 };
int [,] Pairs = GetPairs(OneThroughFour);
for ( int i = 0; i < Pairs.Length; ++i )
{
Console.WriteLine("{0},{1}",Pairs[i,0],Pairs[i,1]);
}

}
}

我得到的错误是

[System.IndexOutOfRangeException: Index was outside the bounds of the array.]

在循环中

    for ( int i = 0; i < Pairs.Length; ++i )
{
Console.WriteLine("{0},{1}",Pairs[i,0],Pairs[i,1]);
}

这对我来说没有任何意义。什么是越界?肯定不是 i , 因为它在 0 范围内, 1 , ..., Pairs.Length - 1 .肯定不是 01 ,因为这些是有效的索引。

此外,是否有可能比 O(n^2) 做得更好? .NET 有没有一种更紧凑、更高效的方法?

最佳答案

对于二维数组,Length 属性返回第一个维度的长度乘以第二个维度的长度。在您的情况下,这等于 2 * n

据我所知,您想要的是遍历第一个维度。

使用 GetUpperBound像这样的方法:

for (int i = Pairs.GetLowerBound(0); i <= Pairs.GetUpperBound(0); ++i)
{
//...
}

关于c# - 为什么我的数组索引在此算法中越界?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36119426/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com