LoginSignup
6
3

More than 1 year has passed since last update.

RustでVecを2つのキーでソートしたい

Last updated at Posted at 2022-03-27

使いたかったときにぱっと書けず悶々としたので共有します。
@Kogia_sima さんにコメントで教えていただきました!!!

vec.sort_by(
    |a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1))
);

ここからが下が元記事です(↑の方がエレガントです)

use std::cmp::Ordering;

// (中略)

let mut vec = vec![];
vec.push((1, 2));
vec.push((2, 3));
vec.push((2, 2));
vec.push((3, 1));
vec.sort_by(|a, b| match a.0.cmp(&b.0) {
    Ordering::Equal => a.1.cmp(&b.1),
    other => other, // ここの変数名はお好みで。
});
println!("{:?}", vec); // [(1, 2), (2, 2), (2, 3), (3, 1)]

ちょっとめんどい。

6
3
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3