Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get all the indexes that fulfill a condition in a vector

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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<_>>();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading