STL之vector使用详解

时间:2021-09-29 04:19:43

好久不用STL了,忘的差不多了,总结一下vector的使用方式,就不对每个方法做出详细解释了,只给出了如何用


void testVector()
{
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
//构造一个元素值全为2大小为10的vector
vector<int> v1(10,2);
//用指针构造
vector<int> v2(a, a + 10);
//用vector iterator构造
vector<int> v3(v2.begin(), v2.end());
//构造一个和v1一样的vector
vector<int> v4(v1);

//使用[]操作符进行遍历
cout << "=================v1===============" << endl;
for (int i = 0; i < v1.size(); i++)
{
cout << v1[i] << " ";
}
cout << endl;



vector<int>::iterator it;
//得到第2个元素的iterator
it = v2.begin() + 1;
//移除第2个元素,返回移除元素后一个元素的iterator
vector<int>::iterator erase_it = v2.erase(it);
cout << *erase_it << endl;
//移除之后就不能通过iterator访问了
//cout << *it << endl;
//通过iterator 遍历
cout << "=================v2===============" << endl;
for (it = v2.begin(); it != v2.end(); it++)
{
cout << *it << " ";
}
cout << endl;

//逆序遍历
cout << "=================v3 reserver======" << endl;
vector<int>::reverse_iterator rit;
for ( rit = v3.rbegin(); rit != v3.rend() ; rit++)
{
cout << *rit << " ";
}
cout << endl;


cout << "=================v4 swap v3========" << endl;
//交换v4和v3的内容
v4.swap(v3);
for (int i = 0; i < v4.size(); i++)
{
cout << v4[i] << " ";
}
cout << endl;


cout << "============v4 push pop insert======" << endl;
//在v4末尾插入100
v4.push_back(100);
//将末尾的100移除
v4.pop_back();
//在第二个元素位置插入1000
v4.insert(v4.begin() + 1, 1000);
//在第二个元素位置插入2个200
v4.insert(v4.begin() + 1, 2, 200);
//在第二个元素位置插入2个v1的开始到结束
v4.insert(v4.begin() + 1, v1.begin(), v1.end());
for (int i = 0; i < v4.size(); i++)
{
cout << v4[i] << " ";
}
cout << endl;

cout << "============v4 clear empty size======" << endl;
//清除v4中所有内容
v4.clear();
//检查v4是否为空
if (v4.empty())
{
cout << "v4 is empty" << endl;
cout << "v4 size = "<<v4.size() << endl;
}
}


以下是测试结果

STL之vector使用详解