snippetrustCritical
How to iterate a Vec<T> with the indexed position?
Viewed 0 times
withhowtheiteratepositionvecindexed
Problem
I need to iterate a
I need something like this:
Vec including the position for each iterated element. I'm sure this is already in the API but I cannot see it. I need something like this:
fn main() {
let v = vec![1; 10];
for (pos, e) in v.iter() {
// do something here
}
}Solution
You can use the
Playground
Iterator::enumerate method:fn main() {
let v = vec![1; 10];
for (pos, e) in v.iter().enumerate() {
println!("Element at position {}: {:?}", pos, e);
}
}Playground
Code Snippets
fn main() {
let v = vec![1; 10];
for (pos, e) in v.iter().enumerate() {
println!("Element at position {}: {:?}", pos, e);
}
}Context
Stack Overflow Q#28991050, score: 226
Revisions (0)
No revisions yet.