是否有更直接,更易读的方法来完成以下任务:
fn main() {
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [7, 8, 9];
let iter = a.iter()
.zip(b.iter())
.zip(c.iter())
.map(|((x, y), z)| (x, y, z));
}
也就是说,如何从n个迭代构建一个迭代器,产生n元组?
答案 0 :(得分:30)
您可以使用crate itertools中的izip!()
宏,它为任意多个迭代器实现此目的:
#[macro_use]
extern crate itertools;
fn main() {
let a = [1, 2, 3];
let b = [4, 5, 6];
let c = [7, 8, 9];
// izip!() accepts iterators and/or values with IntoIterator.
for (x, y, z) in izip!(&a, &b, &c) {
}
}
您必须在Cargo.toml中添加对itertools的依赖,使用最新的版本。例如:
[dependencies]
itertools = "0.7"
答案 1 :(得分:2)
您还可以使用提供的.zip
来创建宏,
$ cat z.rs
macro_rules! zip {
($x: expr) => ($x);
($x: expr, $($y: expr), +) => (
$x.iter().zip(
zip!($($y), +))
)
}
fn main() {
let x = vec![1,2,3];
let y = vec![4,5,6];
let z = vec![7,8,9];
let zipped = zip!(x, y, z);
println!("{:?}", zipped);
for (a, (b, c)) in zipped {
println!("{} {} {}", a, b, c);
}
}
输出:
$ rustc z.rs && ./z
Zip { a: Iter([1, 2, 3]), b: Zip { a: Iter([4, 5, 6, 67]), b: IntoIter([7, 8, 9]), index: 0, len: 0 }, index: 0, len: 0 }
1 4 7
2 5 8
3 6 9
答案 2 :(得分:1)
我希望能够对任意长的向量执行此操作,因此我必须手动实现此操作:
void command_menu(){
string command = "default000",
command_upper;
bool incorrect_input = false;
do{
clear_replit();
default_display();
cout << "\nType 'commands' to see a list of options, or enter a command.\n";
if(command == "default000"){}
else{
cout << special_text("red","'");
cout << special_text("green", command) << special_text("red", "'");
cout << special_text("red", " is not a recognized command.\n");
}
getline(cin, command);
command_upper = string_toupper(command);
if(command_upper == "COMMANDS"){
list_of_commands();
}