Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
898 views
in Technique[技术] by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...