亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

我的 golang stldib 排序出了什么問題?

我的 golang stldib 排序出了什么問題?

Go
慕村225694 2023-05-22 17:15:42
我正在嘗試按其字段之一對(Golang)結構切片進行排序。我看了很多示例、go-playgrounds 和文檔,我覺得我明白了,但我仍然無法讓我的代碼正常工作。package mainimport (? ? "fmt"? ? "sort")type Method struct {? ? MethodNumber int? ? ? ?`json:"methodNumber"`? ? MethodRank? ?int? ? ? ?`json:"rank"`? ? MethodRMSE? ?float64? ?`json:"error"`? ? Forecast? ? ?[]float64 `json:"forecast"`}// extra stuff for sorting.type ByError []Methodfunc (s ByError) Len() int {? ? return len(s)}func (s ByError) Swap(i, j int) {? ? s[i], s[j] = s[j], s[i]}func (s ByError) Less(i, j int) bool {? ? return s[i].MethodRMSE < s[i].MethodRMSE}func main() {? ? xs := make([]Method, 0)? ? fmt.Println(len(xs))? ? xs = append(xs, Method{MethodNumber: 1, MethodRMSE: 10})? ? xs = append(xs, Method{MethodNumber: 2, MethodRMSE: 8})? ? xs = append(xs, Method{MethodNumber: 3, MethodRMSE: 6})? ? xs = append(xs, Method{MethodNumber: 4, MethodRMSE: 4})? ? fmt.Printf("%+v \n", xs)? ? sort.Sort(ByError(xs))? ? fmt.Printf("%+v \n", xs)? ? sort.Sort(sort.Reverse(ByError(xs)))? ? fmt.Printf("%+v \n", xs)}我的非工作代碼:https://play.golang.org/p/h8SHVjTQSPM我的應該按 RMSE 排序,但它根本不會改變順序。現在,我的 go playground 的結果應該是按 RMSE 升序排序,然后反向排序。
查看完整描述

1 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

這里打字錯誤

func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[i].MethodRMSE
}

應該

func (s ByError) Less(i, j int) bool {
    return s[i].MethodRMSE < s[j].MethodRMSE
}

因為它有點難看,第一個(錯誤的)版本將項目與自身進行比較(兩個索引都是i)。第二個正確地使用了ij。


查看完整回答
反對 回復 2023-05-22
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號