Search code examples
c++findstdstdlist

How can I findan element in a list of pointers to a custom class


Background: I'm trying to implement a chess game. The implementation is as follows( -> means that each piece contains a Point) Board -> (list of) Piece -> Point

Generally, my problem is that I have a list of pointers to a custom Class (Piece). I want to find a certain piece based on one of it's fields (his Point - where is he located).

if I try to find him like this:

PieceList::const_iterator itPiece = find(_onePieces.begin(),_onePieces.end(),constSearchPiece);

I believe I get the wrong answer since what's happening is that I am comparing the cell to which both elements are pointing to rather than their contents.

Note: I've created a operator== for my custom classes (Piece and Point). Another Note: I need to get the piece as const since it's located in a const function.

I've tried implementing a search function of my 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)
            return iter;
    }
    return pList.end();
}

While the function works fine and finds the the desired piece, when I check the iterator which calls this function - it's blank.

What should I do to fix this?


Solution

  • Your function takes the pList argument by value. This means that the PieceList container is copied when passed to the function, and the iterators used within constPieceFind all refer to this local copy of the container. The copy gets destroyed when the function returns, and the returned iterator no longer points to valid memory. Change the function so that it takes the pList argument by reference.

    PieceList::const_iterator constPieceFind(PieceList const& pList, Piece p) const
    //                                                 ^^^^^^
    

    You may also want to do the same for the second argument to prevent an unnecessary copy, though that is not necessary to get your code to work.