Search code examples
c++foreachbind2nd

bind2nd in a for_each loop


There is something I currently cannot wrap my head around. I was expecting an output where each element is incremented by 1. Obviously that is not the case.

After looking closer, I think that is because the bind2nd function's return value is discarded; that is to say the function does not modify the elements of the container.

Is my thinking correct? Can someone confirm or provide a correct explanation for the container not being modified?

#include <vector>
#include <iostream>
#include <algorithm>
#include <functional> using namespace std; void printer(int i) {
        cout << i << ", "; } int main() {
        int mynumbers[] = { 8, 9, 7, 6, 4, 1 };
        vector<int> v1(mynumbers, mynumbers + 6);
        for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));//LINE I
        for_each(v1.rbegin(), v1.rend(), printer);//LINE II
        return 0; }

Solution

  • for_each(v1.begin(), v1.end(), bind2nd(plus<int>(), 1));
    

    is equivalent as:

    for (auto first = v1.begin(); first != last; ++first) {
        plus<int>()(*first, 1); // i.e. *first + 1;
    }
    

    As you seen it won't change anything indeed.

    You could use a functor which change the value with std::for_each:

    std::for_each(v1.begin(), v1.end(), [](int &n){ n += 1; });