/* 結論:
vector的存在可以使開發者不必關心內存的申請和釋放。但是,vector背後的內存分配是按照2的倍數分配內存的。當當前容量對插入元素不夠時,分配一塊新的內存,這塊內存的容量是原vector容量的2倍大小,然後復制舊內存,釋放舊內存,可能多次涉及拷貝構造函數和析構函數,而這也正是vector的劣勢所在。*/
在使用cocos2d-x引擎的時候,多次調用cclayer、ccsprite的析構函數,程序會崩掉。
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> iVec;
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //1個元素, 容器容量為1
iVec.push_back(1);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //2個元素, 容器容量為2
iVec.push_back(2);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //3個元素, 容器容量為4
iVec.push_back(3);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //4個元素, 容器容量為4
iVec.push_back(4);
iVec.push_back(5);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //5個元素, 容器容量為8
iVec.push_back(6);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //6個元素, 容器容量為8
iVec.push_back(7);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //7個元素, 容器容量為8
iVec.push_back(8);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //8個元素, 容器容量為8
iVec.push_back(9);
cout << "size: " << iVec.size() << endl;
cout << "capacity " << iVec.capacity() << endl << endl; //9個元素, 容器容量為16
/* 結論:
vector的存在可以使開發者不必關心內存的申請和釋放。但是,vector背後的內存分配是按照2的倍數分配內存的。當當前容量對插入元素不夠時,分配一塊新的內存,這塊內存的容量是原vector容量的2倍大小,然後復制舊內存,釋放舊內存,可能多次涉及拷貝構造函數和析構函數,而這也正是vector的劣勢所在。*/
return 0;
}