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 of accum is made.
If you add std::cout statements to A::A() you can witness this behaviour.
Just to note, you can solve this particular problem using std::count_if():
std::cout << "non-zero elements: "
<< std::count_if(vec.begin(),
vec.end(),
[](const int i) { return i != 0; })
<< std::endl;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With