仿函数返回0

Jon*_*Jon 7 c++ stl

我最近开始自学标准模板库.我很好奇为什么这个类中的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)

  • 如果他们使它成为可修改的引用,那将排除传递临时(这是最常见的用法).如果他们把它作为const引用,那么对于像这样的有状态仿函数,它将回到正方形1 ......它必须复制并按值返回.确定内联引用别名参数对于内联引擎来说可能比双重复制更难,这就是事情的运作方式.我认为规范是非常具有前瞻性的. (5认同)