vector :: reserve()函数以及C ++ STL中的示例
C++vector::reserve()函数
vector::reserve()是“vector”头的库函数,用于请求矢量分配中的更改。请参阅示例以详细了解。
注意:要使用向量,请包含<vector>标头。
vector::reserve()函数的语法
vector::reserve(n);
参数:intn–接受n作为参数,其中n是输入容量。
返回值:void–在有效请求的情况下不返回任何内容。但是,如果请求的容量大于向量的最大大小(vector::max_size),则会引发length_error异常。
示例:情况1:(不带reserve()
)
vector<int> arr1; //通常的动态分配 size = arr1.capacity(); cout << "arr1 growing with usual dynamic allocation:\n"; for (int i = 0; i < 50; ++i) { arr1.push_back(i); if (size != arr1.capacity()) { size = arr1.capacity(); cout << "capacity changed to : " << size << '\n'; } }
在这种情况下,我们没有使用reserve,因此增长是按动态分配进行的,增长了两倍。像1,2,4,8,8,16,32,64,128…..so直到max_size。
示例:案例2:(带有reserve()
)
vector<int> arr2; //使用reserve size = arr2.capacity(); arr2.reserve(50); //使用reserve函数 cout << "arr2 growing with using reverse:\n"; for (int i = 0; i < 50; ++i) { arr2.push_back(i); if (size != arr2.capacity()) { size = arr2.capacity(); cout << "capacity changed to: " << size << '\n'; } }
在这种情况下,我们没有使用储备金,因此增长是按动态分配进行的,增长了两倍。像1,2,4,8,8,16,32,64,128…..so直到max_size。
C++程序演示vector::reserve()函数的示例
#include <iostream> #include <vector> using namespace std; int main(){ vector<int>::size_type size; vector<int> arr1; //通常的动态分配 size = arr1.capacity(); cout << "arr1 growing with usual dynamic allocation:\n"; for (int i = 0; i < 50; ++i) { arr1.push_back(i); if (size != arr1.capacity()) { size = arr1.capacity(); cout << "capacity changed to : " << size << '\n'; } } vector<int> arr2; //使用reserve size = arr2.capacity(); arr2.reserve(50); //使用reserve cout << "arr2 growing with using reverse:\n"; for (int i = 0; i < 50; ++i) { arr2.push_back(i); if (size != arr2.capacity()) { size = arr2.capacity(); cout << "capacity changed to: " << size << '\n'; } } return 0; }
输出结果
arr1 growing with usual dynamic allocation: capacity changed to : 1 capacity changed to : 2 capacity changed to : 4 capacity changed to : 8 capacity changed to : 16 capacity changed to : 32 capacity changed to : 64 arr2 growing with using reverse: capacity changed to: 50
参考:C++vector::reserve()