1

I'm writing a C++ algorithm to solve a board game. The solution is based on the following:

enqueue initial board
while queue not empty:
    dequeue a board
    if board is solved:
        print solution
    else:
        for each possible board that can arise out of this one:
            add board to end of queue

Since I don't want to examine the same board more than one time I use std::set<Board> to keep track of examined boards.

In Board class bool operator<(const Board& rhs) const is defined to make std::set work properly.

So what happens in my std::set if my comparison function doesn't ensure an order in board instances?

As example:

a = Board()
b = Board()
c = Board()

a > b returns true
b > c returns true
a > c returns false

Is it possible that std::set, since it's based on Red-Black Tree, inserts the same Board more than once?

c.bear
  • 1,197
  • 8
  • 21
  • if `operator<` does not work as proper comparator - container behavior is undefined and implementation specific – Hcorg Jul 21 '15 at 08:50
  • 1
    Since the program would be undefined, anything could happen. – molbdnilo Jul 21 '15 at 08:54
  • To add to what others have stated, if you're using Visual C++, the debug runtime checks this and will fail with an assert() if you did anything like what you've posted. So for the Visual C++ debug runtime, the behavior is "well-defined" -- your program will `assert()` and exit. – PaulMcKenzie Jul 21 '15 at 09:25
  • I can't get what is checked and when from your answer. You mean an assert is thrown in `std:set insert`? – c.bear Jul 21 '15 at 10:10
  • 1
    @kuket15: Correct, VC++ asserts when inserting an element that is unordered with respect to the items with which it's compared. Keep in mind that Visual C++ won't compare it with _all_ set elements, that would be prohibitively expensive even for debug builds. – MSalters Jul 21 '15 at 10:21

1 Answers1

1

If the comparator doesn't work properly, the structure won't work properly. It might report that items are missing. It might fail to insert something. It could crash quickly, or it could appear to work for all your test cases and then crash on the customer's machine.

All bets are off.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421
  • Can you serialize boards, i.e. turn them into a string or sequence of bytes? If so, you can compare the serialized representations. (This does require a unique serialization; i.e. if a particular serialization depends on the history of moves then two "identical" board may in fact be unequal. C++ doesn't make assumptions here) – MSalters Jul 21 '15 at 10:25