【问题标题】:how to check if a value exist in QList?如何检查QList中是否存在值?
【发布时间】:2020-07-08 09:17:31
【问题描述】:

我有一个类来保存客户的 ID 和他的名字。保存后,我将对象插入QList 并在桌子上查看它们。

我需要什么:

我需要检查客户是否已经添加到表中。

我的方法:

我正在尝试使用客户 ID 搜索列表,如果找到,我想更新他的记录,否则添加一个新记录。

代码应该是这样的。

bool customerExist = customersList.contains(customerID);

if (!customerExist) 
{
    customersList.append(customer)
}

【问题讨论】:

  • 看来QMap会更合适

标签: c++ qt qlist


【解决方案1】:

您可以通过以下方式在列表中搜索:

auto iterator = std::find_if(
  customersList.begin(), customersList.end(),
  [](MyObject x) { return x.myproperty() == customerID; }
);
if (iterator != customersList.end())

【讨论】:

    【解决方案2】:

    如果您需要定期通过 customerID 访问您的数据,我建议您使用 QMap<int, Customer*>。 (使用您的 customerID 类型作为键)

    如果客户数量越来越多,使用 QMap 会快得多。

    然后您可以执行以下操作::

    if (!myMap.contains(customerID))
    {
        myMap.insert(customerID, customer);
    }
    

    【讨论】:

    • 非常感谢,我已将 QList 更改为 QMap,它就像我需要的那样工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2020-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多