能够动态增长,当 size()=capacity() 触发,容量在以前基础翻倍,但是效率不高,一般提前预设 reverse()
#include<vector>
#include <iostream>
#include<vector>
using namespace std;
void print(vector<int> &vec)
{
cout<<"vec.size="<<vec.size()<<endl;
cout<<"vec.capacity="<<vec.capacity()<<endl;
}
int main()
{
vector<int> vec;
//具有动态增长功能,不预先开辟,初试大小为0,一旦往容器里面放东西,开始动态申请空间,当大小和容量相等时,触发容器申请空间,空间增长到当前大小的2倍
vec.reserve(4); //表示预先开辟大小为4的空间
print(vec);
vec.push_back(1);
print(vec);
vec.push_back(2);
print(vec);
vec.push_back(3);
print(vec);
vec.push_back(4);
print(vec);
vec.push_back(5);
print(vec);
vec.push_back(6);
print(vec);
for(int i=0;i<vec.size();i++)
{
cout<<vec[i]<<" ";
}
cout<<endl;
vector<int>::iterator vp;
for(vp=vec.begin();vp!=vec.end();vp++)
{
cout<<*vp<<" ";
}
cout<<endl;
}
|
//不预先开辟空间 //预先开辟空间4 |
#include<iostream>
#include<vector>
using namespace std;
void printNUM(vector<int> &ver)
{
cout<<"vector.size:"<<ver.size()<<endl;
cout<<"vector.capacity:"<<ver.capacity()<<endl;
}
//size()返回的是容器中push_back()的元素个数
//capacity()返回的是容器的空间(最多放多少个元素)
int main(void)
{
vector<int> ver;
//预先开辟空间
ver.reserve(10);
printNUM(ver);
ver.push_back(1);
printNUM(ver); //vector当size和capacity一样大的时候,capacity会翻倍扩充
ver.push_back(2);
printNUM(ver);
ver.push_back(3);
printNUM(ver);
ver.push_back(4);
printNUM(ver);
ver.push_back(5);
printNUM(ver);
ver.push_back(6);
printNUM(ver);
ver.push_back(7);
printNUM(ver);
ver.push_back(8);
printNUM(ver);
ver.push_back(9);
printNUM(ver);
for(int i=0;i!=ver.size();++i)
{
cout<<ver[i]<<" ";
}
cout<<endl;
vector<int>::iterator it; //迭代器
for(it=ver.begin();it!=ver.end();++it)
{
cout<<*it<<" ";
}
cout<<endl;
}
|