Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I modify a C++ container's values while iterating over it?

Tags:

c++

containers

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.

like image 517
bodacydo Avatar asked Dec 17 '12 19:12

bodacydo


1 Answers

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/

like image 130
dlp Avatar answered Sep 29 '22 20:09

dlp