如何检查QList中是否存在值

how to check if a value exist in QList?

本文关键字:是否 存在 QList 何检查 检查      更新时间:2023-10-16

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

我需要什么:

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

我的方法:

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

代码应该是这样的。

bool customerExist = customersList.contains(customerID);
if (!customerExist) 
{
customersList.append(customer)
}

您可以通过执行以下操作在列表中进行搜索:

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

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

如果客户数量越来越多,使用QMap的速度会更快。

然后你可以做一些类似的事情::

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