标签:
看图:
当创建空容器时, 容量(capacity)为 0;当用完时,增加原容量的 1/2 (各编译器 可能存在差异 vs2013是这样的,mingw则 增加原容量 )--适用如 vector这种 元素连续存储的容器, 如为list则不同。
capacity 一般大于size的原因是为了避免 每次增加数据时都要重新分配内存,所以一般会 生成一个较大的空间,以便随后的数据插入。
1 int main() 2 { 3 vector<int> ivec; 4 cout << "capacity:" << ivec.capacity() << " size:" << ivec.size() << endl; 5 //添加10个元素 6 for (int i = 0; i < 10; ++i) 7 { 8 ivec.push_back(i); 9 cout << "capacity:" << ivec.capacity() << " size:" << ivec.size() << endl; 10 } 11 //将容量用完 12 while (ivec.size() != ivec.capacity()) 13 ivec.push_back(0); 14 //添加1个元素 15 cout << "size = capacity. insert one element\n"; 16 ivec.push_back(0); 17 cout << "capacity:" << ivec.capacity() << " size:" << ivec.size() << endl; 18 19 ivec.reserve(100); 20 cout << "reserve capacity 100\n"; 21 cout << "capacity:" << ivec.capacity() << " size:" << ivec.size() << endl; 22 23 //将容量用完 24 while (ivec.size() != ivec.capacity()) 25 ivec.push_back(42); 26 //添加1个元素 27 cout << "size = capacity. insert one element\n"; 28 ivec.push_back(0); 29 cout << "capacity:" << ivec.capacity() << " size:" << ivec.size() << endl; 30 31 ivec.resize(50); 32 cout << "resize size 50\n"; 33 cout << "capacity:" << ivec.capacity() << " size:" << ivec.size() << endl; 34 getchar(); 35 return 0; 36 }
标签:
原文地址:http://www.cnblogs.com/firstcxj/p/4566666.html