////////////////////////////////////////
// 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 element
v[1] = 8;
v.push_back(3); // creates new (6th) elements of vector
v.push_back(7); // automatically increases size
cout << endl; // capacity of vector v
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.reserve(100); // increase capacity to 100
cout << "Size of v1_int = " << v.size() << endl;
cout << "Capacity v1_int = " << v.capacity() << endl;
int size = sizeof(v); // how big is vector itself
cout << "sizeof v =" << size << endl;
return 0;
}
/*
OUTPUT:
Size of v = 5
Capacity v = 5
Value of each elements is 0 0 0 0 0
Size of v = 7
Capacity v = 7
Value of each elements is 5 8 0 0 0 3 7
Size of v1_int = 7
Capacity v1_int = 100
sizeof v =16
*/