思路:
- 从文件中读出每一行,将字符串中的标点符号替代为空格;
- 使用字符串输入流将字符串里的各个单词赋给单个单词变量;
- 将单词和出现的次数构成映射放入map中;
- 排序: 复制map到vector中,重载>运算符进行排序。
代码:
#include<iostream>
#include<map>
#include<vector>
#incude<algorithm>
#include<string>
using namespace std;
class CWord
{
string word;
public:
CWord(string word)
{
this->word = word;
}
string GetWord() const { return word; }
bool operator < (const CWord &w) const // 用于添加集合
{
return word < w.GetWord();
}
bool operator == (const string &s) const // 用于查询
{
return this->word == s;
}
};
class CWordMap
{
private:
map<CWord, int> wordmap;
public:
bool AddString(string s)
{
map<CWord, int>::iterator it = wordmap.find(s);
if (it == wordmap.end())
{
pair<CWord, int> p(CWord(s), 1);
wordmap.insert(p);
}
else
{
(*it).second += 1;
}
return true;
}
void Show(ostream &os)
{
map<CWord, int>::iterator it = wordmap.begin();
while (it!=wordmap.end())
{
string ss = ((*it).first).GetWord();
int n = (*it).second;
os << ((*it).first).GetWord() << "\t" << (*it).second << endl;
it++;
}
}
map<CWord, int>::iterator begin()
{
return wordmap.begin();
}
map<CWord, int>::iterator end()
{
return wordmap.end();
}
};
bool compare(pair<CWord,int> &mp1, pair<CWord,int> &mp2)
{
return mp1.second > mp2.second;
}
int main()
{
CWordSet wordset;
CWordMap wordmap;
int pos = 0;
string s = "";
string deliset = ",.";
ifstream in("data.txt");
while (!in.eof())
{
getline(in, s);
if (s == "")
{
continue;
}
pos = 0;
while ((pos = s.find_first_of(deliset,pos))!=string::npos)
{
s.replace(pos, 1, " ");
}
istringstream str(s);
while (!str.eof())
{
str >> s;
if (s == "")
continue;
wordmap.AddString(s);
//wordset.AddString(s);
}
}
in.close();
cout<<"未排序前:"<<endl;
wordmap.Show(cout);
vector<pair<CWord, int>>::iterator it= v.begin();
int n = 0;
cout<<"排序后:"<<endl;
while (it!= v.end())
{
if (n != 10)
{
cout << (*it).first.GetWord() << ":" << (*it).second << endl;
it++;
n++;
}
else
break;
}
return 0;
}
程序运行截图: