You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust中如何按索引筛选Vec向量元素 解决enumerate调用报错

报错根因

enumerate()是迭代器特征Iterator的内置方法,无法直接在Vec<f64>类型上调用,必须先将Vec转为迭代器才能使用链式迭代器适配器方法。

方案1:迭代器过滤生成新Vec(推荐)

你的筛选逻辑本身没有问题,只需要补上Vec转迭代器的调用即可,根据是否需要保留原Vec的所有权,可以选择两种写法:

  • 需要保留原Vec后续使用:调用iter()拿到元素的不可变引用,最终map时解引用取值
let x: Vec<f64> = (1..200)
    .map(|x| x as f64 / 200.0)
    .collect();

let y: Vec<f64> = x
    .iter()
    .enumerate()
    .filter(|&(i, _)| i % 7 == 0)
    .map(|(_, e)| *e)
    .collect();
  • 不需要保留原Vec:调用into_iter()直接拿走元素所有权,无需解引用,性能稍好
let x: Vec<f64> = (1..200)
    .map(|x| x as f64 / 200.0)
    .collect();

let y: Vec<f64> = x
    .into_iter()
    .enumerate()
    .filter(|&(i, _)| i % 7 == 0)
    .map(|(_, e)| e)
    .collect();
方案2:retain原地筛选

如果不需要保留原Vec的其他元素,也可以用retain方法原地修改Vec,通过手动维护索引计数器实现基于位置的筛选:

let mut x: Vec<f64> = (1..200)
    .map(|x| x as f64 / 200.0)
    .collect();

let mut idx = 0;
x.retain(|_| {
    let retain_flag = idx % 7 == 0;
    idx += 1;
    retain_flag
});

执行完成后,x内就只保留索引为0、7、14……的元素,不需要额外分配新Vec的内存。

内容的提问来源于stack exchange,提问作者ste_kwr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.01 22:54:37