`Array.Sort`正在改变在Unity中未指定的数组。

huangapple go评论69阅读模式
英文:

Array.Sort is changing unspecified arrays in unity

问题

我正在尝试对数组和索引列表进行排序,但我希望原始数组保持不变。

当我使用Array.Sort()函数时,它不仅对指定的数组进行排序,还对fitnessVals数组进行排序(请参见下面的代码)。有人知道为什么会这样吗,以及我可以采取什么措施阻止它发生?

我的代码:

tempFitnessVals = new float[numberOfItems];
tempFitnessVals = fitnessVals;
int[] indexes = new int[tempFitnessVals.Length];
for (int i = 0; i < indexes.Length; i++)
{
    indexes[i] = i;
}
Array.Sort(tempFitnessVals, indexes);
Array.Reverse(tempFitnessVals);
Array.Reverse(indexes);
英文:

I am trying to sort an array, and a list of indices, but I want the original array to stay the same.

When I use the Array.Sort() function, it not only sorts the specified arrays, but also the fitnessVals array (see code below). Does anyone know why this is, and what I can do to stop it from happening?

My code:

        tempFitnessVals = new float[numberOfItems];
        tempFitnessVals = fitnessVals;
        int[] indexes = new int[tempFitnessVals.Length];
        for (int i = 0; i < indexes.Length; i++)
        {
            indexes[i] = i;
        }
        Array.Sort(tempFitnessVals, indexes);
        Array.Reverse(tempFitnessVals);
        Array.Reverse(indexes);

答案1

得分: 2

以下代码创建了一个引用并导致你面临的问题:

tempFitnessVals = fitnessVals;

你需要将这行替换为 Array.Copy

...
Array.Copy(fitnessVals, tempFitnessVals, numberOfItems);
...
英文:

The following code makes a reference and causes the issue you are facing:

tempFitnessVals = fitnessVals;

You need to replace this line with Array.Copy:

...
Array.Copy(fitnessVals, tempFitnessVals, numberOfItems);
...

huangapple
  • 本文由 发表于 2023年5月13日 14:09:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76241334.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定