当我插入地图c ++时,为什么不会调用少于运算符?

时间:2012-03-09 02:49:30

标签: c++ map operators overloading

class Board {
public:

  virtual void init() = 0;
  virtual void print_board() const = 0;
  virtual Board* clone() const = 0;
  virtual bool less_than(const Board& b2) const = 0;
  inline friend bool operator< (const Board& b1, const Board& b2);
};

inline bool operator< (const Board& b1, const Board& b2){
  std::cout<<"TEST1"<<std::endl;
  return b1.less_than(b2);
}

当我使用mymap [board] = evaluate插入时,根本没有打印Test1; 地图为map<Board*, int>

1 个答案:

答案 0 :(得分:5)

它正在调用operator<(Board*, Board*),它只是比较指针。将地图构建为map<Board, Board> - 或者创建一个仿函数来比较两个地图指针并将其用作模板参数:

struct compareBoards {
    bool operator()(Board const * b1, Board const * b2) const {
        return *b1 < *b2; }
}

map<Board*, int, compareBoards> boardMap;