reserve函数
语法:
1 |
void reserve(size_type __n); |
reserve() 设置Vector最小的元素容纳数量
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
/** * @brief Attempt to preallocate enough memory for specified number of * elements. * @param n Number of elements required. * @throw std::length_error If @a n exceeds @c max_size(). * * This function attempts to reserve enough memory for the * %vector to hold the specified number of elements. If the * number requested is more than max_size(), length_error is * thrown. * * The advantage of this function is that if optimal code is a * necessity and the user can determine the number of elements * that will be required, the user can reserve the memory in * %advance, and thus prevent a possible reallocation of memory * and copying of %vector data. */ void reserve(size_type __n); |
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// 梁笔记 // https://zouzhongliang.com #include <iostream> #include <vector> using namespace std; int main() { vector<int> v1; vector<int> v2(3, 2); v1.push_back(1); v1.push_back(2); v1.push_back(3); v1.push_back(4); v1.push_back(5); cout<<"v1向量骨元素数:"<<v1.size()<<endl; cout<<"v2向量骨元素数:"<<v2.size()<<endl; cout<<"v1向量容量:"<<v1.capacity()<<endl; v1.reserve(10); v1.push_back(5); v1.push_back(5); v1.push_back(5); v1.push_back(5); v1.push_back(5); v1.push_back(5); cout<<"v1向量骨元素数:"<<v1.size()<<endl; cout<<"v1向量容量:"<<v1.capacity()<<endl; } |
测试结果:
1 2 3 4 5 |
v1向量骨元素数:5 v2向量骨元素数:3 v1向量容量:8 v1向量骨元素数:11 v1向量容量:20 |
注:设置reserve意义在于,向量内元素数量多少与向量容量之间的关系。reserve值设越大,向量容量越大,容量越大于向量尺寸(元素数量)。