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

2

6

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

Signification answered 13/8, 2017 at 7:51 Comment(2)
see #24206533Jael
Why not write your own function so that you don't have to "cycle" manually each time?Bossism
V
7

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
}
Vermicular answered 14/8, 2017 at 7:10 Comment(0)
C
6

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
Chapnick answered 14/8, 2017 at 7:39 Comment(2)
It will not work for C++98, Prior C++11 standards have no notion of lambda syntax.Vermicular
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...Chapnick

© 2022 - 2024 — McMap. All rights reserved.