排序地图[string] [] struct {}

时间:2016-01-23 00:09:33

标签: sorting dictionary struct go

我希望通过费用

对此地图进行排序
type Graph struct {
    vertice string
    cost    float64
}

var graph map[string][]Graph

按从低到高的顺序

谢谢!

1 个答案:

答案 0 :(得分:1)

如果目标是按费用对graph中的每个切片进行排序,则只需在[]Graph上实施sort.Interface,然后使用for循环遍历值。

type ByCost []Graph

func (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 values
sortedGraph := make([]GraphKeyPairs, 0, len(graph))
for k,v := range graph {
    // O(n)
    gkp := GraphKeyPairs{key: k, value: v}
    sortedGraph = append(sortedGraph, gkp)
}

type BySummedCost []GraphKeyPairs

func (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))