// File; Concordance.cpp // Use a map to list all words and their # occurrences in a file, // stored by their first letter // Prepared by Dr. Spiegel #include #include #include #include #include using namespace std; typedef map pairMap; ostream &operator <<(ostream &out,pairMap Pairset) { pairMap::iterator p; for (p=Pairset.begin();p!=Pairset.end();) { cout << p->first << "=" << p->second; // << (++p!=Pairset.end()?", ":"") ; p++; if (p!=Pairset.end()) cout << ','; } return(out); } int main() { map Wordmap; ifstream infile("in"); string word; pairMap Pairset; // To hold values for letters while (infile >> word) { Pairset.clear(); char firstLet=toupper(word[0]); if (!isalpha(firstLet)) continue; if (Wordmap.find(firstLet)==Wordmap.end()) { // No entry for that letter...insert one Pairset[word]=1; Wordmap[firstLet]=Pairset; } else { // Got a map for this letter. Pairset=Wordmap[firstLet]; // Now, check for this word if (Pairset.find(word)==Pairset.end()) // word not found...add it Pairset[word]=1; else // it's there...increment Pairset[word]++; // Gotta put in the updated value map Wordmap[firstLet]=Pairset; } } // print the map map::iterator it; for (it=Wordmap.begin();it!=Wordmap.end();it++) { cout << it->first << ": {" << it->second ; cout << "}" << endl; } }