Let’s say I’ve a vector<int> vals. I’m iterating over it and changing values to absolute:
for (vector<int>::iterator it = vals.begin(); it != vals.end(); ++it) {
if (*it < 0) *it = -*it;
}
Is this allowed? I’m not changing the size of the vector<int> so I don’t think it gets invalidated. I think I’m safe. I want to confirm this.
Yes, it’s safe. You aren’t changing the underlying storage. Keep in mind, it will not work if you pass the container as
constin a function like this:This site talks about this pretty well: http://www.cplusplus.com/reference/vector/vector/begin/