2013-08-24 39 views
2

我目前正在研究一些代碼,這些代碼將在Person類型的矢量(我已在代碼中定義並將在需要時顯示)中進行搜索。如果發現該人,則返回他們的姓名。這是目前正在工作,但如果它沒有找到該人,它應該返回一個空指針。問題是,我無法弄清楚如何讓它返回一個空指針!它只是保持每次崩潰的程序。如何返回函數中的空指針C++

代碼:

Person* lookForName(vector<Person*> names, string input) 
{ 
    string searchName = input; 
    string foundName; 
    for (int i = 0; i < names.size(); i++) { 
     Person* p = names[i]; 
     if (p->getName() == input) { 
      p->getName(); 
      return p; //This works fine. No problems here 
      break; 
     } else { 
      //Not working Person* p = NULL; <---Here is where the error is happening 
      return p; 
     } 
    } 
} 
+0

只是返回 '0'(零)。這是C++中空指針的表示形式。 –

+3

'nullptr'會更好,但嚴重的是,使用'std :: find_if',最好是不帶指針的'std :: vector '。 – chris

+0

哦,你也沒有初始化P,所以在任何情況下它都會有一個值!= 0.請記住,C++不會自動初始化它的變量。 –

回答

2

你可以使用std::find_if算法:

Person * lookForName(vector<Person*> &names, const std::string& input) 
{ 
    auto it = std::find_if(names.begin(), names.end(), 
       [&input](Person* p){ return p->getName() == input; }); 


    return it != names.end() ? *it : nullptr; // if iterator reaches names.end(), it's not found 
} 

對於C++ 03版:

struct isSameName 
{ 
    explicit isSameName(const std::string& name) 
    : name_(name) 
    { 
    } 

    bool operator()(Person* p) 
    { 
     return p->getName() == name_; 
    } 
    std::string name_; 
}; 

Person * lookForName(vector<Person*> &names, const std::string& input) 
{ 
    vector<Person*>::iterator it = std::find_if(names.begin(), names.end(), 
          isSameName(input)); 


    return it != names.end() ? *it : NULL; 
} 
+0

感謝您的想法!儘管一個簡單的問題是,我將這些代碼粘貼到我現有的代碼的位置,並且它提出了「錯誤:'它沒有命名一個類型。」我應該刪除部分代碼嗎?還是我需要在其他地方宣佈它? – Silmarilos

+0

@Silmarilos:看來你正在用C++ 03編譯器編譯,或者用C++ 03模式編譯。上面的解決方案取決於一些C++ 11的特性,即'auto'類型推斷,lambdas和'nullptr'。你可以手動展開循環,或者定義一個函子外(函數外部)來使用'std :: find_if'。 –

+0

讓它工作!感謝百萬人的幫助! – Silmarilos

0

看起來你只需要返回NULL,nullptr,或0

codeproject

0

只需使用下面的代碼:

return NULL; 
1

如果你正在搜索的名稱不在第一個元素,那麼你不在r中搜索est的元素。

你需要做這樣的事情 -

for (int i = 0; i<names.size(); i++){ 
    Person* p = names[i]; 
    if (p->getName() == input) { 
     return p; 

     // Placing break statement here has no meaning as it won't be executed. 
    } 
} 

// Flow reaches here if the name is not found in the vector. So, just return NULL 
return NULL; 

就像Chris建議,嘗試使用std::find_if算法。