dtby67541 2013-11-13 06:35
浏览 46
已采纳

对结构图进行排序-GOLANG

I have a map of structs that I am populating by streaming data to a Go program. The way the map is updated is similar to the example below.

Once I have this map of structs populated, what is the best (or good) way to sort this map by the values of the count field in the struct?

package main

type data struct {
    count int64
}

func main() {
    m := make(map[string]data)
    m["x"] = data{0, 0}
    if xx, ok := m["x"]; ok {
        xx.count = 2
        m["x"] = xx
    } else {
        panic("X isn't in the map")
    }
}

This example can be run here: http://play.golang.org/p/OawL6QIXuO

  • 写回答

1条回答 默认 最新

  • dongshenjie3055 2013-11-13 07:57
    关注

    As siritinga already pointed out, the elements of a map isn't ordered, so you cannot sort it.

    What you can do is to create a slice and sort the elements using the sort package:

    package main
    
    import (
        "fmt"
        "sort"
    )
    
    type dataSlice []*data
    
    type data struct {
        count int64
        size  int64
    }
    
    // Len is part of sort.Interface.
    func (d dataSlice) Len() int {
        return len(d)
    }
    
    // Swap is part of sort.Interface.
    func (d dataSlice) Swap(i, j int) {
        d[i], d[j] = d[j], d[i]
    }
    
    // Less is part of sort.Interface. We use count as the value to sort by
    func (d dataSlice) Less(i, j int) bool {
        return d[i].count < d[j].count
    }
    
    func main() {
        m := map[string]*data {
            "x": {0, 0},
            "y": {2, 9},
            "z": {1, 7},
        }
    
        s := make(dataSlice, 0, len(m))
    
        for _, d := range m {
            s = append(s, d)
        }       
    
        // We just add 3 to one of our structs
        d := m["x"]
        d.count += 3
    
        sort.Sort(s)
    
        for _, d := range s {
            fmt.Printf("%+v
    ", *d)
        }
    }
    

    Output:

    {count:1 size:7}
    {count:2 size:9}
    {count:3 size:0}

    Playground

    Edit

    Updated the example to use pointers and to include a map so that you can both do lookups and have a slice to sort over.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog