0

So I have the following code, which is supposed to use an iterator to replace an element in a vector if it matches some given value "old".

    using StringIter = std::vector<std::string>; 
using StringVec = std::vector<std::string>;
void replace(StringVec ref, std::string old, std::string replacement)
{
    for (StringIter::iterator it = ref.begin(); it != ref.end(); it++)
    {
        if (*it == old)
        {
            ref.erase(it); 
            ref.insert(it,replacement);
        }   
    }
}

However, I get the following runtime error: "vector emplace iterator outside range". I've tried changing the order of erase and insert, and using insert(it-1,...) instead, but it doesn't work. Haven't found any solution to this exact problem after an hour or so of googling.

matti1499
  • 25
  • 4
  • 3
    Seems like you just want `*it = replacement;` instead of calling `erase` and `insert` – Kevin May 24 '21 at 19:14
  • 1
    `ref.erase(it);` *invalidates* `it` and **all** iterators after it in the vector. You can't use any of them after this operation, including `end()` iterator. – SergeyA May 24 '21 at 19:15
  • 1
    The code also has a lot of oddities: `StringIter` is not an iterator, but a vector, `StringVec ref` is not a reference, both `old` and `replacement` should likely be `const references`, the whole snippet can be replaced with [std::replace](https://en.cppreference.com/w/cpp/algorithm/replace) – SergeyA May 24 '21 at 19:17
  • I know this can be done simpler, but it is for an assignment where we're specifically asked to use the erase() and insert() member functions. – matti1499 May 24 '21 at 19:20

0 Answers0