size()指 目前存在的元素數。 元素個數
capacity()指 容器能存儲 數據的個數 容器 容量
reserve()指定 容器 能存儲數據的個數
resize() 重新 指定 有效元素的個數 ,區別與reserve()指定 容量的大小
當創建空容器時, 容量(capacity)為 0;當用完時,增加原容量的 1/2 (各編譯器 可能存在差異 vs2010是這樣的,mingw則 增加原容量 )--適用如 vector這種 元素連續存儲的容器, 如為list則不同。
capacity 一般大於size的原因是為了避免 每次增加數據時都要重新分配內存,所以一般會 生成一個較大的空間,以便隨後的數據插入。
include <iostream> #include <vector> using namespace std; int main() { vector<int> ivec; cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; //添加10個元素 for(int i = 0; i < 10; ++i) { ivec.push_back(i); cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; } //將容量用完 while(ivec.size() != ivec.capacity()) ivec.push_back(0); //添加1個元素 cout<<"size = capacity. insert one element\n"; ivec.push_back(0); cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; ivec.reserve(100); cout<<"reserve capacity 100\n"; cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; //將容量用完 while(ivec.size() != ivec.capacity()) ivec.push_back(42); //添加1個元素 cout<<"size = capacity. insert one element\n"; ivec.push_back(0); cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; return 0; } #include <iostream> #include <vector> using namespace std; int main() { vector<int> ivec; cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; //添加10個元素 for(int i = 0; i < 10; ++i) { ivec.push_back(i); cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; } //將容量用完 while(ivec.size() != ivec.capacity()) ivec.push_back(0); //添加1個元素 cout<<"size = capacity. insert one element\n"; ivec.push_back(0); cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; ivec.reserve(100); cout<<"reserve capacity 100\n"; cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; //將容量用完 while(ivec.size() != ivec.capacity()) ivec.push_back(42); //添加1個元素 cout<<"size = capacity. insert one element\n"; ivec.push_back(0); cout<<"capacity:"<<ivec.capacity()<<" size:"<<ivec.size()<<endl; return 0; }
mingw 結果:
vs2010結果
string 類有同樣的函數,但string增加容量時,每次增加16的倍數
string str;
str.reserve(50); //要求容量 最小為 50
cout<<str.capacity(); // 輸出為63 16*4-1