gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:42:29 36 4
gpt4 key购买 nike

我目前正在编写一些代码,这些代码将在一个类型为 Person 的 vector 中进行搜索(我已经在代码中定义了它,并且会在需要时显示)。如果它找到了这个人,它会返回他们的名字。这目前正在工作,但如果它没有找到人,它应该返回一个 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;
}

关于c++ - 如何在函数 C++ 中返回空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18413767/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com