关于动态数组的简单应用

代码展示了如何在C++中使用STLvector实现动态数组,支持多种操作,包括添加元素、排序、翻转和输出等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Easy - STL-vector

给定一个初始为空的动态数组,执行下面几种操作n次:

1 x :表示在数组的末尾添加数字x x(1 ≤ x ≤ 100)。

2 :表示将数组从小到大排序(保证此时数组不为空)。

3 :表示将数组翻转(保证此时数组不为空)。

4 :输出数组中数字的个数。

5 :按顺序输出数组中所有的元素(保证此时数组不为空)。

6 :把数组清空。

Input

第一行,一个整数n(1 ≤ n ≤ 20),表示操作的次数。

第2到n+1行,表示每一种操作。

Output

每次操作如果需要输出则输出一行数字。

Sample 1

InputcopyOutputcopy
10
1 28
1 12
1 17
5
2
5
3
5
6
4
28 12 17
12 17 28
28 17 12
0

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
    int n;
    cin >>n;
    vector<int> arr;
    for (int i = 0; i < n; i++)
    {
        int a;
        cin >>a;
        if (a==1)
        {
            int b;
            cin >> b;
            arr.push_back(b);
        }
        else if (a==2)
        {
            sort(arr.begin(),arr.end());
        }
        else if (a==3)
        {
            reverse(arr.begin(),arr.end());
        }
        else if (a==4)
        {
            cout <<arr.size()<<endl;
        }
        else if (a==5)
        {
            for (int j=0;j<arr.size();j++)
            {
                cout <<arr[j]<<" ";
            }
            cout <<endl;
        }
        else if (a==6)
        {
            arr.clear();
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值