set和map中的STL

 

 

 

 

#pragma warning(disable:4786)
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <set>
#include <map>

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 word == s;
	}
};

class CWordSet
{
	set<CWord> wordset;
public:
	bool AddString(string s)
	{
		wordset.insert(CWord(s));
		return true;
	}

	void Show(ostream &os)
	{
		set<CWord>::iterator it = wordset.begin();
		int n = 0 ;
		while(it != wordset.end())
		{
			os << (*it).GetWord() << "\t";
			n ++;
			if(n % 8 == 0)
			{
				os << endl;
				n = 0;
			}
			it ++;
		}
	}
};

class CWordMap
{
	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 ++;
		}
	}
};

int main()
{
	CWordSet wordset;
	CWordMap wordmap;

	int pos = 0;
	string s = "";
	string delimset = ",.";
	ifstream in("1.txt");

	while(!in.eof())
	{
		getline(in,s);

		if(s == "")
			continue;
		pos = 0;
		while((pos=s.find_first_of(delimset,pos)) != string::npos)
			s.replace(pos,1," ");
		istringstream stringeam(s);

		while(!stringeam.eof())
		{
			stringeam >> s;
			if(s == "")
				continue;
			wordset.AddString(s);
			wordmap.AddString(s);
		}
	}

	in.close();
	
	cout << "word set : " << endl;
	wordset.Show(cout);
	cout << endl;
	cout << "word and times : "<< endl;
	wordmap.Show(cout);
	cout << endl;

	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值