Consider, I’m use std::for_each and object with overloaded operator() to accumulate some data about vector content:
#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;
}
This outputs:
a:1
a:2
a:2
non-zero elements:0
Why is non-zero elements 0?
std::for_each()does not take its third argument by reference, so a copy ofaccumis made.If you add
std::coutstatements toA::A()you can witness this behaviour.Just to note, you can solve this particular problem using
std::count_if():