I am currently working on a bit of code that will search within a vector of type Person (which I have defined in the code and will show if needed). If it finds the person, it returns their name. This is currently working, but if it does not find the person, it is supposed to return a Null pointer. The problem is, I cannot figure out how to make it return a Null pointer! It just keeps either crashing the program every time.
Code:
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 herebreak; } else {//Not working Person* p = NULL; <---Here is where the error is happeningreturn p;}}}
Best Answer
You could use std::find_if algorithm:
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}
For C++03 version:
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;}
If the name you are searching for is not at the first element, then you are not searching in the rest of the elements.
You need to do something like -
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 NULLreturn NULL;
As Chris suggested, try using std::find_if
algorithm.
Looks like you just have to return Null, nullptr, or 0.
codeproject
Just use following code:
return NULL;