zoukankan      html  css  js  c++  java
  • Go 通过结构体指定字段进行排序

    对结构体指定字段进行排序:
      对结构体指定字段进行排序: 
    
    package main
     
    import (
        "fmt"
        "sort"
    )
     
    // 对结构体指定字段进行排序
    type User struct {
        Name string `json:"name"` // `json:"xxx"`:在结构体和json字符串字段顺序不一致的情况下:unmarshal根据tag去寻找对应字段的内容
        Age  int    `json:"age"`
    }
     
    // type Users []User
    // func SortByAge(u Users) {
    func SortByAge(u []User) {
        fmt.Printf("源数据:%+v
    ", u)
     
        sort.Slice(u, func(i, j int) bool { // desc
            return u[i].Age > u[j].Age
        })
        fmt.Printf("按Age降序:%+v
    ", u)
     
        sort.Slice(u, func(i, j int) bool { // asc
            return u[i].Age < u[j].Age
        })
        fmt.Printf("按Age升序:%+v
    ", u)
    }
     
    func main() {
        // 初始化结构体对象数组:
        // 初始化方法1:
        // users := Users{
        //     {
        //         Name: "test1",
        //         Age:  22,
        //     },
        //     {
        //         Name: "test2",
        //         Age:  19,
        //     },
        //     {
        //         Name: "test3",
        //         Age:  25,
        //     },
        // }
     
        // 初始化方法2:
        var users []User
        var u User
        u.Name = "test1"
        u.Age = 22
        users = append(users, u)
        u.Name = "test2"
        u.Age = 20
        users = append(users, u)
        u.Name = "test3"
        u.Age = 26
        users = append(users, u)
     
        SortByAge(users)
    }
     
    // 输出:
    源数据:[{Name:test1 Age:22} {Name:test2 Age:20} {Name:test3 Age:26}]
    按Age降序:[{Name:test3 Age:26} {Name:test1 Age:22} {Name:test2 Age:20}]
    按Age升序:[{Name:test2 Age:20} {Name:test1 Age:22} {Name:test3 Age:26}]
     
    此外也可使用sort.Sort()方法,不过需要自己去实现 Len()、Swap()、Less()方法,参考:golang对自定义类型排序
    
    另外,通过借助“结构体指定字段进行排序”解了一道LeetCode 347题:传送门
  • 相关阅读:
    [题解] LuoguP1587 [NOI2016]循环之美
    [题解] LuoguP3705 [SDOI2017]新生舞会
    [题解] LuoguP3702 [SDOI2017]序列计数
    [题解] LuoguP6476 [NOI Online 2 提高组]涂色游戏
    [题解] LuoguP4240 毒瘤之神的考验
    [题解] LuoguP6156简单题
    [题解] LuoguP6055 [RC-02] GCD
    [题解] LuoguP5050 【模板】多项式多点求值
    AtCoder Grand Contest 028题解
    Codeforces Round #421 (Div. 1) 题解
  • 原文地址:https://www.cnblogs.com/cxy2020/p/14957218.html
Copyright © 2011-2022 走看看