英文:
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);
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论