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

Cof*_*lan 5 rust

我有一个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;
}
Run Code Online (Sandbox Code Playgroud)

这是我到目前为止所得到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
};
Run Code Online (Sandbox Code Playgroud)

这个感觉有点复杂。有没有更简单的方法来做到这一点?

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

Frx*_*rem 8

您应该使用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
}
Run Code Online (Sandbox Code Playgroud)

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

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

(铁锈游乐场链接)