创建特定大小的零向量 [英] Creating a vector of zeros for a specific size
问题描述
我想用在运行时确定的特定大小初始化一个零向量.
I'd like to initialize a vector of zeros with a specific size that is determined at runtime.
在 C 中,它会是这样的:
In C, it would be like:
int main(void)
{
uint size = get_uchar();
int A[size][size];
memset(A, 0, size*size*sizeof(int));
}
这是我尝试用 Rust 编写的辅助函数,但我认为切片语法 0..size
冒犯了编译器.此外,它看起来比 C 版本更冗长.有没有更惯用的方法来做到这一点?
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;
}
我发誓旧文档曾经解释过 from_elem()
方法 here 并且没有 [0 的任何排列;大小]
符号似乎有效
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);
}
推荐答案
要初始化给定长度的零向量(或任何其他常量值),您可以使用 vec!
宏:
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
在 Rust 1.0 中不再存在,size
需要转换为 usize
,并且需要匹配的向量类型(将 let mut zero_vec: Vec
更改为 let mut zero_vec: 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>
.
这篇关于创建特定大小的零向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!