Search code examples
c++stringiteratormove

Does moving characters into string invalidate iterators?


So iterating over a string and using operator[] or insert to change characters can invalidate the iterator.

Is that also the case for an iteration like this?

std::string str = "ABCD";
for(auto&& c : str){
    for(int i = 0; i < 3; ++i){
        switch(c) {
            case 'A':
                c = 'B';
                break;
            case 'B':
                c = 'C';
                break;
            /*...*/
        }
        //do something
    }
}

This code works on gcc and msvc but I don't know if I can trust it. I'm using C++14.


Solution

  • You are modifying existing characters of string so it is completely safe. Iterators are invalidated when the size of the string storage may change, e.g. when you append a new character, there might be a need to allocate a bigger string buffer, so all the iterators pointing to previous buffer may become invalid.