英文:
Sorting a map[string][]struct{}
问题
我会帮你翻译以下内容:
我想按照cost对这个地图进行排序
type Graph struct {
vertice string
cost float64
}
var graph map[string][]Graph
按照从低到高的顺序排列
谢谢!
英文:
I would likde to sort this map by cost
type Graph struct {
vertice string
cost float64
}
var graph map[string][]Graph
In the order of lowest to highest
Thanks!
答案1
得分: 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
}
// 构建一个切片来存储映射的值
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))
英文:
If the goal is to sort each slice in graph
by cost, you only need to implement sort.Interface
on []Graph
, then use a for loop to loop through the values.
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))
If you're trying to iterate through the map in sorted order by the sum of the costs in the []Graph
, that's going to be much less clean.
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论