加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

排序结构图 – GOLANG

发布时间:2020-12-16 19:23:12 所属栏目:大数据 来源:网络整理
导读:我有一个结构图,我通过将数据流传输到Go程序来填充.更新地图的方式与下面的示例类似. 一旦我填充了这个结构图,那么通过结构中count字段的值对这个地图进行排序的最佳(或好)方法是什么? package maintype data struct { count int64}func main() { m := make
我有一个结构图,我通过将数据流传输到Go程序来填充.更新地图的方式与下面的示例类似.

一旦我填充了这个结构图,那么通过结构中count字段的值对这个地图进行排序的最佳(或好)方法是什么?

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

正如siritinga已经指出的那样,地图的元素没有排序,因此您无法对其进行排序.

您可以做的是创建切片并使用排序包对元素进行排序:

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,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("%+vn",*d)
    }
}

输出:

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

Playground

编辑

更新了示例以使用指针并包含一个映射,以便您可以执行查找并使用切片进行排序.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读