Can't use std::for_each() and std::bind() to filter elements in a vector and put those filtered elements into a new vector

Viewed 43

Why doesn't the below code work when I'm trying to use std::for_each() and std::bind() to filter elements in a vector and put those filtered elements into a new vector?

void mypred(int a, int b, vector<int>& c){
    if(a < b){
        cout <<"yes" << endl;
        c.push_back(a);
    }
}

int main(){
    vector<int> test = {1,2,3,4,5,6,7};
    vector<int> final;
    final.reserve(10);
    for_each(test.begin(), test.end(), bind(mypred, placeholders::_1, 3, final));
    for(auto i = final.begin(); i != final.end(); i++){
        cout << *i << endl;
    }

    return 0;
}

This code can only print out two yes. But nothing in the vector final.

1 Answers

Finally, I know what's happened. Thanks for the help from @MikeVine. std::bind() will use a copy rather than a reference of a parameter. So we need to add std::ref() to let it use a reference.

Related