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 const
in a function like this:
void doSomething(const vector<int>& vals)
This site talks about this pretty well: http://www.cplusplus.com/reference/vector/vector/begin/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With