0

Hello i'm curently coding a fonction that erase element from a vector of pointer(to class object), but i cant quite make it work.

I get this error error: no matching function for call to ‘std::vector<biblio::Reference*>::erase(biblio::Reference*&)’

std::vector<Reference*> m_vReferences; //Reference is a class 
for ( auto iter : m_vReferences) //Loop for on every pointer to a class object { if (iter->reqId () == p_id) //Check if the id of the class object is the id we want { m_vReferences.erase (iter); //Erase the pointer in the vector of pointer } else { throw EmptyReferenceException (iter->reqFormatedReference ()); //An exception } } 
6
  • 2
    en.cppreference.com/w/cpp/container/vector/erase takes an iterator, you're giving it an element. Commented Dec 8, 2021 at 22:41
  • 1
    Vector does not support erasing by keys, cause there are no keys. Commented Dec 8, 2021 at 22:41
  • 1
    You might be looking for std::erase_if (from C++20 on). Commented Dec 8, 2021 at 22:45
  • 4
    for ( auto iter : m_vReferences) is an example of bad naming. iter variable is not an iterator, it is an object of type Biblio::Reference*. Commented Dec 8, 2021 at 22:49
  • 2
    worse... it's an UB. erase returns new iterator, iterator given to it becomes invalid and shouldn't be incremented Commented Dec 8, 2021 at 23:56

1 Answer 1

3

Don't use auto-range loops when you want to delete the element from the container. I would use std::remove_if as it is available in standard library.

m_vReferences.erase(std::remove_if(m_vReferences.begin(),m_vReferences.end(),[p_id](Reference* x){ return x->reqId() == p_id; }),m_vReferences.end()); 

or you may loop through vector find at which index is the element you want to delete and use erase function from vector.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.