问题
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.
回答1:
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.
回答2:
You can modify any element of a collection without invalidating its iterators. A string is a collection of characters, so this guarantee applies, including assigning via operator[]
(contrary to the claim in the question). Modifying the value of a character in a string using a reference, as in the same code, is well-defined and the results are predictable.
What you can't do is add or remove elements, so you must not re-use iterators after functions such as replace
or operator+=
.
来源:https://stackoverflow.com/questions/44883312/does-moving-characters-into-string-invalidate-iterators