我有一个vectormatrix_a,它包含3个向量,并用vec初始化!宏.
由于Vec :: with_capacity(dim),每个向量应该具有3的容量,但只有最后一个向量的容量为3.其他向量的容量为0.
有人可以解释为什么吗?
fn main() { let dim = 3; let matrix_a: Vec<Vec<i32>> = vec![Vec::with_capacity(dim); dim]; for vector in matrix_a{ println!("Capacity of vector: {}",vector.capacity()); } }
输出:
Capacity of vector: 0 Capacity of vector: 0 Capacity of vector: 3
解决方法
根据
documentation,vec!定义为:
macro_rules! vec { ( $elem : expr ; $n : expr ) => ( $crate:: vec:: from_elem ( $elem,$n ) ); ( $( $x : expr ),* ) => ( < [ _ ] > :: into_vec ( $crate:: Boxed:: Box:: new ( [ $( $x ),* ] ) ) ); ( $( $x : expr,) * ) => ( vec ! [ $( $x ),* ] ) }
在你的情况下,这意味着:
vec![Vec::with_capacity(dim); dim]
扩展到:
std::vec::from_elem(Vec::with_capacity(dim),dim)
Vec :: from_elem的定义隐藏在文档中,但可以是found in the source:
pub fn from_elem<T: Clone>(elem: T,n: usize) -> Vec<T> { unsafe { let mut v = Vec::with_capacity(n); let mut ptr = v.as_mut_ptr(); // Write all elements except the last one for i in 1..n { ptr::write(ptr,Clone::clone(&elem)); ptr = ptr.offset(1); v.set_len(i); // Increment the length in every step in case Clone::clone() panics } if n > 0 { // We can write the last element directly without cloning needlessly ptr::write(ptr,elem); v.set_len(n); } v } }
而这个神秘之心解决了:
>元素被克隆n – 1次,对于矢量的n-1个第一个元素,然后移动到第n个时隙.
克隆一个向量不能克隆其容量,只有其元素.
因此,您获得的结果与预期完全一致,如果不是预期的话.