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.