//案例1(set、map)
//创建一个集合,保存文件中出现的单词;set
//创建一个映射,保存单词及该单词出现的次数;map
#include"iostream"
using namespace std;
#include"vector"
#include"set"
#include"map"
#include"iterator"
#include"functional"
#include"algorithm"
#include"numeric"
#include"fstream"
#include"sstream"
//单词基础类
class Word
{
private:
string s;
public:
Word(string s)
{
this->s = s;
}
public:
string getword()const
{
return s;
}
bool operator<(const Word &a)const //由于添加集合
{
return s < a.getword();
}
bool operator==(string s) //用于查询
{
return this->s == s;
}
};
//集合类
class Wordset
{
private:
set<Word>set_1;
public:
bool Wordset_add(string s)
{
set_1.insert(Word(s));
return true;
}
void show()
{
for (set< Word>::iterator it1 = set_1.begin(); it1 != set_1.end(); it1++)
{
cout << (*it1).getword() << " ";
}
}
};
//映射类
class Wordmap
{private:
map< Word,int>map_1;
public:
bool Wordmap_add(string s)
{
map<Word, int>::iterator it = map_1.find(s);
if (it == map_1.end())
{
pair<Word, int> p (Word(s),1);
map_1.insert(p);
}
else
{
it->second++;
}
return true;
}
void show()
{
for (map< Word,int>::iterator it2 = map_1.begin(); it2 != map_1.end(); it2++)
{
cout << it2->first.getword()<<":"<<"出现" <<it2->second<< "次";
}
}
};
int main()
{//建立集合和映射的实例;
Wordset set_111;
Wordmap map_111;
//打开文件并读取文本;
int pos = 0;
string s = " ";
string delimet = ",.?";
ifstream in1;
in1.open ("D://data.text");//读文件
char c;
while (in1.peek()!=EOF)//////////////此处用peek,用eof结尾会多一个字符
{
in1.read(&c,1);
cout << c;
}
in1.close();
ifstream in("D://data.text");
while (!in.eof())
{
getline(in,s);
if (s == " ")
continue;
pos = 0;
while ((pos = s.find_first_of(delimet, pos)) != string::npos)
{
s.replace(pos,1," ");
}
istringstream stringeam(s);
while (!stringeam.eof())
{
stringeam >> s;
if (s == "")
continue;
set_111.Wordset_add(s);
map_111.Wordmap_add(s);
}
}
in.close();
cout << endl;
cout << "单词集合为:" << endl;
set_111.show();
cout << endl;
cout << "单词集合及出现的次数:" << endl;
map_111.show();
cout << endl;
system("pause");
return 0;
}