为什么for_each对仿函数的调用sum::total最终不会更新?
struct sum
{
sum():total(0){};
int total;
void operator()(int element)
{
total+=element;
}
};
int main()
{
sum s;
int arr[] = {0, 1, 2, 3, 4, 5};
std::for_each(arr, arr+6, s);
cout << s.total << endl; // prints total = 0;
}
Run Code Online (Sandbox Code Playgroud)
Eri*_*rik 12
for_each通过值获取仿函数 - 因此它被复制.您可以使用例如使用指向外部int的指针初始化的仿函数.
struct sum
{
sum(int * t):total(t){};
int * total;
void operator()(int element)
{
*total+=element;
}
};
int main()
{
int total = 0;
sum s(&total);
int arr[] = {0, 1, 2, 3, 4, 5};
std::for_each(arr, arr+6, s);
cout << total << endl; // prints total = 15;
}
Run Code Online (Sandbox Code Playgroud)
或者您可以使用返回值 for_each
struct sum
{
sum():total(0){};
int total;
void operator()(int element)
{
total+=element;
}
};
int main()
{
sum s;
int arr[] = {0, 1, 2, 3, 4, 5};
s = std::for_each(arr, arr+6, s);
cout << s.total << endl; // prints total = 15;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5822 次 |
| 最近记录: |