英文:
Why sort function in Go and C++ is different? And I can't get the right results in Go
问题
我想对名为nums的切片进行排序,同时不破坏原始顺序。所以我使用inds来记录nums的索引,并对inds进行排序:
nums := []int{1,3,2,1,1,1}
inds := []int{0,1,2,3,4,5}
sort.Slice(inds, func(i, j int) bool {
return nums[i] > nums[j]
})
fmt.Println(inds)
在Go语言中,排序后的inds结果是[1 0 2 3 4 5],与C++的结果和我的预期不同。为什么Go无法正确排序inds呢?
英文:
I want to sort a slice named nums while not disrupting the original order.
So I use inds to record the index of nums and sort inds:
vector<int> nums = {1,3,2,1,1,1};
vector<int> inds = {0,1,2,3,4,5};
sort(inds.begin(), inds.end(),
[nums](int i, int j) -> bool
{
return nums[i] > nums[j];
});
for(int i : inds) {
cout << i;
}
The inds is 120345 after sort. While in Go, I test:
nums := []int{1,3,2,1,1,1}
inds := []int{0,1,2,3,4,5}
sort.Slice(inds, func(i, j int) bool {
return nums[i] > nums[j]
})
fmt.Println(inds)
And The inds is [1 0 2 3 4 5] after sort, which is different from the result of C++ and what I expected.
Why Go can't sort inds well?
答案1
得分: 2
匿名函数的参数i和j是在inds中的索引,但程序将这些参数作为在nums中的索引使用。
通过使用inds将索引值转换为nums来修复:
sort.Slice(inds, func(i, j int) bool {
return nums[inds[i]] > nums[inds[j]]
})
英文:
The anonymous function arguments i and j are indices in inds, but the program uses the arguments as indices in nums.
Fix by using inds to translate the index values to nums:
sort.Slice(inds, func(i, j int) bool {
return nums[inds[i]] > nums[inds[j]]
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论