← 中文资源

简体中文版本

枚举收集全部匹配下标

position 找到首个匹配即停;enumerate 配 filter_map 收集全部匹配下标,rposition 从尾部反向扫描,同一谓词三种检索口径。

阅读英文原文

实现说明

枚举收集全部匹配下标可以归结为函数 main。

使用要点

  • 每一步打印都带着自己的标签:first position:、all positions:、last position:。

常见问题

运行「枚举收集全部匹配下标」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 first position:、all positions:、last position: 标签标明各步骤。

核心语句

let first = readings.iter().position(|&v| v == 12);
let last = readings.iter().rposition(|&v| v == 12);
.filter(|&(_, &v)| v > 10)
.map(|(i, _)| i)
.collect();

代码示例

fn main() {
    let readings = [12, 7, 12, 33, 12, 5];

    // position stops at the first hit
    let first = readings.iter().position(|&v| v == 12);
    println!("first position: {first:?}");

    // collect ALL matching positions: enumerate + filter_map keeps the index
    let all: Vec<usize> = readings
        .iter()
        .enumerate()
        .filter_map(|(i, &v)| (v == 12).then_some(i))
        .collect();
    println!("all positions: {all:?}");

    // rposition runs the same search from the back
    let last = readings.iter().rposition(|&v| v == 12);
    println!("last position: {last:?}");

    // the same enumerate pattern works for any predicate
    let hot: Vec<usize> = readings
        .iter()
        .enumerate()
        .filter(|&(_, &v)| v > 10)
        .map(|(i, _)| i)
        .collect();
    println!("hot positions: {hot:?}");
}