Sorting 对映射[字符串][]结构{}进行排序
我想按成本对这张地图进行排序Sorting 对映射[字符串][]结构{}进行排序,sorting,dictionary,struct,go,Sorting,Dictionary,Struct,Go,我想按成本对这张地图进行排序 type Graph struct { vertice string cost float64 } var graph map[string][]Graph 按从低到高的顺序 谢谢 如果目标是按成本对图中的每个片段进行排序,则只需在[]图上实现,然后使用for循环循环值 type ByCost []Graph func (gs *ByCost) Len() int { return len(gs) } func (gs *ByCost)
type Graph struct {
vertice string
cost float64
}
var graph map[string][]Graph
按从低到高的顺序
谢谢 如果目标是按成本对
图中的每个片段进行排序,则只需在[]图上实现,然后使用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))
目前还不清楚“分类地图”是什么意思。之后你想做什么?地图是无序的,因此它们在传统意义上是不可排序的。您对使用排序有疑问吗?
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))