1. 程式人生 > >vector中capacity,reserve

vector中capacity,reserve

vector<int> ivec;
cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//0,0
ivec.push_back(10);
cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//1,1
ivec.push_back(20);
cout << "大小:" << ivec.size() << ",容量"
<< ivec.capacity() << endl;//2,2 ivec.push_back(30); cout << "大小:" << ivec.size() << ",容量"<<ivec.capacity() << endl;//3,3 ivec.push_back(40); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//4,4 ivec.push_back(50); cout << "大小:"
<< ivec.size() << ",容量" << ivec.capacity() << endl;//5,5 ivec.push_back(60); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//6,6 ivec.push_back(70); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//7,9
ivec.push_back(80); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//8,9 ivec.push_back(40); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//9,9 ivec.push_back(40); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//10,13 ivec.push_back(1); ivec.push_back(1); ivec.push_back(1); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//13,13 ivec.push_back(1); cout << "大小:" << ivec.size() << ",容量" << ivec.capacity() << endl;//14,19

capacity() 和size()區別:
size()為容器實際元素的個數
capacity()為容器目前所能容納的最大元素個數,一旦容量不夠了,就會重新分配一段連續的比原有空間大的記憶體大小,將原來的元素拷貝到新的容器空間內,繼續新增,每一次容量的增長50%

reserve(n)
按需申請n個大小的容量,此時容量capacity就變為n