Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a vector of zeros for a specific size

Tags:

rust

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); } 
like image 985
elleciel Avatar asked Apr 09 '15 04:04

elleciel


People also ask

How do you create a vector of zeros?

R : Create a vector of zeros using the numeric() function In R, the numeric() function creates objects of numeric type. The numeric() function will create a double-precision vector of the specified length in the argument with all elements value equal to zero.

How do I create a vector of a specific length in R?

To create a vector of specified data type and length in R we make use of function vector(). vector() function is also used to create empty vector.

How do you make a vector of 1 in R?

Using rep() function It creates a vector with the value x repeated t times. To create a vector of ones, pass 1 as the first argument to the rep() function and the length of the vector as its second argument.


1 Answers

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

like image 79
anderspitman Avatar answered Sep 28 '22 04:09

anderspitman