# map按key和按value排序

zengfan · · 56187 次点击 · · 开始浏览

jack 70
peter 96
Tom 70
smith 67

peter 96
jack 70
Tom 70
smith 67

smith 67
Tom 70
jack 70
peter 96

1、按照value排序
2、可以递增排序和递减排序
3、保证排序的稳定性

# golang map按key排序

``````//golang的map不保证有序性，所以按key排序需要取出key，对key排序，再遍历输出value
package main

import (
"fmt"
"sort"
)

func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"

// To store the keys in slice in sorted order
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)

// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}

``````

# golang map按value排序

``````//要对golang map按照value进行排序，思路是直接不用map，用struct存放key和value，实现sort接口，就可以调用sort.Sort进行排序了。
// A data structure to hold a key/value pair.
type Pair struct {
Key   string
Value int
}

// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }

// A function to turn a map into a PairList, then sort and return it.
func sortMapByValue(m map[string]int) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
}
sort.Sort(p)
return p
}
``````

# golang map递增排序

``````//sort.Sort是递增排序，如果要实现递减排序，用sort.Reverse
package main

import (
"fmt"
"sort"
)

func main() {
a := []int{4,3,2,1,5,9,8,7,6}
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("After reversed: ", a)
}

``````

# golang map 排序的稳定性

``````
//sort不保证排序的稳定性（两个相同的值，排序之后相对位置不变），排序的稳定性由sort.Stable来保证。
package main

import (
"fmt"
"sort"
)

type person struct {
Name string
Age int
}

type personSlice []person

func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }

func main() {
a := personSlice {
{
Name: "AAA",
Age: 55,
},
{
Name: "BBB",
Age: 22,
},
{
Name: "CCC",
Age: 0,
},
{
Name: "DDD",
Age: 22,
},
{
Name: "EEE",
Age: 11,
},
}
sort.Stable(a)
fmt.Println(a)
}

``````

# C++按value排序、递增和递减、排序的稳定性

``````//看一下本题的C++解法，C++ sort的第三个参数用来定义排序方法，即按key还是value排序，递增还是递减排序等，stable_sort用来保证排序的稳定性，主要思路与golang解法相似，都是用struct封装key和value来代替map。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct student{
string name;
int score;
};
bool cmp0(const student &a, const student &b){
// 从高到低排序
return a.score > b.score;
}
bool cmp1(const student &a, const student &b){
// 从低到高排序
return a.score < b.score;
}
int main(){
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int N, type;
while(cin >> N >> type){
vector<student> stud(N);

for(int i = 0; i < N; i ++){
cin >> stud[i].name >> stud[i].score;
}
if(type == 0)
stable_sort(stud.begin(), stud.end(), cmp0);   //稳定排序
else
stable_sort(stud.begin(), stud.end(), cmp1);

for(int i = 0; i < N; i ++){
cout << stud[i].name << " " << stud[i].score << endl;
}
}

return 0;
}
``````

4 回复  |  直到 2019-05-15 11:14:55

• 请尽量让自己的回复能够对别人有帮助
• 支持 Markdown 格式, **粗体**、~~删除线~~、``单行代码``
• 支持 @ 本站用户；支持表情（输入 : 提示），见 Emoji cheat sheet
• 图片支持拖拽、截图粘贴等方式上传

jack 70
peter 96
Tom 70
smith 67

peter 96
jack 70
Tom 70
smith 67

smith 67
Tom 70
jack 70
peter 96

1、按照value排序
2、可以递增排序和递减排序
3、保证排序的稳定性

# golang map按key排序

``````//golang的map不保证有序性，所以按key排序需要取出key，对key排序，再遍历输出value
package main

import (
"fmt"
"sort"
)

func main() {
// To create a map as input
m := make(map[int]string)
m[1] = "a"
m[2] = "c"
m[0] = "b"

// To store the keys in slice in sorted order
var keys []int
for k := range m {
keys = append(keys, k)
}
sort.Ints(keys)

// To perform the opertion you want
for _, k := range keys {
fmt.Println("Key:", k, "Value:", m[k])
}
}

``````

# golang map按value排序

``````//要对golang map按照value进行排序，思路是直接不用map，用struct存放key和value，实现sort接口，就可以调用sort.Sort进行排序了。
// A data structure to hold a key/value pair.
type Pair struct {
Key   string
Value int
}

// A slice of Pairs that implements sort.Interface to sort by Value.
type PairList []Pair

func (p PairList) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p PairList) Len() int           { return len(p) }
func (p PairList) Less(i, j int) bool { return p[i].Value < p[j].Value }

// A function to turn a map into a PairList, then sort and return it.
func sortMapByValue(m map[string]int) PairList {
p := make(PairList, len(m))
i := 0
for k, v := range m {
p[i] = Pair{k, v}
}
sort.Sort(p)
return p
}
``````

# golang map递增排序

``````//sort.Sort是递增排序，如果要实现递减排序，用sort.Reverse
package main

import (
"fmt"
"sort"
)

func main() {
a := []int{4,3,2,1,5,9,8,7,6}
sort.Sort(sort.Reverse(sort.IntSlice(a)))
fmt.Println("After reversed: ", a)
}

``````

# golang map 排序的稳定性

``````
//sort不保证排序的稳定性（两个相同的值，排序之后相对位置不变），排序的稳定性由sort.Stable来保证。
package main

import (
"fmt"
"sort"
)

type person struct {
Name string
Age int
}

type personSlice []person

func (s personSlice) Len() int { return len(s) }
func (s personSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
func (s personSlice) Less(i, j int) bool { return s[i].Age < s[j].Age }

func main() {
a := personSlice {
{
Name: "AAA",
Age: 55,
},
{
Name: "BBB",
Age: 22,
},
{
Name: "CCC",
Age: 0,
},
{
Name: "DDD",
Age: 22,
},
{
Name: "EEE",
Age: 11,
},
}
sort.Stable(a)
fmt.Println(a)
}

``````

# C++按value排序、递增和递减、排序的稳定性

``````//看一下本题的C++解法，C++ sort的第三个参数用来定义排序方法，即按key还是value排序，递增还是递减排序等，stable_sort用来保证排序的稳定性，主要思路与golang解法相似，都是用struct封装key和value来代替map。
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
struct student{
string name;
int score;
};
bool cmp0(const student &a, const student &b){
// 从高到低排序
return a.score > b.score;
}
bool cmp1(const student &a, const student &b){
// 从低到高排序
return a.score < b.score;
}
int main(){
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
int N, type;
while(cin >> N >> type){
vector<student> stud(N);

for(int i = 0; i < N; i ++){
cin >> stud[i].name >> stud[i].score;
}
if(type == 0)
stable_sort(stud.begin(), stud.end(), cmp0);   //稳定排序
else
stable_sort(stud.begin(), stud.end(), cmp1);

for(int i = 0; i < N; i ++){
cout << stud[i].name << " " << stud[i].score << endl;
}
}

return 0;
}
``````