如何在 C++ 函数中返回空指针

Sil*_*los 3 c++ null pointers vector

我目前正在编写一些代码,这些代码将在 Person 类型的向量中进行搜索(我已在代码中定义了该向量,并且将在需要时显示)。如果找到这个人,就会返回他们的名字。这目前正在工作,但如果它没有找到该人,它应该返回一个空指针。问题是,我不知道如何让它返回空指针!它只是每次都会使程序崩溃。

代码:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

bil*_*llz 5

您可以使用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
}
Run Code Online (Sandbox Code Playgroud)

对于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;
}
Run Code Online (Sandbox Code Playgroud)