此题需要将一组用可能用字母表达的电话号码中重复的电话号码统计出来并按顺序打印出来。
刚拿到此题我是蒙蔽的,于是百度了一下解法,认识到了map的妙用,大概相当于python中的字典。
当然也有些慢慢看出来的体会,比如新建一个map中的键值对时如果不给value赋值那么应该是默认为零,譬如:
map<string,int>mp;
string s;
map[s]+=1;
代码没有写全,想要表达的是这个map[s]+=1应该就是初始创建时为零,也就是说如果按上面代码运行s对应的值应该为1。
还有一个是map是自动按照键的大小来排序的,所以说使用map后就不需要再为排序问题纠结了,只需要记住键值是升序就可以了。
显然使用map非常方便于统计数据对。将最终提交代码贴在下面:
#include<iostream>#include<map>#include<string>using namespace std;char convert(char cha){ switch(cha) { case 'A': case 'B': case 'C': return '2'; case 'D': case 'E': case 'F': return '3'; case 'G': case 'H': case 'I': return '4'; case 'J': case 'K': case 'L': return '5'; case 'M': case 'N': case 'O': return '6'; case 'P': case 'R': case 'S': return '7'; case 'T': case 'U': case 'V': return '8'; case 'W': case 'X': case 'Y': return '9'; default: return cha; }}int main(){ map<string, int>mp; int count; cin >> count; string str; bool find = false; for (int i = 0; i < count; i++) { cin >> str; string s = ""; for (int j = 0; j < int(str.length()); j++) { if ((str[j] >= '0'&&str[j] <= '9') || (str[j] >= 'A'&&str[j] <= 'Z')) s += convert(str[j]); } mp[s] += 1; } map < string, int >::iterator it; for (it = mp.begin(); it != mp.end(); it++) { if (it->second != 1) { find = true; for (int i = 0; i < 7; i++) { cout << it->first[i]; if (i == 2) cout << '-'; } cout << ' '; cout << it->second<<endl; } } if (!find) cout << "No duplicates."<<endl; return 0;}
新闻热点
疑难解答