STL编程题-动态添加序列

问题描述

写一个程序完成以下命令:

new id ——新建一个指定编号为id的序列(id<10000)

add id num——向编号为id的序列加入整数num

merge id1 id2——合并序列id1和id2中的数,并将id2清空

unique id——去掉序列id中重复的元素

out id ——从小到大输出编号为id的序列中的元素,以空格隔开

输入

第一行一个数n,表示有多少个命令( n<=200000)。以后n行每行一个命令。

输出

按题目要求输出。

作者是利用链表和vector容器来解决的问题:http://blog.csdn.net/nnnnnnnnnnnny/article/details/50472593#cpp,下面是参考后改用hash_map实现的,个人觉觉得要简单些:

#include <iostream>
#include <iterator>
#include <list>//双向链表
#include <vector>
#include <string>
#include <hash_map>
#include <algorithm>
using namespace std;

template <class T>
struct print
{
	void operator()(const T &x)
	{
		cout << x << " ";
	}
};

int main()
{
	int n;
	cin >> n;
	hash_map<int, list<int> > myDb;

	for (int i = 0; i < n; i++)
	{
		string str;
		cin >> str;
		if (str == "new")
		{
			int id;
			cin >> id;
			myDb[id] = list<int>();
		}
		else if (str == "add")
		{
			int id, num;
			cin >> id >> num;
			myDb[id].push_back(num);
		}
		else if( str == "merge")
		{
			int id1, id2;
			cin >> id1 >> id2;
			myDb[id1].sort();
			myDb[id2].sort();
			myDb[id1].merge(myDb[id2]);
			myDb.erase(id2);
		}
		else if (str == "unique")
		{
			int id;
			cin >> id;
			myDb[id].sort();
			myDb[id].unique();
		}
		else if (str == "out")
		{
			int id;
			cin >> id;
			for_each(myDb[id].begin(), myDb[id].end(), print<int>());
			cout << endl;
		}

	}
	return 0;
}
运行结果如下:



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值