c++ - std::find not using my defined == operator -
i have simple class storing in vector pointers. want use find on vector failing find object. upon debugging doesn't seem call == operator i've provided. can 'see' object in debugger know there. code below uses copy of first item in list, still fails. way can make pass use mergeline* mlt = linelist.begin(), shows me comparing objects , not using equality operator @ all.
class mergeline { public: std::string linename; int startindex; double startvalue; double fidstart; int length; bool operator < (const mergeline &ml) const {return fidstart < ml.fidstart;} bool operator == (const mergeline &ml) const { return linename.compare( ml.linename) == 0;} }; class otherclass{ public: std::vector<mergeline*>linelist; std::vector<mergeline*>::iterator ll_iter; void dosomething( std::string linename){ // original version returned linelist.end() // mergeline * mlt // mlt->linename = linename; // version doesn't work either (i thought sure!) mergeline *mlt =new mergeline(*linelist.front()); ll_iter = std::find(linelist.begin(), linelist.end(), mlt); if (ll_iter == linelist.end()) { throw(exception("line not found in linelist : " + mlt->linename)); } mergeline * ml = *ll_iter; } };
cheers, marc
since container contains pointers , not objects, comparison between pointers. way pointers equal when point exact same object. you've noticed comparison operator objects never called.
you can use std::find_if
, pass comparison object use.
class mergelinecompare { mergeline * m_p; public: mergelinecompare(mergeline * p) : m_p(p) { } bool operator()(mergeline * p) { return *p == *m_p; } }; ll_iter = std::find_if(linelist.begin(), linelist.end(), mergelinecompare(mlt));
Comments
Post a Comment