首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >对结构映射进行排序-- GOLANG

问对结构映射进行排序-- GOLANG
EN

Stack Overflow用户
提问于 2013-11-13 14:35:28
回答 1查看 14.4K关注 0票数 12

我有一个结构图,我通过将数据流式传输到Go程序来填充它。地图的更新方式类似于下面的示例。

填充了此结构映射后,根据结构中count字段的值对此映射进行排序的最佳(或好)方法是什么?

代码语言:javascript
复制
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")
    }
}

这个例子可以在这里运行:http://play.golang.org/p/OawL6QIXuO

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-13 15:57:50

正如siritinga已经指出的,map的元素是没有排序的,所以你不能对它排序。

您可以做的是创建一个slice并使用sort包对元素进行排序:

代码语言:javascript
复制
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\n", *d)
    }
}

输出:

{计数:1大小:7}

{计数:2大小:9}

{计数:3大小:0}

Playground

编辑

更新了示例,以使用指针并包含映射,以便您既可以进行查找,又可以对切片进行排序。

票数 26
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19946992

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档