Here is a little code snipped that illustrates how to search a struct. It contains a custom search function and also a solution using std::find_if
from 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;
}
Since you are new to c++, the example also uses the following features you might not be familiar with, yet:
- range base for loop
for (const auto& p : people)
. Loopy through all elements of people
.
- lambda function
[](const Person& p){return p.name == "Bar";}
. Allows to define a function 'on-the-fly'. You could also add a free function bool has_name(const Person &p) {return p.name == "Bar";}
or (better) a functor which can store "Bar" as member variable and defines operator()
.
Note Be careful with lower/upper case and whitespace. "Name Surname" != "name surname" != "name surname"
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…