vector
vector
1 基本操作
(1)头文件#include<vector>.
(2)创建vector对象,vector<int> vec;
(3)尾部插入数字:vec.push_back(a);
(4)使用下标访问元素,cout<<vec[0]<<endl;记住下标是从0开始的。
(5)使用迭代器访问元素.
vector<int>::iterator it;
for( it=a.begin() ; it!=a.end() ;it++) cout<<*it<<" ";
(6)插入元素: vec.insert(vec.begin()+i,a);在第i个元素后面插入a;
(7)删除元素: vec.erase(vec.begin()+2);删除第3个元素
vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始
(8)向量大小:vec.size();
(9)清空:vec.clear() //清空之后,vec.size()为0
[eg]
#include<bits/stdc++.h>
#include<vector>
using namespace std;
int main()
{
int i=0;
vector<int> vec;
for(i=0; i<10; i++)
{
vec.push_back(i); //10个元素依次进入,结果为10
}
for(unsigned int i=0; i<vec.size(); i++)
{
cout<<"初始化遍历:"<<vec[i]<<endl;
}
//结果为:0,1,2,3,4,5,6,7,8,9
vector<int>::iterator it;
for(it = vec.begin(); it!=vec.end(); it++)
{
cout<<"迭代遍历:"<<*it<<endl;
}
//结果为:0,1,2,3,4,5,6,7,8,9
vec.insert(vec.begin()+4,0);
//结果为:11
for(unsigned int i=0; i<vec.size(); i++)
{
cout<<"插入遍历:"<<vec[i]<<endl;
}
//结果为:0,1,2,3,0,4,5,6,7,8,9
vec.erase(vec.begin()+2);
for(unsigned int i=0; i<vec.size(); i++)
{
cout<<"擦除遍历:"<<vec[i]<<endl;
}
//结果为:0,1,3,0,4,5,6,7,8,9
vec.erase(vec.begin()+3,vec.begin()+5);
for(vector<int>::iterator it = vec.begin(); it!=vec.end(); it++)
{
cout<<"迭代遍历:"<<*it<<endl;
}
return 0;
}
题目链接: https://www.luogu.com.cn/problem/P3156
https://www.luogu.com.cn/problem/P3613