Vector creation and VEC! Macros contain different capacities

I have a vectormatrix_ a. It contains three vectors and is initialized with VEC! Macro

Because VEC:: with_ Capacity (DIM), each vector should have a capacity of 3, but only the last vector has a capacity of 3 The capacity of the other vectors is 0

Can anyone explain why?

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());
    }
}

Output:

Capacity of vector: 0
Capacity of vector: 0
Capacity of vector: 3

Solution

According to documentation, VEC! Defined as:

macro_rules! vec {
    ( $elem : expr ; $n : expr ) => (
        $crate:: vec:: from_elem ( $elem,$n )
    );
    ( $( $x : expr ),* ) => (
        < [ _ ] > :: into_vec (
            $crate:: @R_632_2419@ed:: @R_632_2419@:: new ( [ $( $x ),* ] )
        )
    );
    ( $( $x : expr,) * ) => ( vec ! [ $( $x ),* ] )
}

In your case, this means:

vec![Vec::with_capacity(dim); dim]

Extend to:

std::vec::from_elem(Vec::with_capacity(dim),dim)

Vec :: from_ The definition of elem is hidden in the document, but can be 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
    }
}

And this mysterious heart solves:

>The element is cloned n – 1 times, for the first n - 1 element of the vector, and then moved to the nth time slot Cloning a vector cannot clone its capacity, only its elements

Therefore, your results are exactly as expected, if not as expected

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>