2013-11-25 81 views
0

如何搜索用戶從程序中輸入的名稱?目前我有這個用於我的搜索,但每當程序找到選定的學生,它會像不斷結束的循環打印不停。即時通訊也使用多態性,因爲學生分爲本地和國際學生。使用矢量搜索名稱

我想過使用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; 
      } 

     } 
    } 
} 
+0

聽說find/find_if? http://en.cppreference.com/w/cpp/algorithm/find – billz

回答

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 
+0

[&searchName](const clsStudent * student) 這行代碼是做什麼的? –

+0

@AlexiusLim它是一個[lambda函數](http://en.cppreference.com/w/cpp/language/lambda),它通過引用捕獲'searchName',並將一個'clsStudent *'作爲參數。 – juanchopanza

+0

自動不似乎在這裏工作。我的編譯器給了我一個錯誤,說它沒有命名類型 –

0

因爲如果學生被發現,你打印的名字,然後打破for -loop,當while條件重新評估仍然是正確的,因爲searchName還沒有改變。您應該將searchName設置爲長度爲0的字符串,或者使用其他一些條件來突破while

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; 

...爲了修改searchName並提示一個空的輸入將導致程序退出的用戶while循環中。

+1

感謝您的解釋。 –