1-A-vector
题目
Vector
For a dynamic arrayA={a0,a1,…}
A ={a0,a1,…} of integers, perform a sequence of the following operations:
- 0 pushBack(x): add element x at the end of A randomAccess§:
- 1 p print element a[p]
- 2 popBack(): delete the last element of A A is a 0-origin array and it is empty in the initial state.
输入
The input is given in the following format.
q
q1
q2
…
qi
Each query queryi is given by 0 x or p or2
where the first digits 0, 1 and 2 represent pushBack, randomAccess and popBack operations respectively.
randomAccess and popBack operations will not be given for an empty array.
(1≤q≤200,000 0≤p< the size of A −1,000,000,000≤x≤1,000,000,000)
样例输入
8
0 1
0 2
0 3
2
0 4
1 0
1 1
1 2
样例输出
1
2
4
题解(代码流程)
#include<bits/stdc++.h>
using namespace std;
#define endl ’\n‘//此处换行符的替换提高运行速度
int main() {
ios::sync_with_stdio(false);//
cin.tie(nullptr);//
cout.tie(nullptr);//优化,提高整个程序运行速度
vector<int> A;//定义vector
int q;
cin >> q;
while (q--) {
int t;
cin >> t;
if (t == 0) {
int x;
cin >> x;
A.push_back(x);//在最后添加一个元素
} else if (t == 1) {
int p;
cin >> p;
if (A.empty())continue;//判断是否为空并进行过滤操作
cout << A[p] << endl;
} else {
if (A.empty())continue;
A.pop_back();//移除最后一个元素
}
}
return 0;
}
小结
学习了vector的定义与使用,及几项对vector修改的基本操作。
remember
- push_back()
- pop_back()
- empty()