为什么Go和C++中的排序函数不同?而且我在Go中无法得到正确的结果。

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

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

匿名函数的参数ij是在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]]
})

huangapple
  • 本文由 发表于 2022年3月20日 11:41:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/71543860.html
匿名

发表评论

匿名网友

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

确定