Code:
static int counter = 0;
int add(int x) {
counter++;
return ++x;
}
int main() {
vector<int> b;
b.push_back(1);
b.push_back(1);
b.push_back(1);
transform(b.begin(),b.end(),b.begin()+2,add);
for (vector<int>::iterator it = b.begin(); it != b.end(); it++)
cout << (*it) << endl;
cout << "counter: " << counter << endl;
}
For me this compiles with no warnings and prints out:
1
1
2
counter: 3
What is happening here in the transform function? How is it that add(…) gets called 3 times but b.end() is not overwritten? Is this undefined behavior?
Yes, it’s undefined behavior. It’s your responsibility to avoid running past the end of the vector, not the compiler’s.
What do you mean by, “
b.end()is not overwritten”? If you mean that you expected the vector to change length, then no, it didn’t, you can’t change a vector’s length this way.