直接贴代码:
#include <vector>
#include <iostream>
using std::cout;
using std::endl;
using std::vector;
int main()
{
int a[] = { 2,4,5,5,5,1,8,7,4 };
vector<int> test(a, a + 9);
vector<int>::iterator it, it1;
cout << test.size() << " " << test.capacity() <<endl<<endl; //分别输出容器的元素个数和容量(及可容纳元素个数)
for (it = test.begin(); it != test.end();)
{
it1 = find(test.begin(), it, *it); //若当前位置之前存在重复元素,删除当前元素,erase返回当前元素的下一个元素指针
if (it1 != it)
it = test.erase(it);
else
it++;
}
cout << "result: " << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
cout << test.size() << " " << test.capacity() << endl; //只改变size,不改变capacity,即只改变元素个数,不改变容量
test.reserve(7); //强制改变容器的容量,但7<9,编译器会忽略
cout << test.size() << " " << test.capacity() << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
test.reserve(12); //12>9,强制改变容器容量为12
cout << test.size() << " " << test.capacity() << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
test.resize(3); //强制改变元素个数,因为3<12(容量),所以容量不会改变(还装得下),元素保留前3个
cout << test.size() << " " << test.capacity() << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
test.resize(7); //7<12,容量仍旧不会改变,元素增加,默认补0
cout << test.size() << " " << test.capacity() << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
test.resize(9, 2);//9<12,容量不变,元素增加,元素为2,resize()的重载
cout << test.size() << " " << test.capacity() << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
test.resize(15); //因为15>12,容器装不下了,所以容量会自动分配
cout << test.size() << " " << test.capacity() << endl;
for (it = test.begin(); it<test.end(); it++)
cout << *it;
cout << endl << endl;
system("pause");
}
运行结果:
萌新一枚,还望各路大神指点=。=