0

I am someone who is new to Qt. I have a doubt how to conditionally iterate over a QList.

struct Data { QString Feature; QString Id; QString Result; }; QList<Data> myList; 

And I have the list like this :

List Preview

I want to get the items of the list where Feature="F1" and Result="pass" I need to get the count of ID in feature 1. Removing duplicates.

I am familiar with LINQ and C# List and its achievable in a single line of code in C#. But with QList I am a bit confused.

1
  • Do you need the number of "id" values that match the criteria or the count of how often each id occurs in the matches? I.e. do you need the output to be 1 (only Id1 matches the criteria) or a map like [ Id1 -> 3] (Id1 matches the criteria 3 times) Commented Jan 3, 2017 at 10:47

1 Answer 1

1

First of all you should not be using QList but rather QVector as it is more efficient in most cases. Unless you need QList because you interface with Qt API that expects it of course. Even then though QVector::toList would probably be better.

As for your problem, it can be one-liner in C++ as well:

QVector<Data> data{{"F1", "Id1", "Pass"}, //or QList<Data> if you really insist... {"F1", "Id1", "Pass"}, {"F1", "Id1", "Pass"}, {"F1", "Id2", "Fail"}, {"F1", "Id2", "Fail"}, {"F3", "Id3", "Pass"}, {"F3", "Id3", "Pass"}, {"F2", "Id4", "Pass"}, {"F2", "Id4", "Pass"}}; qDebug() << std::count_if(data.cbegin(), data.cend(), [](const Data &data) { return data.Feature == "F1" && data.Result == "Pass"; }); 

Prints 3.

Requires C++11 for the lambda but count_if itself does not.

To list all unique IDs that satisfy the condition it could still be a one-liner but it is starting to get messy:

QVector<Data> result; std::copy_if(data.cbegin(), data.cend(), std::back_inserter(result), [&result](const Data &data) { return std::find_if(result.cbegin(), result.cend(), [&data](const Data &d) { return d.Id == data.Id; }) == result.cend() && data.Feature == "F1" && data.Result == "Pass"; }); qDebug() << result.count(); 
Sign up to request clarification or add additional context in comments.

4 Comments

In your question says that you are starting to use Qt, so ask the answer to learn how to use QList.
@eyllanesc The code would be identical for QList so I do not understand your downvote or comment. Furthermore the OP did not state he is learning to use QList but that he is using it, most likely because he comes from C# where List is default container. I merely pointed out that it should not be considered default in Qt.
He says: "But in QList I am bit confused" and "I am some who is new to QT"
@eyllanesc And you deduced from it that he needs to use QList. He should NOT use it ever unless he has very good reason like need to pass it to Qt API. The point still stands - my code is identical for QList.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.