问题描述
我是 C++ 新手
我想搜索通过数组输入的变量。结构看起来像这样..
struct Person
{
string name;
string phone;
Person()
{
name = "";
phone = "";
}
bool Matches(string x)
{
return (name.find(x) != string::npos);
}
};
如何通过该结构搜索输入的值?
void FindPerson (const Person people[],int num_people)
{
string Searchedname;
cout<<"Enter the name to be searched: ";
cin>>Searchedname;
if(Searchedname == &people.name)
{
cout<<"it exists";
}
}
解决方法
这里截取了一小段代码,说明了如何搜索结构体。它包含自定义搜索功能以及使用 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"
。