CppPrimer
CppPrimer copied to clipboard
Exercise 9.28(The loop may not stop)
The loop can't stop if there is a string in the list
(type: forward_listto_find
(type: string)
void find_and_insert(forward_list<string> &list, const string& to_find, const string& to_add)
{
auto prev = list.before_begin();
auto size = std::distance(list.begin(), list.end());
for (auto curr = list.begin(); curr != list.end(); prev = curr++)
if (*curr == to_find) list.insert_after(curr, to_add);
if (size == std::distance(list.begin(), list.end())) list.insert_after(prev, to_add);
}
The code should be modified in this line:
if (*curr == to_find) curr = list.insert_after(curr, to_add);
best regards!