Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ operator() behavior

Tags:

c++

std

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?

like image 298
sevenbit Avatar asked Aug 24 '26 07:08

sevenbit


1 Answers

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;
like image 83
hmjd Avatar answered Aug 25 '26 19:08

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!