咱们在使用一些容器类型时,若是事先能大致知道存储空间的大小,使用成员函数reserve能够有效减小容器从新分配内存的次数。 下面的代码从实际项目改编而来。
#include <iostream> #include <vector> int main() { std::vector<int> numbers; numbers.reserve(3); numbers[0]=10; numbers[1]=20; std::cout << "The size of numbers: " << numbers.size() << std::endl; std::cout << "The first elem of numbers: " << numbers[0] << std::endl; std::cout << "The second elem of numbers: " << numbers[1] << std::endl; return 0; }
上面程序使用clang++/g++ -std=c++17输出以下:ios
The size of numbers: 0
The first elem of numbers: 10
The second elem of numbers: 20
之因此出错能够归为两点:c++
capacity
和size
是两个概念,不可混淆capacity >= size
。代码中的的reserve
实际上改变capacity
,没有改变size
。要改变size
,能够使用push_back
等成员函数。operator[]
操做不进行边界检查。要求咱们不能违背C++的“惯用法”,不然编译器也帮不了咱们。std::vector::at
。补充一句:Rust的默认的operator[]
行为等价于C++的std::vector::at
,运行时会报错。编程
文章已同步到公众号,微信号: pltfan,二维码以下:微信