【发布时间】:2013-10-01 18:37:03
【问题描述】:
所以基本上我的程序所做的就是读入一个单词数据流,并计算每个单词的出现次数,以及唯一单词的总数。它会将它们读入地图。我的程序运行良好,除了一个问题...当我调用 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;
}
【问题讨论】:
-
很高兴您发现了您的问题,但请更好地命名您的变量、类、函数和参数。描述性有助于其他阅读您的代码的人。
标签: c++ printing pass-by-value