KillerPunk
KillerPunk

Reputation: 123

Iterator skipping for loop

I'm working with list container but I'm facing a problem when I use the for loop. I don't understand why is skipping, I'm printing some "Label" to see until which part is working and the only one that is printing is "First if " and then is skipping all the others. Why is that problem happening?

Header

class CRoute
{
    private:
        vector<CWaypoint> m_pWaypoint;
        vector<CPOI*> m_pPoi;
        CPoiDatabase* m_pPoiDatabase;
        list<CWaypoint*>m_pRoute;
        CWpDatabase* m_pWpDatabase;

    public:
        void connectToPoiDatabase(CPoiDatabase* pPoiDB);
        void connectToWpDatabase(CWpDatabase* pWpDB);
        void addPoiAndWp(string namePoi, string afterWp);

};

Cpp

void CRoute::addPoiAndWp(string namePoi, string afterWp)
{
    CPOI* poi = m_pPoiDatabase->getPointerToPoi(namePoi);

    list<CWaypoint*>::iterator pos1;

    if( (m_pWpDatabase != 0) && (poi != 0))
    {
        cout << "First if " << endl; // this is printed

        for(pos1 = m_pRoute.begin(); pos1 != m_pRoute.end(); pos1++) //here is skipping all
        {
            cout << "It's in the for loop" << endl;

            if( (*pos1)->getName() == afterWp)
            {
                cout << "Waypoint found! " << endl;
                list<CWaypoint*>::iterator pos2 = pos1;
                m_pRoute.insert(++pos2,poi);
            }

            cout << "Before leave the loop" << endl;
        }
    }
    else
    {
        cout << "WP not found / DB not connected " << endl;
    }
        cout << "Waypoint not found " << endl; // This is also printed

}

Upvotes: 0

Views: 174

Answers (1)

KeximusMaximus
KeximusMaximus

Reputation: 30

The issue is that for an empty list, .begin() and .end() will return the same value. I'd suggest you insert either the first value or a null value before you enter the loop. Try like below.

    if(/*pos1 is a valid position*/) {
          m_pRoute.insert(pos1);
    }
    for(pos1 = m_pRoute.begin(); pos1 != m_pRoute.end(); pos1++) //here is skipping all
    {

        cout << "It's in the for loop" << endl;
        if( (*pos1)->getName() == afterWp)
        {
            cout << "Waypoint found! " << endl;
            list<CWaypoint*>::iterator pos2 = pos1;
            m_pRoute.insert(++pos2,poi);
        }

        cout << "Before leave the loop" << endl;
    }

Upvotes: 1

Related Questions