mardi 28 février 2017

Changing vector inside std::for_each on the same vector

I want to figure out if it is allowed to change the vector inside for_each. Consider the code:

std::vector<int> v;
for (int i = 0; i < 10; i++) v.push_back(i);

for (auto &i : v) std::cout << i << " ";
std::cout << std::endl;
std::transform(v.begin(), v.end(), std::back_inserter(v),
          [](auto i) { return i;});

for (auto &i : v) std::cout << i << " ";
std::cout << std::endl;

I expect to expand vector with elements which are base on exist vector contents. Here is the output:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 

But if I replace begin and end with rbegin and rend correspondingly the output is following:

0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 9 8 7 6 5 4 3 2 0 0

I get unexpected 0 instead of 1 in a position before last. This makes me wonder if this code is a UD per se, and I should not rely on correct output with forward iterators.

Aucun commentaire:

Enregistrer un commentaire