Get all the indexes that fulfill a condition in a vector
Asked Answered
C

1

7

I would like to know if it is possible to get all the indexes that fulfill a condition in a rust vector datatype. I know the trait operator provides a method to find the first element that does it:

let test=vec![1,0,0,1,1];
let index = test.iter().position(|&r| r == 1);
println!("{}",index) //0

However, I would be interested in obtaining all the indexes that are equal to 1 in the test vec.

let test=vec![1,0,0,1,1];
let indexes =  //Some Code
println!("{:?}",indexes) //0,3,4

What should I do?

Chiropractor answered 9/3, 2022 at 8:8 Comment(0)
O
16

Use enumerate():

let test = vec![1, 0, 0, 1, 1];
let indices = test
    .iter()
    .enumerate()
    .filter(|(_, &r)| r == 1)
    .map(|(index, _)| index)
    .collect::<Vec<_>>();
dbg!(indices); // 0, 3, 4

Playground.

You can also combine filter() and map(), although I think the former version is cleaner:

let indices = test
    .iter()
    .enumerate()
    .filter_map(|(index, &r)| if r == 1 { Some(index) } else { None })
    .collect::<Vec<_>>();

Or

let indices = test
    .iter()
    .enumerate()
    .filter_map(|(index, &r)| (r == 1).then(|| index))
    .collect::<Vec<_>>();
Ocelot answered 9/3, 2022 at 8:20 Comment(1)
You can return the index without a closure using then_some: test.iter().enumerate().filter_map(|(index, &r)| (r == 1).then_some(index)).collect::<Vec<_>>()Quite

© 2022 - 2024 — McMap. All rights reserved.