下午好。我有 2 个长度不等的向量
let names = vec!["Marie", "Jana", "Eva", "Anna"];
let surnames = vec!["Novakova", "Svobodova", "Novotna", "Dvorakova", "Kralova"];
如何查看名字和姓氏的所有可能组合?
我想得到的条件3向量:
let gen_full_name = vec!["Marie Novakova", "Jana Novakova", "Eva Novotna", "Anna Novotna", "Jana Novakova", ...];
let names = vec!["Marie", "Jana", "Eva", "Anna"];
let surnames = vec!["Novakova", "Svobodova", "Novotna", "Dvorakova", "Kralova"];
let mut full_names = Vec::with_capacity(names.len() * surnames.len());
for name in &names {
for surname in &surnames {
full_names.push(format!("{} {}", name, surname));
}
}
println!("{:?}", full_names);
无需不必要的分配。
这是一种使用函数式编程风格的方法。
let names = vec!["Marie", "Jana", "Eva", "Anna"];
let surnames = vec!["Novakova", "Svobodova", "Novotna", "Dvorakova", "Kralova"];
let combinations = names.iter()
// First, map all firstnames `n` to a list containing
// a combination of this firstname with every lastname
.map(|&n|
// For every firstname, the surnames are iterated
surnames.iter()
// For every surname iteration, the firstname and lastname are
// combined into a single string
.map(move |&s| format!("{} {}", &n, &s))
.collect::<Vec<_>>())
// the lists are seperated for every first name so far.
// last but not least they must be joined together.
.fold(vec![], |mut v, mut dat| { v.append(&mut dat); v} );