猿问

对地图进行排序 [string][]struct{}

我想按成本对这张地图进行排序


type Graph struct {

    vertice string

    cost    float64

}


var graph map[string][]Graph

按照从低到高的顺序


一只萌萌小番薯
浏览 169回答 1
1回答

浮云间

如果目标是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 {&nbsp; &nbsp; sort.Sort(ByCost(v))如果您尝试按照中的成本总和排序的顺序遍历地图[]Graph,那将变得不那么干净。type GraphKeyPairs struct {&nbsp; &nbsp; key string&nbsp; &nbsp; value []Graph}// Build a slice to store our map valuessortedGraph := make([]GraphKeyPairs, 0, len(graph))for k,v := range graph {&nbsp; &nbsp; // O(n)&nbsp; &nbsp; gkp := GraphKeyPairs{key: k, value: v}&nbsp; &nbsp; 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 {&nbsp; &nbsp; // O(2n)&nbsp; &nbsp; iCost, jCost := 0, 0&nbsp; &nbsp; for _, v := range gkp[i].value {&nbsp; &nbsp; &nbsp; &nbsp; iCost += v.cost&nbsp; &nbsp; }&nbsp; &nbsp; for _, v := range gkp[j].value {&nbsp; &nbsp; &nbsp; &nbsp; jCost += v.cost&nbsp; &nbsp; }&nbsp; &nbsp; return iCost < jCost}sort.Sort(BySummedCost(sortedGraph))
随时随地看视频慕课网APP

相关分类

Go
我要回答