c++qtqlist

how to check if a value exist in QList?


I have a class to save the ID of customer and his name. After saving I'm inserting the object into a QList and viewing them on table.

What I need:

I need to check if the customer is already added to the table or not.

My approach:

I'm trying to search the list using the customer ID and if I find it I want to update his record otherwise add a new one.

The code should look something like this.

bool customerExist = customersList.contains(customerID);

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

Solution

  • If you need to access your data through a customerID regularly, I would recommend to use a QMap<int, Customer*>. (use as key the type of your customerID)

    Using a QMap will be much faster if the number of customers is getting large.

    Then you can do something like::

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