知识卡片
向量容量决定何时扩容
Vec<T> 的长度是实际元素数,容量是在现有缓冲区能容纳的总元素数。向量达到容量后再追加,一般需要分配更大的空间、移动现有元素并交还旧缓冲区。Vec::with_capacity(2) 创建的是长度 0 的向量,却可在至少追加两项前避免扩容。追加第三项仍能成功,新的具体容量无须作为程序假设。
关联阅读:[[向量的创建与遍历]]。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- Fundamental Types 动态向量的构造、容量与更新 · 查看原书依据
Just as a vector’s len method returns the number of elements it contains now, its capacity method returns the number of elements it could hold
参考来源
- 位置:《Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)》第02章《Fundamental Types》|动态向量的构造、容量与更新,来源项目 `book-source`,`extracted/Programming Rust Fast, Safe Systems Development, 3rd ed. (First Early Release)/_epub-src/OEBPS/ch02.xhtml#vectors`
- 结论依据:原文描述指针、容量和长度三个组成值,并用 with_capacity 的插入例区分初始预留与后续扩容保证。
- 原始内容:Just as a vector’s len method returns the number of elements it contains now, its capacity method returns the number of elements it could hold