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

如何实现Rust Vector中元素第n次出现的索引获取函数

获取向量中元素第n次出现的索引函数实现

需求说明

需要实现函数 fn get_index(vec: Vec<T>, occurrence: usize, value: T),用于查找向量中目标值第occurrence次出现时对应的索引。例如在向量 let v: Vec<u8> = vec![3, 2, 1, 4, 2, 1]; 中,调用 get_index(v, 2, 1) 应返回 5。

实现方案

这里提供两种实现方式,分别适用于不同场景:

方式一:找不到时直接 panic(符合示例断言要求)

use std::cmp::PartialEq;

fn get_index<T: PartialEq>(vec: Vec<T>, occurrence: usize, value: T) -> usize {
    vec.into_iter()
        .enumerate()
        .filter(|(_, val)| *val == value)
        .nth(occurrence - 1)
        .expect("指定的出现次数超出元素实际出现次数")
        .0
}

// 测试示例
fn main() {
    let v: Vec<u8> = vec![3, 2, 1, 4, 2, 1];
    assert_eq!(get_index(v, 2, 1), 5);
}

方式二:返回 Option(更安全的错误处理)

如果需要避免panic,推荐使用这种方式,让调用者自行处理元素不存在指定次数的情况:

use std::cmp::PartialEq;

fn get_index<T: PartialEq>(vec: Vec<T>, occurrence: usize, value: T) -> Option<usize> {
    vec.into_iter()
        .enumerate()
        .filter(|(_, val)| *val == value)
        .nth(occurrence - 1)
        .map(|(idx, _)| idx)
}

// 测试示例
fn main() {
    let v: Vec<u8> = vec![3, 2, 1, 4, 2, 1];
    assert_eq!(get_index(v, 2, 1), Some(5));
}

代码说明

  • 泛型 T: PartialEq 确保函数支持所有可比较相等的类型;
  • enumerate() 方法同时获取元素的索引和值;
  • filter() 筛选出与目标值匹配的元素;
  • nth(occurrence - 1) 取第 occurrence-1 个匹配元素(因为nth从0开始计数);
  • 方式一用expect在匹配不足时抛出 panic,方式二用map提取索引并返回Option。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:01:14