参考链接:C++中resize和reserve的区别
在使用STL时常常会把resize() 和 reserve()函数弄混,严重时会导致程序出现错误。
在解释这两个函数之前需要介绍容器的capacity和size之间的区别:
- capacity:指容器能够容纳的最大的元素的个数;
- size:指此时容器实际的元素个数。
就比如我有一个容量为300ml的水杯,里面现在装的水是200ml。意思是它最多能装300ml,只不过现在只是装了200ml。此时capacity为300, size为200。 所以reserve()是设置capacity的值,但是此时容器内还没有任何对象,不能通过下标访问。 而resize()是设置size的值,既分配了空间,也创建了对象(如果没有指定参数,系统调用默认构造函数),可以通过下标访问。
如下例子:
#include#include #include using namespace std; void demo_reserve(){ cout << " demo_reserve() " < v; v.reserve(10); cout << "v.capacity: " << v.capacity() < cout << p << endl; } } void demo_resize(){ cout << endl << " demo_resize() " < v; v.resize(10); cout << "v.capacity: " << v.capacity() < void{ cout < demo_reserve(); demo_resize(); return 0; }
输出:
demo_reserve() v.capacity: 10 v.size: 0 demo_resize() v.capacity: 10 v.size: 10 0 0 100 0 0 0 0 0 0 99



