当前位置: 代码迷 >> 综合 >> vector-reserve
  详细解决方案

vector-reserve

热度:25   发布时间:2023-12-15 04:30:07.0

// 2018/04/18 12:13:12
// vector-reserve/*size是当前vector容器真实占用的大小,也就是容器当前拥有多少个容器。capacity是指在发生realloc前能允许的最大元素数,即预分配的内存空间。当然,这两个属性分别对应两个方法:resize()和reserve()。使用resize(),容器内的对象内存空间是真正存在的。使用reserve()仅仅只是修改了capacity的值,容器内的对象并没有真实的内存空间(空间是"野"的)。此时切记使用[]操作符访问容器内的对象,很可能出现数组越界的问题。 */
#include <iostream>
#include <vector>using namespace std;int main(){vector<int> v(5, 0);  // 5 elements each-value 0/*- - - - - - - - - - - - */cout << "Size of v = " << v.size() << endl;cout << "Capacity v = " << v.capacity() << endl;cout << "Value of each elements is ";for (int i = 0; i < v.size(); i++){cout << v[i] << " ";}cout << endl;v[0] = 5;       // new value for first elementv[1] = 8;v.push_back(3);  // creates new (6th) elements of vectorv.push_back(7);  // automatically increases sizecout << endl;    // capacity of vector vcout << "Size of v = " << v.size() << endl;cout << "Capacity v = " << v.capacity() << endl;cout << "Value of each elements is ";for (int i = 0; i < v.size(); i++){cout << v[i] << " ";}cout << endl;v.reserve(100);     // increase capacity to 100cout << "Size of v1_int = " << v.size() << endl;cout << "Capacity v1_int = " << v.capacity() << endl;int size = sizeof(v); // how big is vector itselfcout << "sizeof v =" << size << endl;return 0;
}/* OUTPUT:Size of v = 5Capacity v = 5Value of each elements is 0 0 0 0 0Size of v = 7Capacity v = 7Value of each elements is 5 8 0 0 0 3 7Size of v1_int = 7Capacity v1_int = 100sizeof v =16 */ 
  相关解决方案