CppPrimer icon indicating copy to clipboard operation
CppPrimer copied to clipboard

Exercise 9.28(The loop may not stop)

Open Yuanzidan081 opened this issue 1 year ago • 0 comments

The loop can't stop if there is a string in the list (type: forward_list) that can match to_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!

Yuanzidan081 avatar Oct 12 '23 00:10 Yuanzidan081