c++ - How can I findan element in a list of pointers to a custom class -
background: i'm trying implement chess game. implementation follows( -> means each piece contains point) board -> (list of) piece -> point
generally, problem have list of pointers custom class (piece). want find piece based on 1 of it's fields (his point - located).
if seek find him this:
piecelist::const_iterator itpiece = find(_onepieces.begin(),_onepieces.end(),constsearchpiece); i believe wrong reply since what's happening comparing cell both elements pointing rather contents.
note: i've created operator== custom classes (piece , point). note: need piece const since it's located in const function.
i've tried implementing search function of own:
piecelist::const_iterator constpiecefind(piecelist plist, piece p) const{ piecelist::const_iterator iter; for( iter =plist.begin(); iter !=plist.end(); iter++){ if (**iter == p) homecoming iter; } homecoming plist.end(); } while function works fine , finds the desired piece, when check iterator calls function - it's blank.
what should prepare this?
your function takes plist argument by value. means piecelist container copied when passed function, , iterators used within constpiecefind refer local re-create of container. re-create gets destroyed when function returns, , returned iterator no longer points valid memory. alter function takes plist argument by reference.
piecelist::const_iterator constpiecefind(piecelist const& plist, piece p) const // ^^^^^^ you may want same sec argument prevent unnecessary copy, though not necessary code work.
c++ find std stdlist
No comments:
Post a Comment