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

Dasd picture Dasd · Aug 13, 2017 · Viewed 12k times · Source

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

Answer

Simon picture Simon · Aug 14, 2017

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
}