c++codeblocksturbo-c++

C++ Search value through array of struct


im new to C++

i would like to search a variable entered through an array. the struct looks like this..

    struct Person
{
    string name;
    string phone;

    Person()
    {
        name = "";
        phone = "";
    }

    bool Matches(string x)
    {
        return (name.find(x) != string::npos);
    }



};

how can i search an entered value through that struct?

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";
    }
}

Solution

  • 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:

    Note Be careful with lower/upper case and whitespace. "Name Surname" != "name surname" != "name surname".