浮云间
如果目标是graph按成本对每个切片进行排序,则只需实现sort.Interfaceon []Graph,然后使用 for 循环遍历值。type ByCost []Graphfunc (gs *ByCost) Len() int { return len(gs) }func (gs *ByCost) Less(i, j int) bool { return gs[i].cost < gs[j].cost }func (gs *ByCost) Swap(i, j int) { gs[i], gs[j] = gs[j], gs[i] }for _, v := range graph { sort.Sort(ByCost(v))如果您尝试按照中的成本总和排序的顺序遍历地图[]Graph,那将变得不那么干净。type GraphKeyPairs struct { key string value []Graph}// Build a slice to store our map valuessortedGraph := make([]GraphKeyPairs, 0, len(graph))for k,v := range graph { // O(n) gkp := GraphKeyPairs{key: k, value: v} sortedGraph = append(sortedGraph, gkp)}type BySummedCost []GraphKeyPairsfunc (gkp *BySummedCost) Len() int { return len(gkp) }func (gkp *BySummedCost) Swap(i, j int) { gkp[i], gkp[j] = gkp[j], gkp[i] }func (gkp *BySummedCost) Less(i, j int) bool { // O(2n) iCost, jCost := 0, 0 for _, v := range gkp[i].value { iCost += v.cost } for _, v := range gkp[j].value { jCost += v.cost } return iCost < jCost}sort.Sort(BySummedCost(sortedGraph))