如何在函数C++中返回空指针
How do I return a Null Pointer in a function C++
我目前正在编写一段代码,该代码将在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;
相关文章:
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 如何在C++中返回矢量指针?
- 运行时错误:引用绑定到类型为"int"的空指针
- 在函数内初始化无符号字符指针将返回空指针
- Freeimage FreeImage_ConvertTo24Bits 返回空指针
- 为什么 weak_from_this() 总是返回空的弱指针
- 无法将键设置为"redisClusterCommand()"返回空指针
- opus_encoder_create() 返回一个空指针
- C++返回一个空指针数组
- C++从另一个类调用(向量)指针返回空大小
- 如何返回列表成员 c++ 的空指针
- 如何在函数C++中返回空指针
- 返回空指针的用户定义运算符new
- 在返回地址之前清空指针
- 在C++中返回空状态(NULL)的对象,而不返回指针
- 我可以在c++方法中返回空指针吗?
- Dynamic_cast返回空指针
- 返回语句返回一个空指针值而不是期望的值
- C++返回空指针
- 什么是返回非空指针的正确方法