统计文章中相同单词的个数

利用STL中的multimap实现:

#include 
#include 
#include 
#include 
#include 

using namespace std;

template 
void print_map (const T& m)
{
	T::const_iterator p = m.begin();
	for (; p!=m.end(); ++p)
	{
		cout << (p->second) << ":" << (p->first) << endl;
	}
}

class MyString : public string
{
	friend bool operator < (const MyString& ms1, const MyString& ms2)
	{
		int i;
		string s1 = ms1;
		string s2 = ms2;
		for (i=0; i='A' && c<='Z' || c>='a' && c<='z'))
		{
			c = ' ';
		}
		ss.put(c);
	}

	MyString word;
	map words;
	
	while (ss >> word)
		++words[word];

	multimap > mwords;
	for (map::iterator p=words.begin(); p!=words.end(); ++p)
	{
		pair pa(p->second, p->first);
		mwords.insert(pa);
	}
	print_map(mwords);

	return 0;
}


结果的结构是:

你可能感兴趣的:(C&&C++,STL)