2017-09-13 16 views
0
type Item struct { 
    Y int 
    X int 
    otherProp int 
} 

私は、上記のような構造体のスライスを持っています。どのように私は、SQL文ORDER BY X,YのようにYの値によって最初にしてX値によってスライスitem []Itemを並べ替えるのですか?goスライスを複数の値でソートするにはどうすればよいですか?

私は、あなたが行く1.8以降sort.Slice()を使用することができていることがわかりますが、スライスの上に数回ループすることなく、これを解決するための簡単な方法は何ですか?

+6

その後、Yの値をXを比較します。これを行うのに問題がある場所の例を表示できますか? ( 'sort.Slice'あなたはいつもあまりにも標準' sort.Sort'でこれを行うことができ、必要とされていません。) – JimB

+4

は、パッケージでも一般的なケースでそれを行う方法の例が含まれます。https:// golangを。 org/pkg/sort /#example__sortMultiKeysです。代わりに、2回ソートすることもできます。最初はYで、次に安定した(!)をXで実行します。 – Volker

+0

予想される動作の例を挙げることはできますか? – tgogos

答えて

0

ここから最初の例を次に示します。Xが等しく、もしそうなら、私はその後、YをチェックするとPackage sort、私は私がチェックLess()関数の内部次...

を書きました。

playground demo

package main 

import (
    "fmt" 
    "sort" 
) 

type Item struct { 
    X int 
    Y int 
    otherProp int 
} 

func (i Item) String() string { 
    return fmt.Sprintf("X: %d, Y: %d, otherProp: %d\n", i.X, i.Y, i.otherProp) 
} 

// ByX implements sort.Interface for []Item based on 
// the X field. 
type ByX []Item 

func (o ByX) Len() int   { return len(o) } 
func (o ByX) Swap(i, j int)  { o[i], o[j] = o[j], o[i] } 
func (o ByX) Less(i, j int) bool { 
    if o[i].X == o[j].X { 
     return o[i].Y < o[j].Y 
    } else { 
     return o[i].X < o[j].X 
    } 
} 

func main() { 
    items := []Item{ 
     {1,2,3}, 
     {5,2,3}, 
     {3,2,3}, 
     {9,2,3}, 
     {1,1,3}, 
     {1,0,3}, 
    } 

    fmt.Println(items) 
    sort.Sort(ByX(items)) 
    fmt.Println(items) 

} 

出力:

[X: 1, Y: 2, otherProp: 3 
X: 5, Y: 2, otherProp: 3 
X: 3, Y: 2, otherProp: 3 
X: 9, Y: 2, otherProp: 3 
X: 1, Y: 1, otherProp: 3 
X: 1, Y: 0, otherProp: 3 
] 
[X: 1, Y: 0, otherProp: 3 
X: 1, Y: 1, otherProp: 3 
X: 1, Y: 2, otherProp: 3 
X: 3, Y: 2, otherProp: 3 
X: 5, Y: 2, otherProp: 3 
X: 9, Y: 2, otherProp: 3 
] 
1

[...]スライスの上に数回ループすることなく、これを解決するための簡単な方法は何ですか?

いいえ。比較ベースの並べ替えでは、基本的に常に少なくとも1回はスライスを繰り返します。しかし、心配しないでください:sort.Sliceは多すぎる仕事をしません。

あなたの質問は何ですか?

関連する問題