Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 821
Dasd Avatar asked Dec 18 '22 05:12

Dasd


1 Answers

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
}
like image 78
Simon Avatar answered Dec 24 '22 02:12

Simon