Question

So essentially what my program does is read in a data stream of words, and count the occurrence of each word, and the total number of unique words. It will will read them into a map. My program works perfectly except for one problem...when I call p.print(), the value for total is still at 0. There seems to be some problem where total is incremented in the for_each statement, but when I p.print, it acts as if was never incremented...My print function is defined as follows:

void print_words(const map<string,int> &aMap) {
    PRN p(aMap.size());
    for_each(aMap.begin(), aMap.end(), p);
    p.print();
}

I have a class that is in charge of processing each word, here is the definition:

//CLASS PRN FUNCTIONS
// constructor
PRN::PRN(const int& s, const int& c, const int& t) {
    sz=s;
    cnt=c;
    total=t;
}

// overloaded operator, where P is defined as
// typedef pair < string, int > P;
void PRN::operator()(const P& p) {
    if(cnt%NO_ITEMS == 0 && cnt != 0)
        cout << '\n';
    cout << setw(ITEM_W) << left << p.first << " : " << setw(NO_W) << left << p.second;
    total += p.second;
    cnt++;
}

// to printout final value of total                                                             
void PRN::print() const {
    cout << '\n' << '\n';
    cout << "no of words in input stream  : " << total << endl;
    cout << "no of words in output stream : " << sz << endl;
}
Was it helpful?

Solution

Figured it out...I need to have

p = for_each(aMap.begin(), aMap.end(), p);

No better feeling then figuring out your own problem!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top