mardi 18 août 2020

std::vector Error shows up: "Cannot increment a vector past the end", while wanting to erase specific element

I have a vector of classes, the class has a string name, among other private fields.

I want to implement a void delete(string name) function, which looks for the element based on the string (each class in a vector has a unique name).

However after simple testing, it gives me an error "Cannot increment past the end".

This is my function:

void delete_member(string member_name)
{
    int count = 0;

    for (auto it = member_list.begin(); it != member_list.end(); ++it, ++count)
        if (it->get_name() == member_name)
            member_list.erase(member_list.begin() + count);
}

As far as I have searched for an answer, it seems that the iterator shouldn't go past the .end() of the vector.

What is the flaw here? I am using the same loop to iterate over a vector for add_member(Member m) function which works completely fine

Aucun commentaire:

Enregistrer un commentaire