mardi 29 septembre 2015

Why does the value assigned by get<>() in my code change outside the construct?

Why is the output of statement 2 different from that of statement 1?

// a is of type vector < tuple <int, int> >

for (auto i: a)
{
    get<0>(i)+=get<1>(i);                                       
    cout << get<0>(i) << " " << get<1>(i) << endl;              // 1
}

for (auto i: a) cout << get<0>(i) << " " << get<1>(i) << endl;  // 2

Suppose that initially, a contains [7, 3] , [9, 1]

Then 1 outputs

10 3
10 1

whereas 2 outputs

7 3
9 1

In short, the loop enclosing statement 1 seems to have no effect.

I think it has something to do with my usage of auto and not using *i to change the value, but I don't think that we can use *i in get.

Aucun commentaire:

Enregistrer un commentaire