Search code examples
c++vectorpolymorphismstl-algorithm

searching for name using vectors


how do i search for a name that has been entered by the user from the program? Currently i have this for my search but whenever the program found the selected student, it will print non-stop like a never ending loop. im also using polymorphism for this, as student is categorized into local and international student.

I've thought of using the stl algorithm to iterate through the students but im quite new to stl. I've tried some examples from the internet but it always gave me an error when applied to my program.

main function

int main()
{
    clsUniversityProgram objProgram[3];

    for (int x = 0; x < 3; x++)
    {
        objProgram[x].programInfo();
    }

    vector <clsStudent*> student;
    addStudents(student, objProgram);
    searchStudent(student);
    return 0;
}


void searchStudent(const vector <clsStudent*>& s)
{
    string searchName;
    const clsStudent *foundStudent;

    cout << "\nEnter student name to search for. [ENTER] terminates" << endl;
    cin >> searchName;

    if (s.size() == 0)
        cout << "There is 0 student in the database.";

    while(searchName.length() != 0)
    {
        for (int i = 0; i < s.size(); i++)
        {
            if (s[i]->getName() == searchName)
            {
                cout << "Found " << searchName << "!";
               // s[i]->print();
                break;
            }
            else
            {
                cout << "No records for student: " << searchName;
                cout << "\nEnter student name to search for. [ENTER] terminates" << endl;
                cin >> searchName;
            }

        }
    }
}

Solution

  • how do i search for a name that has been entered by the user from the program?

    Using std::find_if:

    auto it = std::find_if(s.begin(), 
                           s.end(),
                           [&searchName](const clsStudent* student)
                           { return student->getName() == searchName; });
    if (it != s.end()) {
      // name was found, access element via *it or it->
    else {
      // name not found
    }
    

    C++03 version:

    struct MatchName
    {
      MatchName(const std::string& searchName) : s_(searchName) {}
      bool operator()(const clsStudent* student) const
      {
        return student->getName() == s_;
      }
     private:
      std::string s_;
    };
    
    
    vector<clsStudent*>::iterator it = std::find_if(s.begin(), 
                                                    s.end(),
                                                    MatchName(searchName));
    
    // as before