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

How do I return a Null Pointer in a function C++

本文关键字:返回 空指针 C++ 函数      更新时间:2023-10-16

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

代码:

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

您可以使用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;
}

如果您要搜索的名称不在第一个元素,那么您就不会在其他元素中搜索。

你需要做一些类似的事情

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算法。

看起来您只需要返回Null、nullptr或0。

代码项目

只需使用以下代码:

return NULL;