【问题标题】:Why isnt the less than operator being called when I insert into a map c++?为什么当我插入地图 C++ 时不调用小于运算符?
【发布时间】:2012-03-09 02:49:29
【问题描述】:
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&lt;Board*, int&gt;

【问题讨论】:

  • 你能提供你用来测试的确切代码吗?

标签: c++ map operators overloading


【解决方案1】:

它调用operator&lt;(Board*, Board*),它只是比较指针。将您的地图构造为map&lt;Board, Board&gt; - 或创建一个函子来比较两个地图指针并将其用作模板参数:

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

map<Board*, int, compareBoards> boardMap;

【讨论】:

  • 如果我的地图是不同类的私有成员,我将如何使用它作为模板参数?
猜你喜欢
  • 1970-01-01
  • 2014-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 2012-03-09
相关资源
最近更新 更多