在Rust中迭代Vec的替代元素的最佳方法是什么?

问题描述 投票:1回答:2

我有一个Vec<usize>,并希望迭代其中的所有偶数元素。基本上我想了解以下C ++代码的理想Rust等价物:

const std::vector<uint64_t> vector{1, 4, 9, 16, 25};

for (uint64_t index = 0; index < vector.size(); index += 2) {
    std::cout << vector[index] << std::endl;
}

这是我到目前为止用enumeratefilter得到的:

let vector: Vec<usize> = vec![1, 4, 9, 16, 25];

// Prints even-indexed numbers from the Vec.
type PredicateType = fn(&(usize, &usize)) -> bool;
let predicate: PredicateType = |&tuple| tuple.0 % 2 == 0;
for tuple in vector.iter().enumerate().filter(predicate) {
    println!("{:?}", tuple.1); // Prints 1, 9, and 25
};

这感觉有点复杂。有更简单的方法吗?

我还看到每次迭代都会构造一个元组,然后在每次交替迭代时丢弃。这似乎效率低下。有没有办法在不构建中间元组的情况下做到这一点?

rust
2个回答
0
投票

你应该使用step_by迭代器方法,它将逐步跳转:

let vector: Vec<usize> = vec![1, 4, 9, 16, 25];

// Prints even-indexed numbers from the Vec.
for item in vector.iter().step_by(2) {
    println!("{:?}", item); // Prints 1, 9, and 25
}

要从与0不同的索引开始,将其与skip结合使用:

// Prints odd-indexed numbers from the Vec.
for item in vector.iter().skip(1).step_by(2) {
    println!("{:?}", item); // Prints 4, 16
}

(Rust playground link)


0
投票

使用step_by

let data = vec![1,2,3,4,5,6,7];

for x in data.iter().step_by(2) {
    println!("{}", x)
}

输出:

1
3
5
7
© www.soinside.com 2019 - 2024. All rights reserved.