im是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";
}
}
这里有一个小代码,演示了如何搜索结构。它包含一个自定义搜索功能,还包含一个使用algorithm
中的std::find_if
的解决方案。
#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
的所有元素 - λ函数CCD_ 5。允许定义"动态"功能。你也可以添加一个自由函数CCD_;条形图";作为成员变量并定义CCD_ 7
注意注意小写/大写和空格。"Name Surname" != "name surname" != "name surname"
。