我最近开始自学标准模板库.我很好奇为什么这个类中的GetTotal()方法返回0?
...
class Count
{
public:
Count() : total(0){}
void operator() (int val){ total += val;}
int GetTotal() { return total;}
private:
int total;
};
void main()
{
set<int> s;
Count c;
for(int i = 0; i < 10; i++) s.insert(i);
for_each(s.begin(), s.end(), c);
cout << c.GetTotal() << endl;
}
Run Code Online (Sandbox Code Playgroud)
GMa*_*ckG 13
for_each
采用函数按值.也就是说,它使用仿函数的副本而不是仿函数本身.你的本地c
保持不变.
for_each
但是返回它使用的仿函数,所以你可以这样做:
Count c;
c = for_each(s.begin(), s.end(), c);
Run Code Online (Sandbox Code Playgroud)
或更具惯用性:
Count c = for_each(s.begin(), s.end(), Count());
Run Code Online (Sandbox Code Playgroud)
但是,已经存在这样的功能(不需要你的仿函数):
int total = std::accumulate(s.begin(), s.end(), 0);
Run Code Online (Sandbox Code Playgroud)