使用向量搜索名称

时间:2013-11-25 08:37:11

标签: c++ vector polymorphism stl-algorithm

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

我曾经想过使用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;
            }

        }
    }
}

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

  

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

使用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

答案 2 :(得分:0)

应用程序会连续打印结果,因为您的条件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并提示用户空输入将导致程序退出。