我有一个自定义结构的向量和一个属性列表,用于按优先级降序对该向量进行排序。例如:
struct TheStruct {
artist: String,
title: String,
date: String,
}
let order_vec: Vec<String> = vec!["artist".to_string(),"title".to_string(),"date".to_string()];
let item_vec: Vec<TheStruct> = Vec::new();
我希望向量按 order_vec
给定的顺序排序。在此示例中,它应首先按艺术家姓名排序,当这相等时应按标题排序。我不想对这个顺序进行硬编码,因为 order_vec
是动态变化的。
我发现 Vec::sort_by
有一个比较函数。我如何动态生成该函数?有没有不用 sort_by
就可以做到这一点的方法?
最佳答案
How do I dynamically generate that function
你不知道。您有一个内部具有动态行为的特定闭包。
在这里,我们有一个要应用的排序列表。当我们需要比较两个项目时,我们遍历列表。我们使用 Ordering::then_with
仅在上一个比较为 Equal
时应用比较:
use std::cmp::Ordering;
#[derive(Debug, Copy, Clone)]
enum Field {
Artist,
Title,
Date,
}
struct TheStruct {
artist: String,
title: String,
date: String,
}
fn main() {
let mut items: Vec<TheStruct> = vec![];
use Field::*;
let orders = vec![Artist, Title];
items.sort_by(|a, b| {
orders.iter().fold(Ordering::Equal, |acc, &field| {
acc.then_with(|| {
match field {
Artist => a.artist.cmp(&b.artist),
Title => a.title.cmp(&b.title),
Date => a.date.cmp(&b.date),
}
})
})
})
}
我为这些字段使用了一个枚举,因为我不想处理当其中一种是未知字段时该怎么做。
关于sorting - 使用动态改变其行为的比较器对向量进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46512227/