C++ for_each()和函数指针

raj*_*504 0 c++ function-pointers

我试着让myFunction给我一个数组中的值的总和,但我知道我不能使用返回值,当我用代码运行我的程序时,所有我得到的是打印出来的值并没有总结为什么?

void myFunction (int i) {
int total = 0;
total += i;
cout << total;
}


int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

for_each( array, array+10, myFunction);


return 0;
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ork 8

你真的需要一个仿函数来在迭代之间存储状态:

struct Sum
{
    Sum(int& v):  value(v) {}
    void operator()(int data) const { value += data;}

    int& value;
};

int main()
{
    int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    int total = 0;
    std::for_each( array, array+10, Sum(total));

    std::cout << total << std::endl;
}
Run Code Online (Sandbox Code Playgroud)