【问题标题】:list iterators incompatible with erasing列出与擦除不兼容的迭代器
【发布时间】:2020-04-25 11:03:03
【问题描述】:

这是我的代码:

std::list<User>::iterator it;
    while (it != allUsers.end())
    {
        if (it->getId() == userId)
        {
            allUsers.remove(*it);
            return *it;
        }
        else
        {
            it++;
        }
    }

我得到的错误:列表迭代器与擦除不兼容 为什么?

【问题讨论】:

  • remove之后的迭代器无效。您无法访问它。
  • 请复制并粘贴确切的消息。
  • 从列表中删除一个值会擦除被删除的元素,这会使引用该列表元素的迭代器无效。所以allUsers.remove(*it) 使it 无效。取消引用它(如return *it)`然后会导致未定义的行为。你的编译器告诉你(粗略地说)。
  • 显示完整的函数和User 类。制作minimal reproducible exampleit 是默认构造的,不会自动从allUsers.begin() 开始。
  • @Hee hee 迭代器 std::list::iterator it;未初始化。

标签: c++ list debugging


【解决方案1】:

您必须使用erase(),而不是remove(),才能使用迭代器从列表中删除元素:

while (it != allUsers.end()) {
    if (it->getId() == userId) {
        auto oldvalue = *it;
        allUsers.erase(it);
        return oldvalue;
    }
    it++;
}

【讨论】:

    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多