Search code examples
c++pointersc++11runtime-errorstdlist

C++ How can I remove pointers refering to the same element in two different std::lists?


I am new in programming c++, so please don't be angry with me if my source code is not exactly brilliant.

I have to write a programm to handle with nodes and edges in a graph for my studies.

I have 2 std::lists in my source code. The first one is to store general Nodes and the other one for saving the kind class of my nodes called ArticleNodes. In general, all elements are pointers to the created objects.

To figure out whether one object is the same in the other list I save the memory address and compare it to the elements on the second list. If there is a match the second element will be deleted.

Now I'd like to delete one element in both lists:

void Graph::deleteNode(unsigned int nodeNumber)
{
    list<Node*>::iterator it = m_nodes.begin();
    ArticleNode* pCurrentArticleNode;
    for(unsigned int i=1; i<nodeNumber; i++) { it++; }

    Node* pCurrentNode = (*it);

    for (list<ArticleNode*>::iterator itArticle = m_articlenode.begin(); itArticle != m_articlenode.end(); itArticle++)
    {
        pCurrentArticleNode = (*itArticle);
        if(pCurrentNode==pCurrentArticleNode) { m_articlenode.remove(pCurrentArticleNode); }
    }

    m_nodes.remove(pCurrentNode);

    delete pCurrentNode;
    delete pCurrentArticleNode;
}

I can compile this, but when I call the function, my programm just exits with return 1. Actually, I figured out that the remove-command in the if-clause is the problem. Why does that not work??


Solution

  • You should use algorithms more than doing everything manually:

    void Graph::deleteNode(unsigned int nodeNumber)
    {
        assert (nodeNumber < m_nodes.size());
    
        auto it = std::next( m_nodes.begin(), nodeNumber - 1 );
    
        auto itArticle = std::find( m_articlenode.begin(), m_articlenode.end(), *it );
        if( itArticle != m_articlenode.end() )
            m_articlenode.erase( itArticle );
    
        delete *it;
        m_nodes.erase(it);
    }
    

    Btw your code deletes the same object twice.