#include #include #include // for accumulate #include #include #include using namespace std; #include "strutils.h" /** * Info stores a string and how many times * the string occurs: wrap word/count together */ struct Info { Info(const string& s="") // default count = 1 : myStr(s), myCount(1) { } string myStr; int myCount; }; // operators to facilitate STL functions with Info objects bool operator ==(const Info& lhs, const Info& rhs) // post: return true iff Info strings are the same { return lhs.myStr == rhs.myStr; } ostream& operator << (ostream& out, const Info& inf) // post: inf inserted onto out (both count and string) { out << inf.myCount << "\t" << inf.myStr; return out; } // can use the function or the functor/function object // these allow Info (count) to be added to an int int addup(int x, const Info& inf) // post: return x + inf (inf.count used) { return x + inf.myCount; } struct AddUp { int operator()(int x, const Info& inf) // post: return x + inf (inf.count used) { return x + inf.myCount; } }; int main(int argc, char * argv[]) { vector st; // store words/counts here vector::iterator it; // iterate over the vector if (argc == 1) { cerr << "usage: " << argv[0] << " filename" << endl; exit(1); } ifstream input(argv[1]); string s; while (input >> s) { it = find(st.begin(),st.end(),s); // lookup string if (it == st.end()) // didn't find it { st.push_back(s); // so add to end } else // found string { it->myCount++; // bump # occurrences } } copy(st.begin(), st.end(), ostream_iterator(cout,"\n")); cout << "# unique words = " << st.size() << endl; cout << "total # words = " << accumulate(st.begin(), st.end(), 0, addup) // << accumulate(st.begin(), st.end(), 0, AddUp()) << endl;; return 0; }