第一轮
第一版(不完整)
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
string s;
getline(cin, s);
istringstream iss(s);
unordered_map<string, int> words;
string word;
while(iss >> word){
words[word]++;
}
// 用词频(值)对哈希表中的键值对排序,但哈希表又无法排序。
// 似乎可以先把哈希表中的键值对拆出来放到vector容器里。
vector<pair<string, int>> key_words;
for (string s : words[]) {
}
// 在容器里就可以用sort排序了。
sort(key_words.begin(), key_words.end(), [](const pair<string, int>& a, const pair<string, int>& b){
if (a.second != b.second) return a.second > b.second;
if (a.first != b.first) return a.first < b.first;
});
}
// 64 位输出请用 printf("%lld")
- 主要的卡点在于不会遍历
vector<pair<string, int>>
类型。
第二版(无法编译)
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
string s;
getline(cin, s);
istringstream iss(s);
unordered_map<string, int> words;
string word;
while(iss >> word){
words[word]++;
}
// 用词频(值)对哈希表中的键值对排序,但哈希表又无法排序。
// 似乎可以先把哈希表中的键值对拆出来放到vector容器里。
vector<pair<string, int>> key_words;
for (const auto& entry : words) {
if(entry.second >= 3) key_words.emplace_back(entry);
}
// 在容器里就可以用sort排序了。
sort(key_words.begin(), key_words.end(), [](const pair<string, int>& a, const pair<string, int>& b){
if (a.second != b.second) return a.second > b.second;
if (a.first != b.first) return a.first < b.first;
});
for(const auto& result : key_words){
cout << result.first << endl;
}
}
// 64 位输出请用 printf("%lld")
- 注意这里在
vector<pair<string, int>>
类型后追加用的函数是emplace_back()
。
第三版(AC)
#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
string s;
getline(cin, s);
istringstream iss(s);
unordered_map<string, int> words;
string word;
while(iss >> word){
words[word]++;
}
// 用词频(值)对哈希表中的键值对排序,但哈希表又无法排序。
// 似乎可以先把哈希表中的键值对拆出来放到vector容器里。
vector<pair<string, int>> key_words;
for (const auto& entry : words) {
if(entry.second >= 3) key_words.emplace_back(entry);
}
// 在容器里就可以用sort排序了。
sort(key_words.begin(), key_words.end(), [](const pair<string, int>& a, const pair<string, int>& b){
if (a.second != b.second) return a.second > b.second;
return a.first < b.first;
});
for(const auto& result : key_words){
cout << result.first << endl;
}
}
// 64 位输出请用 printf("%lld")
- 注意前面的编译错误,这是因为之前的lambda函数没有考虑清楚,没能覆盖所有情况。在脑海中画一个图出来就好了。