Nathan Merrill
Nathan Merrill

Reputation: 8386

C++ map returning different values

I am writing a program, and I could swear that the Map is returning different values than I put in. I don't actually believe that this is the case, but that I'm missing something that I should do when using maps.

choices is a std::map<int,Board>, choice and board is a Board, and getId() will return a unique int hash.

Here's a portion of my generation code (when I am building up my map):

if (choices.find(board.getId())!=choices.end())//If choices already contains the new state
    std::cout<<"Error!"<<std::endl;
checkGoodMove(board,choice);
choices.insert(std::pair<int,Board>(board.getId(),choice));

Then, this is the code when I access my map:

if (choices.find(board.getId())==choices.end())
    std::cout<<"Error!"<<std::endl;
 auto choice = choices[board.getId()];
 checkGoodMove(board, choice);
 return choice;

Here's what's happening:

  1. I build my entire map at once. The only insert function is the one you see.
  2. When I build my map, I verify that board.getID() returns a unique value because "Error" is never printed out.
  3. I also verify that my map contains the ID before I access it because, once again, "Error" is never printed.
  4. checkGoodMove verifies that the move from the first state and the second state is a valid move. It never throws an error when building my map, but will frequently throw an error when accessing.

Why am I getting random states back from the map, when I am putting in perfectly valid states in?

Upvotes: 0

Views: 146

Answers (1)

kfsone
kfsone

Reputation: 24249

Based on the code provided and the OPs assertions of correctness, the problem must be in the copy or assignment operator of Board. Note that 'auto choice' will make choice a copy of the right hand side. It seems strange that you don't use a const reference

const auto& choice = choices[board.getId()];

And take the argument the same way in checkGoodMove.

Alternatively, the code in checkGoodMove is at fault.

Upvotes: 1

Related Questions