Reputation: 105
While debugging my code, I've noticed a change in stored iterator, pointed to begin(), after every 4 or 5 call to += operator on a string (what it points to, isn't even in the string itself!). Here's what my code looks like:
for (auto ch=word.begin(); ch!=word.end(); ++ch) {
// on a condition, the following loop starts
// ch == word.begin()
for (int i=0; ...) {
string_view tmp = arr[i];
word += tmp;
}
// ch is no longer equal to word.begin()
}
While reassigning ch to word.begin()
after second loop fixed my issue, I'm wondering why this has happened. I couldn't find anything on the internet.
Upvotes: 1
Views: 180
Reputation: 150
When you extend cointainers like vector or string sometimes they may to reallocate their memory to new location - so it change address. They need continuous memory, beacuse aren't list with pointer to next element.
Iterator move through continous memory addresses. Next element is address+1.
So, at begining, your first element in string is stored in address X. But you add few letters, what results in reallocating container to new location. Now, your string isn't stored in address X, but address Y. Despite this, your iterator still point to address X.
You can't use iterator without reinitallizing, when adding or removing elements, because these operation cause iterators to be invalidated.
Upvotes: 3