golang中对map操作类

来源:互联网 发布:阿里数据库oceanbase 编辑:程序博客网 时间:2024/06/05 08:47
                                                                                                     
  1. package beeku  

  2.   

  3. import (  

  4.     "sort"  

  5. )  

  6.   

  7. type MapSorter struct {  

  8.     Keys []string  

  9.     Vals []string  

  10. }  

  11.   

  12. func NewMapSorter(m map[string]string) *MapSorter {  

  13.     ms := &MapSorter{  

  14.         Keys: make([]string, 0, len(m)),  

  15.         Vals: make([]string, 0, len(m)),  

  16.     }  

  17.     for k, v := range m {  

  18.         ms.Keys = append(ms.Keys, k)  

  19.         ms.Vals = append(ms.Vals, v)  

  20.     }  

  21.     return ms  

  22. }  

  23.   

  24. func (ms *MapSorter) Sort() {  

  25.     sort.Sort(ms)  

  26. }  

  27.   

  28. func (ms *MapSorter) Len() int           { return len(ms.Keys) }  

  29. func (ms *MapSorter) Less(i, j int) bool { return ms.Keys[i] < ms.Keys[j] }  

  30. func (ms *MapSorter) Swap(i, j int) {  

  31.     ms.Vals[i], ms.Vals[j] = ms.Vals[j], ms.Vals[i]  

  32.     ms.Keys[i], ms.Keys[j] = ms.Keys[j], ms.Keys[i]  

  33. }  





查看原文:http://www.zoues.com/2016/10/27/golang%e4%b8%ad%e5%af%b9map%e6%93%8d%e4%bd%9c%e7%b1%bb/
0 0
原创粉丝点击