Does moving characters into string invalidate iterators?

好久不见. 提交于 2021-02-08 07:50:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!