How to iterate a Vec<T> with the indexed position?
Asked Answered
P

2

127

I need to iterate a 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
    }
}
Pd answered 11/3, 2015 at 15:40 Comment(0)
S
197

You can use the Iterator::enumerate method:

fn main() {
    let v = vec![1; 10];
    for (pos, e) in v.iter().enumerate() {
        println!("Element at position {}: {:?}", pos, e);
    }
}

Playground

Smoker answered 11/3, 2015 at 15:44 Comment(3)
@Shepmaster Is there also a way to do this and get the element directly instead of a reference to it?Crispa
@Crispa What is the difference between iter and into_iter?Quadruplet
if we call .next(), and then enumerate(), it don't keep track of the real indexCyclone
A
-1

Not maybe the Rust way but you can try something like:

let n: usize = your_vector.len();

for i in 1..n {
    print!("{}", your_vector[i])
}
Amalburga answered 3/5, 2024 at 20:4 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.