此題需要將一組用可能用字母表達的電話號碼中重復的電話號碼統計出來并按順序打印出來。
剛拿到此題我是蒙蔽的,于是百度了一下解法,認識到了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;}
新聞熱點
疑難解答