麻烦在对象列表上使用迭代器

Jus*_*tin 0 c++ iterator list

所以我有一个名为symbol的类,它由4个字符串组成,这些字符串都是公共的.我创建了这些列表,我想在此列表中查看.这就是我到目前为止所拥有的.我查找了迭代器方法,它说它支持+运算符,但是我得到了一个错误.

    bool parser::parse(list<symbol> myList){
    //Will read tokens by type to make sure that they pass the parse
    std::list<symbol>::const_iterator lookAhead = myList.begin();
    if ((lookAhead + 1) != myList.end)
        lookAhead++;
    for (std::list<symbol>::const_iterator it = myList.begin(); it != myList.end(); ++it){
        if (it->type == "") {

        }
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

尝试向lookAhead添加1时出错.为列表创建前瞻的有哪些好方法?

谢谢,宾克斯

Cam*_*ron 7

链表不支持随机访问迭代器,即您不能向其迭代器添加整数.

使用std::next(lookAhead)获取下一个迭代器来替代,或者std::advance(lookAhead, 1).这些函数知道正在传递什么类型的迭代器,并且如果可能的话将使用随机搜索(例如使用std::vector随机访问迭代器),或者手动前进(在这种情况下使用循环std::advance()),否则就像在这种情况下一样.

但是要小心地无条件地推进迭代器 - 前进的过程end()是不确定的!

您可以在此处阅读有关不同类别的C++迭代器的更多信息.

旁注:由于您按值传递整个列表,因此在传入时会复制整个列表.您可能希望通过引用传递它(list<symbol> const& myList).您还可以使用C++ 11 auto关键字简化代码,该关键字从初始化变量的表达式的类型中自动推导出类型:

bool parser::parse(list<symbol> const& myList){
    // Will read tokens by type to make sure that they pass the parse
    auto lookAhead = myList.begin();
    if (lookAhead != myList.end() && std::next(lookAhead) != myList.end())
        ++lookAhead;
    for (auto it = myList.begin(); it != myList.end(); ++it){
        if (it->type == "") {

        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)