迭代器跳过循环

Iterator skipping for loop

我正在使用列表容器,但在使用 for 循环时遇到问题。我不明白为什么要跳过,我正在打印一些 "Label" 以查看直到哪个部分在工作并且唯一正在打印的是 "First if " 然后跳过所有其他部分。为什么会出现这个问题?

页眉

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

}

问题是对于空列表,.begin().end() 将 return 相同的值。我建议您在进入循环之前插入第一个值或空值。像下面这样尝试。

    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;
    }