考虑一下,我使用 std::for_each 和带有重载 operator() 的对象来积累一些关于向量内容的数据:
#include <iostream>
#include <vector>
#include <algorithm>
struct A{
int a;
A(): a(0){}
void operator()(int i) {
if(i) a++;
std::cout << "a:" << a << std::endl;
}
};
int main(int argc, char *argv[]) {
//test data
std::vector<int> vec;
vec.push_back(1);
vec.push_back(1);
vec.push_back(0);
//accumulator
A accum;
std::for_each(vec.begin(), vec.end(), accum);
std::cout << "non-zero elements:" << accum.a << std::endl;
return 0;
}
这输出:
a:1
a:2
a:2
non-zero elements:0
为什么是non-zero elements
0?