Creating a vector of zeros for a specific size

2019-01-18 17:24发布

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

In C, it would be like:

int main(void)
{
    uint size = get_uchar();
    int A[size][size];
    memset(A, 0, size*size*sizeof(int));
}

Here's the helper function that I tried writing in Rust, but I think the slicing syntax 0..size is offending the compiler. Besides, it looks more verbose than the C version. Is there a more idiomatic way to do this?

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

I swear that the old docs used to explain a from_elem() method here and none of the permutations of the [0 ; size] notation seem to work

I'd like to stick this into a substring search algorithm ultimately:

pub fn kmp(text: &str, pattern: &str) -> i64 {
    let mut shifts = zeros(pattern.len()+1);
}

标签: rust
4条回答
女痞
2楼-- · 2019-01-18 18:04

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()
}
查看更多
时光不老,我们不散
3楼-- · 2019-01-18 18:08

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)
    }
}
查看更多
Melony?
4楼-- · 2019-01-18 18:11

You may use resize

let mut v = Vec::new();
let l = 42;
v.resize(l, 0u32);
查看更多
叼着烟拽天下
5楼-- · 2019-01-18 18:15

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>.

查看更多
登录 后发表回答