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