1

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; }
Ely
  • 10,860
  • 4
  • 43
  • 64

3 Answers3

2

The declaration of operator() of template <typename T> std::plus is

T operator()(const T& lhs, const T& rhs) const;

i.e. it does not modify the input arguments. You need std::transform:

std::transform(v1.cbegin(), v1.cend() v1.begin(), std::bind2nd(std::plus<int>(), 1));

or you can use a lambda which does modify it's input argument:

std::for_each(v1.begin(), v1.end(), [] (int& x) { ++x; });
Daniel
  • 8,179
  • 6
  • 31
  • 56
1

std::for_each does not modify the input sequence.

To apply a change to each element of the container, use std::transform instead:

transform(v1.begin(), v1.end(), v1.begin(), bind2nd(plus<int>(), 1));
//                              ~~~~~~~~~^ puts the results back into the input sequence
Piotr Skotnicki
  • 46,953
  • 7
  • 118
  • 160
1
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; });
songyuanyao
  • 169,198
  • 16
  • 310
  • 405