map按key和按value排序

看一個題:
查找和排序
題目:輸入任意(用戶,成績)序列,可以獲得成績從高到低或從低到高的排列,相同成績
都按先錄入排列在前的規(guī)則處理。
例示:
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、保證排序的穩(wěn)定性

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,實現(xiàn)sort接口,就可以調(diào)用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是遞增排序,如果要實現(xiàn)遞減排序,用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 排序的穩(wěn)定性


//sort不保證排序的穩(wěn)定性(兩個相同的值,排序之后相對位置不變),排序的穩(wěn)定性由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排序、遞增和遞減、排序的穩(wěn)定性

//看一下本題的C++解法,C++ sort的第三個參數(shù)用來定義排序方法,即按key還是value排序,遞增還是遞減排序等,stable_sort用來保證排序的穩(wěn)定性,主要思路與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);   //穩(wěn)定排序
        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;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容