容量和大小
函数原型:
代码语言:javascript复制#include<iostream>
using namespace std;
#include<vector>
//vector的容量和大小
void print(vector<int>& v)
{
for (vector<int>::iterator beg = v.begin(); beg != v.end(); beg )
{
cout << *beg <<" ";
}
cout << endl;
}
void test()
{
vector<int> v;
for (int i = 0; i < 6; i )
v.push_back(i);
if (v.empty())
{
cout << "容器v为空" << endl;
}
else {
cout << "容器v不为空" << endl;
cout << "容器v的容量为: " << v.capacity() << endl;
cout << "容器v的大小为:" << v.size() << endl;
}
//重新指定大小
v.resize(10,520); //利用重载版本,可以指定默认填充值--->参数2
print(v); //如果重新指定的比原来长了,默认用0填充新位置
cout << "改变大小后的容器容量为: " << v.capacity() << endl;
cout << "改变大小后的容器大小为: " << v.size() << endl;
//如果重新指定的大小比原来短了,超出的部分会被删除
v.resize(3);
print(v);
}
int main()
{
test();
system("pause");
return 0;
}