doufang8965 2019-05-27 10:08
浏览 38
已采纳

如何检查自定义结构的片段是否已排序?

We can check if a slice of strings is sorted with

var slice = []string { "a", "b }

sort.StringsAreSorted(slice)

But what about when you have struct and you want to know if a slice of that struct is sorted by a certain member?

type Person struct {
  Name string
  LastName string
}

var p = []Person{ {"John", "Smith" }, { "Ben", "Smith" } }

sort.StringsAreSorted(p???)
  • 写回答

1条回答 默认 最新

  • doulao1966 2019-05-27 10:12
    关注

    If your type implements sort.Interface, simply use the sort.IsSorted() function.

    If not, you may use sort.SliceIsSorted(), passing a less() function which decides / specifies the order(ing):

    sortedByName := sort.SliceIsSorted(p, func(i, j int) bool {
        return p[i].Name < p[j].Name
    })
    fmt.Println("Sorted by name:", sortedByName)
    
    sortedByLastName := sort.SliceIsSorted(p, func(i, j int) bool {
        return p[i].LastName < p[j].LastName
    })
    fmt.Println("Sorted by last name:", sortedByLastName)
    

    This will output (try it on the Go Playground):

    Sorted by name: false
    Sorted by last name: true
    

    If you look into the implementation of these functions, they use a simple loop to iterate over the elements and tell if the ones being next to each other does not violate the ordering (less() function). You may just as easily use a for loop too.

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

报告相同问题?

悬赏问题

  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器