QList中,如果要根据某个类的属性值来查找对象,可以使用std::find_if函数来实现。这两种方法都需要提供一个谓词函数(Predicate Function),用于判断目标对象是否符合条件。

假设我们有一个Person类,其中包含nameage两个属性,代码如下所示:

class Person {
public:
    QString name;
    int age;
};

现在有一个QList<Person>类型的对象,我们想根据name属性来查找对象。可以按以下步骤进行操作:

 1、调用std::find_if函数来查找目标对象。

// 使用 std::find_if
auto it = std::find_if(personList.begin(), personList.end(), [=](const Person& p) {
    return p.name == "张三";
});
if (it != personList.end()) {
    // 找到了目标对象
    Person& targetPerson = *it;
}

 

2、通过std::copy_if函数来查找满足条件的对象集合

QList<Person> targetList;
// 使用 std::copy_if 将源容器中满足条件的元素复制到目标容器
std::copy_if(personList.begin(), personList.end(), std::back_inserter(targetList), [=](const Person& p) {
    return p.name == "张三";
});

 

3、std::transform函数将集合中的某个属性值的集合拷贝到另一个集合里

 QList<int> targetAgeList;
 std::transform(personList.begin(), personList.end(), std::back_inserter(targetAgeList), [=](const Person& p) {
        return p.age;
  });