Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 我可以使用什么作为std::map键?_C++_Stl_Map_Key - Fatal编程技术网

C++ 我可以使用什么作为std::map键?

C++ 我可以使用什么作为std::map键?,c++,stl,map,key,C++,Stl,Map,Key,我有: struct Coord { int row, col ; bool operator<( const Coord& other ) const { return row < other.row && col < other.col ; } } ; 结构坐标 { int row,col; 布尔运算符您可能需要: bool operator<( const Coord& other ) const { if ( row

我有:

struct Coord { int row, col ; bool operator<( const Coord& other ) const { return row < other.row && col < other.col ; } } ; 结构坐标 { int row,col; 布尔运算符您可能需要:

 bool operator<( const Coord& other ) const
  {
    if ( row < other.row ) {
       return true;
    }
    else if ( row == other.row ) {
       return col < other.col;
    }
    else {
       return false ;
    }
  }
bool操作符尝试以下操作:

struct Coord
{
  int row, col ;

  bool operator<( const Coord& other ) const
  {
    if (row != other.row)
      return row < other.row;

    return col < other.col ;
  }
} ;
struct-Coord
{
int row,col;

布尔运算符是的,严格弱排序很可能会出现问题。很可能它的工作方式与您预期的不一样。请考虑:

  bool operator<( const Coord& other ) const
  {
    return row < other.row && col < other.col ;
  }
bool运算符为false

好吧,那么:

obj2错误

唯一的结论是它们必须相等(基于<运算符)。由于这是一个贴图,并且关键点是唯一的,所以两个关键点都会保留到同一个位置。这种行为可能是您所期望的,也可能不是您所期望的,但听起来可能不是

您需要的是在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;
  }

<代码>布尔运算符>代码>布尔运算符> p>比较函数,在对象的值集上强加弱的排序,其中一个条件是等价必须是及物的。<代码> < <代码> >代码> b>代码>如果(C++语法)<代码>是等价的!(a < b)& &(b < a)< /C> >是真的。< /P>
您的
运算符可以更具体地说明“有bug”?您的代码是否编译?返回错误的结果?崩溃?std::map没有任何bug。至少在我看到的MS STL中是这样。而且wikipedia不是RTFN的最佳源。我所说的“有bug”只是以下句子:“Coord对地图的查找返回了错误的结果。"不使用
=
运算符更为正确。使用
operator@GMan我们在这里讨论的是比较整数。用括号说明&&的优先级高于| |?@Neil在抽象意义上这是一个很好的观点。你不希望你的代码因为改变了基础类型而中断。不,不是这样,但我确实尝试将底层类型的要求降到最低。如果在这里只使用<,那么底层类型只需定义一个运算符库就可以接受,但我认为Doug t的答案要好得多,并且包括了我写的内容。好吧,你的答案是,而且更早。但我会更改它else
返回行
问题不仅在于比较可能无法达到预期效果,还在于原始定义下的等价关系不是等价关系,这违反了
std::map
+1中用作键的要求,这就是专业人士使用
tie(col,row)
;)
bool operator<(const Coord& other) const
{
    return row < other.row
        || row ==other.row
        && col < other.col;
}