c++ - 根据 id 从列表中删除结构

标签 c++ list struct

我已经创建了一个函数来执行此操作:

void Server::removeClient(unsigned short value) {
    std::list<Client>::iterator itri = clients.begin();
    while (itri != clients.end()) {
        if (itri->id == value) {
            itri = clients.erase(itri);
        } else {
            ++itri;
        }
    }
}

但出现错误:

list iterator not incrementable

我一直在寻找类似的问题,例如 this one那说我不应该在我调用删除后增加我的迭代器,告诉提问者他们应该把他们的迭代器增量放在我有的 else 语句中。

而且我知道这种问题已经被问了很多,但我真的很困惑。

完整文档如下:

Server.h

Server.cpp

注意我的 C++ 文件,我复制粘贴了 mpiatek 的问题链接答案,以额外确保我的代码是正确的。注释掉的代码和当前代码都不起作用。

我还尝试了 user4581301 建议的 remove_if:

clients.erase(
    std::remove_if(clients.begin(), clients.end(), [&](Client const & c) {
    return c.id == value;
}),
    clients.end());

我从 this question. 得到代码它不起作用并返回相同的错误。

最佳答案

我认为问题不在您显示的代码中,而在调用函数中。

您在此代码中调用您的 removeClient:

   for (Client &c : clients) {
        c.timeSinceLastPacket+= dt;
        if (c.timeSinceLastPacket.asSeconds() > 10) {
            std::cout << c.id << " has timed out!" << std::endl;
            removeClient(c.id);
        }
    }

一旦 removeClient 完成它的工作,您的 for 循环正在使用的(隐藏的)迭代器就会失效并且 for 循环无法继续。

您最好只在外循环中使用迭代器并通过迭代器删除,而不是再次通过 ID 查找。

最好使用评论中建议的类似 std:remove_if 的东西

关于c++ - 根据 id 从列表中删除结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42355071/

相关文章:

c++ - Typedef-name 与 C++ 中的 struct 标记冲突

C++11:可变同质非 POD 模板函数参数?

c# - 无法转换名单

python - for循环与python中的子列表

object - 类型断言非简约

将结构复制到相同类型结构的数组中

C++理解拷贝构造函数

c++ - 模仿boost lexical_cast操作

c++ - 如果编译器不支持,将可变参数传递给 lambda 表达式的解决方法

python - 如何将元组按时间间隔排序