2021春季学期面向对象程序设计第十四、十五周课外练习--List

List
Description
写一个程序完成以下命令:
new id ——新建一个指定编号为id的序列(id<10000)
add id num——向编号为id的序列加入整数num
merge id1 id2——合并序列id1和id2中的数,并将id2清空
unique id——去掉序列id中重复的元素
out id ——从小到大输出编号为id的序列中的元素,以空格隔开
Input
第一行一个数n,表示有多少个命令(n<=200000)。以后n行每行一个命令。
Output
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
如果OJ平台不需要每行末尾不加空格,那就简单多了
献上一份Open judge上通过的代码在这里插入代码片

在这里插入代码片#include<iostream>
#include<string>
#include<iterator>
#include<list>
using namespace std;
int main(){
    int n;
    cin>>n;
    list<int> lst[10005];
    string command;
    int id;
    while(n--){
        cin>>command;
        if(command=="new") cin>>id;
        else if(command=="add"){
            int num;
            cin>>id>>num;
            lst[id].push_back(num);
        }
        else if(command=="merge"){
            int id2;
            cin>>id>>id2;
            lst[id].merge(lst[id2]);
        }
        else if(command=="unique"){
            cin>>id;
            lst[id].sort();
            lst[id].unique();
        }
        else{
            cin>>id;
            lst[id].sort();
            copy(lst[id].begin(),lst[id].end(),ostream_iterator<int>(cout," "));
            cout<<endl;
        }
    }
    return 0;
}

但是末尾不需要空格的难到我了,淦。话不多说,直接上我的代码

//  main.cpp
//  List
//
//  Created by liang on 5/31/21.
//

#include<iostream>
#include<string>
#include<iterator>
#include<list>
using namespace std;
int main(){
    int n;
    cin>>n;
    list<int> lst[10005];
    string command;
    int id;
    while(n--){
        cin>>command;
        if(command=="new") cin>>id;
        else if(command=="add"){
            int num;
            cin>>id>>num;
            lst[id].push_back(num);
        }
        else if(command=="merge"){
            int id2;
            cin>>id>>id2;
            lst[id].merge(lst[id2]);
        }
        else if(command=="unique"){
            cin>>id;
            lst[id].sort();
            lst[id].unique();
        }
        else{
            cin>>id;
            lst[id].sort();
            //copy(lst[id].begin(),lst[id].end(),ostream_iterator<int>(cout," "));
            if(lst[id].size()>0){//一定要判断,不然会输出一些奇怪的东西,可以自己试试,反正你就会WA
            list<int>::iterator iter1=lst[id].begin();
            list<int>::iterator iter2=lst[id].end();
            advance(iter2, -1);//advance迭代器的辅助函数,advance(iter,n)就相当于iter+=n,n可以为负
                //数
            for(auto it=iter1;it!=iter2;++it)
                cout<<*it<<" ";
            cout<<lst[id].back();//输出最后一个数据,list.back()返回最后一个元素的引用
            }
            cout<<endl;
        }
    }
    return 0;
}

如果大佬有更好的方法,欢迎评论区发表高见!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值