什么_can_我用作std :: map键?

bob*_*obo 4 c++ stl key map

延伸.

我有:

struct Coord
{
  int row, col ;

  bool operator<( const Coord& other ) const
  {
    return row < other.row && col < other.col ;
  }
} ;

我想创建一个map<Coord, Node*>,在那里你可以查找Node*Coord.

问题是,它有错误.对the map<Coord, Node*>的查找Coord返回错误的.

我很难搞清楚这是否合适.

维基百科说,map [keys]需要严格的弱序.我做错了吗?有没有办法使它工作,或者地图的键是否可以"严格排序"的简单值?

基本上问题是自定义struct作为我的std :: map的关键字需要什么?

Dou*_* T. 20

是的,你很可能遇到严格弱序的问题.赔率是它没有像你期望的那样工作.考虑:

  bool operator<( const Coord& other ) const
  {
    return row < other.row && col < other.col ;
  }
Run Code Online (Sandbox Code Playgroud)

obj1(this)row:2 col:3

obj2行:3 col:2

obj1 <obj2?=>假

那么好吧:

obj2 <obj1?=>假

唯一的结论是它们必须相等(基于您的<运算符).由于这是一张地图,并且按键是唯一的,因此两个按键都会重新连接到同一个地点.这种行为可能或者可能不是你所期望的,但听起来可能不是.

你需要的是在row/col之间建立一个优先级,以便<真的像你期望的那样工作:

  bool operator<( const Coord& other ) const
  {
     // look at row first, if row is equal, check column.
     if (row < other.row)
     {
         return true;
     }
     else if (row == other.row)
     {
         return col < other.col ;
     }
     return false;
  }
Run Code Online (Sandbox Code Playgroud)

  • 这不仅仅是比较可能没有做到所需的问题,而是原始定义下的等价不是等价关系,这违反了在std中用作关键字的要求: :map`. (2认同)
  • +1,这就是专业人士使用`tie(col,row)<tie(other.col,other.row)`;)的原因 (2认同)

小智 6

你可能想要:

 bool operator<( const Coord& other ) const
  {
    if ( row < other.row ) {
       return true;
    }
    else if ( row == other.row ) {
       return col < other.col;
    }
    else {
       return false ;
    }
  }
Run Code Online (Sandbox Code Playgroud)

或相反亦然.这个也咬过我几次!