这里截取了一小段代码,说明了如何搜索结构体。它包含自定义搜索功能以及使用 std::find_if
中的 algorithm
的解决方案。
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct Person
{
std::string name;
Person(const std::string &name) : name(name) {};
};
void custom_find_if (const std::vector<Person> &people,const std::string &name)
{
for (const auto& p : people)
if (p.name == name)
{
std::cout << name << " found with custom function." << std::endl;
return;
}
std::cout << "Could not find '" << name <<"'" << std::endl;
}
int main()
{
std::vector<Person> people = {{"Foo"},{"Bar"},{"Baz"}};
// custom solution
custom_find_if(people,"Bar");
// stl solution
auto it = std::find_if(people.begin(),people.end(),[](const Person& p){return p.name == "Bar";});
if (it != people.end())
std::cout << it->name << " found with std::find_if." << std::endl;
else
std::cout << "Could not find 'Bar'" << std::endl;
return 0;
}
由于您不熟悉 C++,因此该示例还使用了您可能还不熟悉的以下功能:
- 循环
for (const auto& p : people)
的范围基础。循环遍历 people
的所有元素。
- lambda 函数
[](const Person& p){return p.name == "Bar";}
。允许“即时”定义函数。您还可以添加一个免费函数 bool has_name(const Person &p) {return p.name == "Bar";}
或(更好)一个可以将“Bar”存储为成员变量并定义 operator()
的函子。
注意注意小写/大写和空格。 "Name Surname" != "name surname" != "name surname"
。
本文链接:https://www.f2er.com/1141641.html