c++ - 迭代器跳过循环

标签 c++ stl iterator

我正在使用列表容器,但在使用 for 循环时遇到问题。我不明白为什么要跳过,我正在打印一些“标签”以查看直到哪个部分在工作并且唯一正在打印的是“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() 将返回相同的值。我建议您在进入循环之前插入第一个值或空值。像下面这样尝试。

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

关于c++ - 迭代器跳过循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31274290/

相关文章:

c++ - STL 按多个参数排序 C++

java - 如何通过迭代器在特定条件下从Set中删除元素?

c++ - 前向迭代器 iterator_traits::reference 的要求

c++ - OpenGL 相机 vector

c++ - 使 QGraphicsView 大小适合

C++ std::string 初始化的不正确行为

c - C 中带有 char 迭代器的 FOR 循环是否可行?

c++ - 如何通过自动返回类型返回引用?

c++ - 我可以在两个不同的类实例中使用 boost asio 套接字引用吗?

c++ - 在 C++ 中使用 std::getline() 的签名错误