Reputation: 309
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?
Upvotes: 8
Views: 4020
Reputation: 71595
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
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<_>>();
Upvotes: 16