首页 > 解决方案 > 如何通过一个或多个参数实现搜索

问题描述

我有一个对象容器。我需要通过多个参数来实现搜索(即用户可以选择不同的参数,我需要找到所有具有这些参数的对象)。

假设我们有一个容器std::vector<Person> v,其中存储了带有字段的对象:[姓名、年龄、职业]。

["Lucy", 18, "None"],
["Alex", 25, "Teacher"],
["Lucy", 18, "Student"],
["Lucy", 25, "None"],
["Sofia", 25, "None"].

例如,用户需要所有名为 Lucy 的人。他得到结果:

["Lucy", 18, "None"],
["Lucy", 18, "Student"],
["Lucy", 25, "None"].

现在用户想要找到 18 岁的名字为 Lucy 的人。他会得到结果:

["Lucy", 18, "None"],
["Lucy", 18, "Student"].

现在他需要25岁没有职业的人。

["Lucy", 25, "None"],
["Sofia", 25, "None"].

进行搜索的字段的选择取决于用户的选择!他可以在 GUI 中选择搜索参数。

我想我需要一些比较器,但不知道它应该是什么样子。

template<typename _Comp>
struct Person
{
    std::string name;
    int age;
    std::string profession;
};

标签: c++

解决方案


我想你有一个

struct Person {
    std::string name;
    unsigned age;
    std::string profession;
};

和一个填充了一些数据的向量

  std::vector<Person> persons{ {"Lucy", 18, "None"},
                             {"Alex", 25, "Teacher"},
                             {"Lucy", 18, "Student"},
                             {"Lucy", 25, "None"},
                             {"Sofia", 25, "None"}};

只需编写一个循环并检查条件:

std::vector<Person> select_by_name(const std::vector<Person>& persons,const std::string name){
    std::vector<Person> result;
    for (const auto& p : persons) if (p.name == name) result.push_back(p);
    return result;
}

...类似于ageprofession...

如果您愿意,可以改用算法:

std::vector<Person> select_by_name2(const std::vector<Person>& persons,const std::string name){
    std::vector<Person> result;
    auto equal_name = [name](const Person& p) { return name == p.name; };
    auto copy_to = std::back_inserter(result);       
    std::copy_if(persons.begin(),persons.end(),copy_to,equal_name);
    return result;
}

这可以概括为将选择元素的 lambda 传递给函数,以便您可以使用相同的函数来选择name,ageprofession, 例如

template <typename F>
std::vector<Person> select_by(const std::vector<Person>& persons,F f){
    std::vector<Person> result;
    auto copy_to = std::back_inserter(result);       
    std::copy_if(persons.begin(),persons.end(),copy_to,f);
    return result;
}

使用与上面相同的 lambda,这将被这样调用

auto selected = select_by(persons,equal_name);

推荐阅读