How do I return a Null Pointer in a function C++ -
i working on bit of code search within vector of type person (which have defined in code , show if needed). if finds person, returns name. working, if not find person, supposed return null pointer. problem is, cannot figure out how make return null pointer! keeps either crashing program every time.
code:
person* lookforname(vector<person*> names, string input) { string searchname = input; string foundname; (int = 0; < 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 error happening return p; } } }
you use std::find_if algorithm:
person * lookforname(vector<person*> &names, const std::string& input) { auto = std::find_if(names.begin(), names.end(), [&input](person* p){ return p->getname() == input; }); return != 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 = std::find_if(names.begin(), names.end(), issamename(input)); return != names.end() ? *it : null; }
Comments
Post a Comment