感觉这个算法挺巧妙的。利用map的性质进行字典序排序,将id设置为键值,若新插入的数据与map中不重复,则插入map1中,否则插入map2中。在2中将键值设置为name,即可通过使用迭代器遍历2得到输出结果。
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main() {
int n;
while (cin>>n && n) {
string name, id;
map<string, string>s1, s2;
map<string, string>::iterator it;
while (n--) {
cin>>name>>id;
it = s1.find(id); // 首先给it初始化
if (it == s1.end()) {
s1.insert(pair<string, string>(id, name));
}
else {
s2.insert(pair<string, string>(it->second, name));
}
}
for (it = s2.begin() ; it != s2.end() ; it++) {
cout<<it->second<<" is the MaJia of "<<it->first<<endl;
}
cout<<endl;
}
return 0;
}
本文介绍了一种使用C++中的map数据结构实现的字典序排序算法。该算法通过对ID进行排序来确保字典序,并利用迭代器遍历处理重复项。适用于需要对数据进行快速字典序排序并处理重复数据的场景。
694

被折叠的 条评论
为什么被折叠?



