gpt4 book ai didi

rust - len() 和 capacity() 有什么区别?

转载 作者:行者123 更新时间:2023-11-29 08:23:21 28 4
gpt4 key购买 nike

当我创建一个向量时,长度和容量是相同的。这些方法有什么区别?

fn main() {
let vec = vec![1, 2, 3, 4, 5];
println!("Length: {}", vec.len()); // Length: 5
println!("Capacity: {}", vec.capacity()); // Capacity: 5
}

最佳答案

Growable vectors为将来的添加保留空间,因此分配的空间(容量)和实际使用的空间(长度)之间存在差异。

这在 standard library's documentation for Vec 中有解释:

The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector's length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.

For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector's length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use Vec::with_capacity whenever possible to specify how big the vector is expected to get.

关于rust - len() 和 capacity() 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54889521/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com