Creating a vector of zeros for a specific size

后端 未结 4 1642
挽巷
挽巷 2020-12-01 15:20

I\'d like to initialize a vector of zeros with a specific size that is determined at runtime.

In C, it would be like:



        
相关标签:
4条回答
  • 2020-12-01 15:54

    To initialize a vector of zeros (or any other constant value) of a given length, you can use the vec! macro:

    let len = 10;
    let zero_vec = vec![0; len];
    

    That said, your function worked for me after just a couple syntax fixes:

    fn zeros(size: u32) -> Vec<i32> {
        let mut zero_vec: Vec<i32> = Vec::with_capacity(size as usize);
        for i in 0..size {
            zero_vec.push(0);
        }
        return zero_vec;
    }
    

    uint no longer exists in Rust 1.0, size needed to be cast as usize, and the types for the vectors needed to match (changed let mut zero_vec: Vec<i64> to let mut zero_vec: Vec<i32>.

    0 讨论(0)
  • 2020-12-01 16:10

    You may use resize

    let mut v = Vec::new();
    let l = 42;
    v.resize(l, 0u32);
    
    0 讨论(0)
  • 2020-12-01 16:15

    You can also use the iter::repeat function, which I suppose is "more idiomatic" (and just looks nicer to me):

    use std::iter;
    
    fn zeros(size: usize) -> Vec<i32> {
        iter::repeat(0).take(size).collect()
    }
    
    0 讨论(0)
  • 2020-12-01 16:20

    Here is another way, much shorter. It works with Rust 1.0:

    fn zeros(size: u32) -> Vec<i32> {
        vec![0; size as usize]
    }
    
    fn main() {
        let vec = zeros(10);
        for i in vec.iter() {
            println!("{}", i)
        }
    }
    
    0 讨论(0)
提交回复
热议问题