-2

I have the following code in one of my problems for a certification program I'm in and can't figure out why the vector of A objects aren't being changed when the for-each statement is called with the doubler() struct. The code is below, if anyone could shed some light on why this is the case that would be great; I'm sure it's something minuscule I'm overlooking.

class A {
    int a;
public:
    A(int a) :a(a) {}
    int getA() const { return a; } void setA(int a) { this->a = a; }
    bool operator < (const A & b) const { return a<b.a; }
};
struct myprinter { void operator() (const A & a) { cout << a.getA() << ", "; } };
struct doubler
{
    void operator() (A a) { a.setA(a.getA() * 2); }
};

int main() {
    int mynumbers[] = { 3, 9, 0, 2, 1, 4, 5 };
    vector<A> v1(mynumbers, mynumbers + 7);
    set<A> s1(mynumbers, mynumbers + 7);
    for_each(v1.begin(), v1.end(), doubler()); for_each(v1.begin(), v1.end(), myprinter())
    for_each(s1.begin(), s1.end(), doubler()); for_each(s1.begin(), s1.end(), myprinter());
    return 0;
}

My output from the program is as follows: 3, 9, 0, 2, 1, 4, 5, 0, 1, 2, 3, 4, 5, 9,

I was expecting each of the values to be doubled, but for some reason the for-each statement with doubler() did not do anything.

2 Answers2

0

Your operator passes a by value, making a copy of it. Take a reference instead.

void operator() (A & a) { a.setA(a.getA() * 2); }
//        Add this ^

Edit: It's been indicated in the comments that you are applying your operation on an std::set. The elements of a set cannot be modified. See this answer for more information on why you cannot modify the elements in a set.

Community
  • 1
  • 1
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
0

In your doubler::operator () implementation, you're passing in the A object by value. It's doubling a copy of the A object, not the A object itself. You probably want:

struct doubler
{
    void operator() (A& a) { a.setA(a.getA() * 2); }
};
Chris Vig
  • 8,552
  • 2
  • 27
  • 35