【C++编程基础】AOJ (C++ Programming II)—1-A-vector

本文详细解析了一种动态数组的实现方式,通过C++的vector进行数组的增删查操作,包括push_back、pop_back和随机访问等功能,并提供了一个完整的代码示例,展示了如何处理一系列的操作指令。

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()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值