c++ - 如何通过一个或多个参数实现搜索
问题描述
我有一个对象容器。我需要通过多个参数来实现搜索(即用户可以选择不同的参数,我需要找到所有具有这些参数的对象)。
假设我们有一个容器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;
};
解决方案
我想你有一个
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;
}
...类似于age
和profession
...
如果您愿意,可以改用算法:
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
,age
或profession
, 例如
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);
推荐阅读
- javascript - Nodemailer 在路由文件夹中不起作用
- azure - 将 35GB 的 redis 从一个实例复制到另一个实例的最快方法(在 Azure 标准中)
- server - 无法为 FTP 文件传输设置远程文件时间
- javascript - MongoDB 插入异步问题
- python - 使用 Pycharm 的 py.test 运行器时如何将插件选项传递给 py.test?
- java - 如何实例化包中类型的 StructDescriptor 对象
- codeception - 我可以在代码接收中结合单元测试和验收测试吗?
- java - 有没有办法禁用 java.util.logging 并稍后重新启用它?
- c# - EF DbContext 处置
- docker - Docker Swarm 不断创建和关闭实例