局部变量/类变量增量

Local Variable / Class variable increment

本文关键字:类变量 局部变量      更新时间:2023-10-16

所以本质上我的程序所做的是在单词的数据流中读取,并计算每个单词的出现次数,以及唯一单词的总数。它会将它们读入地图。我的程序运行良好,除了一个问题...当我调用p.print()时,total的值仍然为0。似乎有一些问题,在 for_each 语句中增加总数,但是当我 p.print 时,它表现得好像从未增加过......我的打印函数定义如下:

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

我有一个负责处理每个单词的类,这是定义:

//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;
}

通了...我需要有

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

没有比弄清楚自己的问题更好的感觉了!