//下面这个程序很有意思,看看发现到第二次的时候svec里面不是1000个元素,这实际上是resize()函数在作怪!但是最后一步中的capacity如何为3000多的我自己也不太清//楚,如果有知道的可以给我留言:
#include <vector>
#include <string>
#include <iostream>
using namespace std;
int main()
{
vector<string> svec;
svec.reserve(1024);
int n=0;
while(n++<256)
{
string tmp;
svec.push_back(tmp);
}
cout<<"the last size : "<<svec.size()<<endl;
cout<<"the capasity before resize : "<<svec.capacity()<<endl;
svec.resize(svec.size()+svec.size()/2);
cout<<"after resize of the svec:"<<svec.size()<<endl;
cout<<"after read words, capacity : "<<svec.capacity()<<endl;
cout<<endl;
while(n++<1000)
{
string tmp;
svec.push_back(tmp);
}
cout<<"n= "<<n<<endl;
cout<<"the last size : "<<svec.size()<<endl;
cout<<"the capasity before resize : "<<svec.capacity()<<endl;
svec.resize(svec.size()+svec.size()/2);
cout<<"after resize of the svec:"<<svec.size()<<endl;
cout<<"after read words, capacity : "<<svec.capacity()<<endl;
cout<<endl;
while(n++<1048)
{
string tmp;
svec.push_back(tmp);
}
cout<<"the last size : "<<svec.size()<<endl;
cout<<"the capasity before resize : "<<svec.capacity()<<endl;
svec.resize(svec.size()+svec.size()/2);
cout<<"after resize of the svec:"<<svec.size()<<endl;
cout<<"after read words, capacity : "<<svec.capacity()<<endl; //最后这一步的capacity()为什么不是4096???
}
STL中的resize函数与capacity函数
最新推荐文章于 2023-11-02 14:22:02 发布
本文深入探讨了C++中vector容器的resize函数在不同情况下的行为变化,特别是通过循环推动生成字符串列表并观察其大小和容量的变化过程。重点在于理解resize函数如何影响容器的内存分配,并解释在特定操作后容器容量未能达到预期值的原因。

2037

被折叠的 条评论
为什么被折叠?



