10

Following my question, How to iterate a Vec with indexed position in Rust, now I need to zip two dynamic vectors with their indexed position.

Community
  • 1
  • 1
bitloner
  • 1,581
  • 5
  • 12
  • 13
  • 1
    Shepmaster, can you stop downvoting all my questions and editing them. I am not bothering to use SO for Rust anymore because of you. – bitloner Mar 12 '15 at 11:43
  • 1
    I'm sad to see you go, and I hope you reconsider. For what it's worth, I didn't downvote your question, and I've just upvoted it as it's not a *bad* question. However, I don't apologize for editing questions to try to improve them for future searchers. If you disagree with any of my edits, feel free to roll them back; I'm not going to start an edit war with anyone! – Shepmaster Mar 12 '15 at 12:41
  • 1
    @Shepmaster is keeping the SO-questions with [rust] tag clean. He's doing a great job at that. You should not feel offended if he edits your question, rather remember he thought it useful enough to want it to fit into the general look of Rust/SO questions. – oli_obk Mar 12 '15 at 14:34

2 Answers2

33

The enumerate function exists for all iterators. Using zip on two iterators a and b yields another iterator. Therefor you can also call enumerate on the resulting iterator.

fn main() {
    let a = vec![1; 10];
    let b = vec![2; 10];

    let it = a.iter().zip(b.iter());

    for (i, (x, y)) in it.enumerate() {
        println!("{}: ({}, {})", i, x, y);
    }
}
oli_obk
  • 28,729
  • 6
  • 82
  • 98
0
fn main() {
    let a = vec![1; 10];
    let b = vec![2; 10];

    for ((i,x),(j,y)) in a.iter().enumerate().zip(b.iter().enumerate()) {
        println!("(({},{}),({},{}))", i, x, j, y);
    }
}
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
bitloner
  • 1,581
  • 5
  • 12
  • 13
  • 2
    aren't `i` and `j` always the same and could therefor be merged? I'm thinking `a.iter().zip(b.iter()).enumerate()` – oli_obk Mar 12 '15 at 08:25
  • true! that's a much better solution. add it as an answer so you can have all the fame and glory of having a better answer ^^ – bitloner Mar 12 '15 at 11:41