将字符移动到字符串中会使迭代器无效吗? [英] Does moving characters into string invalidate iterators?
问题描述
因此遍历字符串并使用operator[]
或插入以更改字符可以使迭代器无效.
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
}
}
此代码适用于gcc和msvc,但我不知道我是否可以信任它.我正在使用C ++ 14.
This code works on gcc and msvc but I don't know if I can trust it. I'm using C++14.
推荐答案
您正在修改字符串的现有字符,因此它是完全安全的.当字符串存储区的大小可能更改时,例如,迭代器无效.当您添加新字符时,可能需要分配更大的字符串缓冲区,因此所有指向先前缓冲区的迭代器都可能无效.
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.
这篇关于将字符移动到字符串中会使迭代器无效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!