鍍金池/ 問答/PHP  GO/ slice排序保留原先索引

slice排序保留原先索引

a:=[]int{2,1,3}
排序結(jié)果是[1,2,3]索引重置0,1,2如何在排序的時候保留原先的索引1,0,2

回答
編輯回答
尕筱澄

同意Cedrus.

package main

import (
    "fmt"
    "sort"
)

func main() {
    a := []int{2, 1, 3}

    m := make(map[int]int, len(a))
    for i, v := range a {
        m[v] = i
    }

    sort.Ints(a)
    for _, v := range a {
        fmt.Printf("%d's old index is %d\n", v, m[v])
    }
}
2017年8月9日 02:00
編輯回答
舊城人

程序不是這么設計的。既然想關了兩個字段,為何不用map

type food struct{
    typ int
    price int
}
foods := make(map[int]food,0)
2017年10月1日 12:36