Iterate over 2D Vector and store data in hash map

Vec is a 2D vector.

 for i in vec {
        if vec[i as usize][0] == 0 {
            map.insert (0, vec[i as usize][1]);
        } else {
            map.insert (1, vec[i as usize][1]);
        }
    }

Error: non-primitive cast: std::vec::Vec<i32> as usize (solution.rs)
|
8 | for j in vec[i as usize] {
| ^^^^^^^^^^
|
= note: an as expression can only be used to convert between primitive types. Consider using the From trait

When you make that kind of for loop, i is not the index. Try running this:

fn main() {
    let vec = vec![vec![0,2], vec![1,3]];
    
    for i in vec {
        println!("{:?}", i);
    }
}

click to run

I see. How do I get access to vectors within the vector?

You can use the value you're iterating directly. Here's an example:

use std::collections::HashMap;

fn main() {
    let vec = vec![vec![0,2], vec![1,3]];
    let mut map = HashMap::new();
    
    for v in &vec {
        if v[0] == 0 {
            map.insert(0, v[1]);
        } else {
            map.insert(1, v[1]);
        }
    }
    
    println!("{:?}", map);
}

playground

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.