用C++写main函数实现:Write a program to complete the following command: new id - create a specified sequence of Numbers for id (id < 200000) Add id num - to join the sequence of Numbers for id integer num merge id1 id2 - merger sequence number of id1 and id2, and make id2 empty unique id - remove repetitive element in the sequence id out id - from small to large, output the elements of sequence of Numbers for ids separated by Spaces Input The First Line is n which mean the number of the Command (n <= 200000). The next n lines are correct Command. You don't have to worry wrong input and id is int. Output Then output according the requirements.
时间: 2024-02-14 22:13:40 浏览: 19
Sure, here's an implementation of the program in C++:
```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
unordered_map<int, vector<int>> sequences;
for (int i = 0; i < n; i++) {
string command;
cin >> command;
if (command == "new") {
int id;
cin >> id;
sequences[id] = {};
} else if (command == "add") {
int id, num;
cin >> id >> num;
sequences[id].push_back(num);
} else if (command == "merge") {
int id1, id2;
cin >> id1 >> id2;
sequences[id2].insert(sequences[id2].end(), sequences[id1].begin(), sequences[id1].end());
sequences[id1].clear();
} else if (command == "unique") {
int id;
cin >> id;
sort(sequences[id].begin(), sequences[id].end());
sequences[id].erase(unique(sequences[id].begin(), sequences[id].end()), sequences[id].end());
} else if (command == "out") {
int id;
cin >> id;
sort(sequences[id].begin(), sequences[id].end());
for (int num : sequences[id]) {
cout << num << " ";
}
cout << endl;
}
}
return 0;
}
```
This program works in a similar way to the Python implementation. It uses an `unordered_map` called `sequences` to keep track of the sequences of numbers for each id.
For each command, the program reads in the command string and checks the first word to determine what action to take. If the first word is `new`, it creates a new empty sequence for the specified id. If the first word is `add`, it adds the specified number to the sequence for the specified id. If the first word is `merge`, it merges the sequence for the first id into the sequence for the second id, and clears the first sequence. If the first word is `unique`, it removes duplicate elements from the sequence for the specified id. If the first word is `out`, it sorts the sequence for the specified id and prints it out as a space-separated list.
I hope this helps! Let me know if you have any questions or if there's anything else I can do for you.