Find the most common character.

1. use a hashmap. 

#include<unordered_map>
#include<iostream>
#include<fstream>

using namespace std;


int main()
{
	ifstream file("a.txt");
	string line;
	unordered_map<char, int> hashmap;
	unordered_map<char, int>::iterator itr;

	while(file.good())
	{
		char c = file.get();
		if(c != ' ')
		{
			if(!hashmap.count(c))
			{
				hashmap[c] = 1;
			}
			else
			{
				int n = hashmap.find(c)->second;
				hashmap[c] = ++n;
			}
		}
	}
	char result;
	int max = 0;
	for(itr = hashmap.begin(); itr!=hashmap.end(); itr++)
	{
		if(itr->second > max)
		{
			max = itr->second;
			result = itr->first;
		}
	}
	
	cout<<result<<" "<<max<<endl;
	system("pause");
	return 0;
}

  

posted @ 2011-07-30 13:35  Sw_R  阅读(163)  评论(0编辑  收藏  举报