使用矢量搜索名称

searching for name using vectors

本文关键字:搜索      更新时间:2023-10-16

如何搜索用户从程序中输入的名称?目前我有这个供我搜索,但每当程序找到选定的学生时,它就会像一个永无止境的循环一样不停地打印。我也使用多态性,因为学生被分为本地和国际学生。

我曾想过使用stl算法在学生中迭代,但我对stl很陌生。我试过一些来自互联网的例子,但当应用到我的程序时,它总是给我一个错误。

主要功能

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

如何搜索用户从程序中输入的名称?

使用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版本:

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

因为如果找到了学生,则打印名称,然后中断for-循环,并且当重新评估while条件时,由于searchName没有更改,该条件仍然为true。您应该将searchName设置为长度为0的字符串,或者使用其他条件来中断while

由于条件while(searchName.length() != 0)仍然有效,应用程序会连续打印结果。当您编写break时,您会突破for循环for (int i = 0; i < s.size(); i++)。例如:

while (true) {
    for (;;) {
        std::cout << "I get printed forever, because while keeps calling this for loop!" << std::endl;
        break;
    }
    // Calling break inside the for loop arrives here
    std::cout << "I get printed forever, because while's condition is always true!" << std::endl;
}

如果你试图允许用户不断搜索学生集合(即"找到/没有找到学生,找到另一个?"),你需要包括这些行。。。

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

在while循环中,以便修改searchName并提示用户空输入将导致程序退出。