Created
September 27, 2011 15:11
-
-
Save allen501pc/1245319 to your computer and use it in GitHub Desktop.
Count Words and Sort It!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Program Description: | |
* Count the input data character frequence, and store the characters which are composed with 'A-Z' or 'a-z'. | |
* And output the character and respective frequency. Note that the characters 'A-Z' and 'a-z' are the same. | |
* For example, | |
* Input: | |
* This is a text for Q2. | |
* My cellphone number is 123-456-789. | |
* E-mail: [email protected] | |
Output: | |
E 6 | |
L 6 | |
I 5 | |
M 5 | |
A 4 | |
C 3 | |
N 3 | |
O 3 | |
S 3 | |
T 3 | |
H 2 | |
P 2 | |
R 2 | |
B 1 | |
F 1 | |
G 1 | |
Q 1 | |
U 1 | |
X 1 | |
Y 1 | |
*/ | |
#include <iostream> | |
#include <cstdlib> | |
#include <map> | |
#include <string> | |
#include <algorithm> | |
#include <vector> | |
using namespace std; | |
class MyCompare | |
{ | |
public: | |
bool operator()(const pair<char,int> & Obj1, const pair<char, int> & Obj2) | |
{ | |
if(Obj1.second == Obj2.second) | |
{ | |
return Obj1.first < Obj2.first; | |
} | |
else | |
{ | |
return Obj1.second > Obj2.second; | |
} | |
} | |
}; | |
typedef map<char, int> MyMap; | |
int main(int argc, char * argv[]) | |
{ | |
int MaxLines = 0; | |
string MyStr; | |
MyMap StoredMap; | |
while(getline(cin,MyStr)) | |
{ | |
for(int Idx=0;Idx<MyStr.size();++Idx) | |
{ | |
char GetChar ='8'; | |
if(MyStr[Idx]>=65 && MyStr[Idx]<=90) | |
GetChar = MyStr[Idx]; | |
else if(MyStr[Idx]>=97 && MyStr[Idx]<=122) | |
GetChar = MyStr[Idx]-32; | |
if(GetChar!='8') | |
{ | |
pair<MyMap::iterator,bool> FindIt = StoredMap.insert(pair<char,int>(GetChar,1)); | |
if(!FindIt.second) | |
{ | |
FindIt.first->second += 1; | |
} | |
} | |
} | |
} | |
vector<pair<char,int> > StoredVector; | |
for(MyMap::iterator TempIt = StoredMap.begin(); TempIt != StoredMap.end(); ++ TempIt) | |
{ | |
StoredVector.push_back(pair<char,int>(TempIt->first,TempIt->second)); | |
} | |
/* Sort */ | |
sort(StoredVector.begin(),StoredVector.end(),MyCompare()); | |
/* Print */ | |
for(vector<pair<char, int> >::iterator TempIt = StoredVector.begin(); TempIt != StoredVector.end(); ++ TempIt) | |
{ | |
cout << TempIt->first << " " << TempIt->second << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment