How to find object in QList by specific field in c++98?

14,089

Solution 1

You can use the std::find algorithem.

you need to overload operator== for std::find

class SomeClass
{
     //Your class members...

public: 
    bool operator==(const SomeClass& lhs, const SomeClass& rhs)
    {
      return lhs.key == rhs.key;
    }
}

Then to find your key use:

if (std::find(myList.begin(), myList.end(), "mykey1") != myList.end())
{
   // find your key
}

Solution 2

if you need a pointer to the element you could use std::find_if:

#include <QCoreApplication>
#include <functional>
#include <QDebug>
#include <QString>

class SomeClass
{
    public:
        QString key;
        QString someData;
        int otherField;
        SomeClass(QString key, QString someData, int otherField)
        {
            this->key = key;
            this->someData = someData;
            this->otherField = otherField;
        }
        QString getKey() { return key; }
};


void print(QList<SomeClass*>& list)
{
    for(auto* someclass : list) {
        qDebug() << someclass->key << someclass->someData << someclass->otherField;
    }
    qDebug() << "";
}

int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    // create list
    QList<SomeClass*> list {
        new SomeClass("first",  "first_data", 100),
        new SomeClass("mykey1", "second_data", 100)
    };

    // print
    print(list);

    // search for element and if found change data
    auto itr = std::find_if(list.begin(), list.end(), [](SomeClass* someclass) { return someclass->getKey() == "mykey1"; });
    if(itr != list.end()) {
        (*itr)->someData = "NEW";
    }

    // print
    print(list);

    return app.exec();
}

Prints:

"first" "first_data" 100
"mykey1" "second_data" 100

"first" "first_data" 100
"mykey1" "NEW" 100
Share:
14,089

Related videos on Youtube

Dasd
Author by

Dasd

Updated on July 05, 2022

Comments

  • Dasd
    Dasd almost 2 years

    I have this simple class:

    class SomeClass
    {
       QString key;
       QString someData;
       int otherField;
       public:
          QString getKey() { return key };
    };
    

    And I have this list:

    QList<SomeClass*> myList;
    

    I want to check if myList contains object with key = "mykey1";

    for(int i = 0; i < myList.size(); i++)
    {
      if(myList.at(i)->getKey() == "mykey1") 
      { 
          //do something with object, that has index = i
      }
    }
    

    Is there any standard function, that will do cycle and return this object or index or pointer ? , so I don't need to use cycle

  • Simon
    Simon almost 7 years
    It will not work for C++98, Prior C++11 standards have no notion of lambda syntax.
  • Spiek
    Spiek almost 7 years
    yes you're right it's just working in C++11 and above, damn i overlooked completely the c++98 syntax limitation in the question...