题一: 有一个txt文件,里面都是空格或者回车分隔的英文单词。请写一个程序,输入文件名,输出文件中出现次数最多的前20个单词。
1,使用 unordermap统计字符出现次数
2,将unordermap统计后的次数转化成pair 的vector ,
3,调用sort函数自定义排序规则进行排序。
#include <iostream>
#include <unordered_map>
#include <string>
#include <vector>
#include <sstream>
#include <fstream>
#include <iterator>
#include <algorithm>
using namespace std;
vector<string> FindMaxCountWords01()
{
ifstream in("in.txt");
string line;
unordered_map<string, int> wordMap;
vector<string> res;
while (getline(in, line))
{
stringstream ss(line);
string word;
while (ss >> word) ++wordMap[word];
}
vector<pair<string, int>> vec;
for (const auto &m : wordMap) vec.push_back(m);
sort(vec.begin(), vec.end(), [](const pair<string, int> &p1, const pair<string, int> &p2) { return p1.second > p2.second; });
for(int loop = 0;loop < min(20, static_cast<int> (vec.size()));loop++)
{
res.push_back(vec[loop].first);
}
return res;
}
题二:混合字符串数组的排序,输入字符串数组/vector,输出,递增排序后的字符串数组/vector
两个字符串(字符串1、字符串2)的大小比较,字符串可能既含有字符(a~z)又含有数字(0~9)。比较规则:
(1)从左到右分离单纯的子字符串(全字符)和子数字串(全数字)进行比较。
(2)如果被比较的都是子字符串,则可以调用strcmp比较子字符串大小。
(3)如果被比较的都是子数字串,则根据值比较大小,如果值相等,则子数字串短的一方大(前面的0少)。
(4)如果被比较的一边是子数字串,一边是子字符串,则子字符串大。
测试例子,对字符串组B1,B01,B2,B11进行递增排序:输出应该是B01,B1,B2,B11。
调用sort函数对vector排序,自定义规则。
1,对string 正则匹配切分。
2,对切分的每一个字串按照相关规则进行比较。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <regex>
#include <string.h>
using namespace std;
bool comp(const string &s1, const string &s2)
{
regex e(R"(\d+|[a-z,A-Z]+)");
string s1Sub,s2Sub;
sregex_iterator iter1(s1.begin(), s1.end(), e);
sregex_iterator end1;
sregex_iterator iter2(s2.begin(), s2.end(), e);
sregex_iterator end2;
for(;(iter1 != end1) && (iter2 != end2); ++iter1,++iter2)
{
s1Sub = (*iter1)[0];
s2Sub = (*iter2)[0];
if(s1Sub.compare(s2Sub) == 0) continue;
if(regex_match(s1Sub, regex("\\d+")) && regex_match(s2Sub, regex("\\d+"))){
return (stoi(s1Sub) == stoi(s2Sub)) ? (s1Sub.size() > s2Sub.size()) : (s1Sub < s2Sub);}
else if(regex_match(s1Sub, regex("\\w+")) && regex_match(s2Sub, regex("\\w+"))){
return strcmp(s1Sub.c_str(),s2Sub.c_str()) > 0 ? true : false;}
else{
return regex_match(s1Sub, regex("\\d+"));}
}
return true;
}
void SortString(vector<string> &vec)
{
sort(vec.begin(), vec.end(),comp);
}