STL较少运算符和“无效运算符”错误 [英] STL less operator and "invalid operator<" error

查看:209
本文介绍了STL较少运算符和“无效运算符”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码在VS 10.0中编译良好,但在插入几个项目到Orders地图下面,我收到一个无效的运算符< Microsoft调试库中的错误。我的less运算符很简单,只是比较8字节字符串char by char。任何人都知道为什么会收到此错误?

I have some code that compiles fine in VS 10.0 but after inserting a few items into the Orders map below I receive an "invalid operator <" error in Microsoft debug library. My less operator is simple, just compares the 8 byte string char by char. Anyone have any idea why I would receive this error?

感谢,
Mike

Thanks, Mike

typedef struct MY_orderID_t
{
    char orderID[8];
} MY_orderID_t;

struct std::less<MY_orderID_t>
{ 
   bool operator()(const MY_orderID_t& k1, const MY_orderID_t& k2) const
   {
       for( int i=0; i < 8; i++ )
       {
           if( k1.orderID[i] < k2.orderID[i] )
           return( true );
       }
       return( false );
   }
};

std::map< MY_orderID_t, MY_order_t > Orders[5];


推荐答案

我认为这里的问题是,比较两个 MY_orderID_t 的不是 严格的弱订单 ,是C ++ STL所需的排序关系类型。要成为严格的弱订单,您的小于运算符必须具有以下四个属性:

I believe that the problem here is that your method of comparing two MY_orderID_t's is not a strict weak order, the type of ordering relation required by the C++ STL. To be a strict weak order, your less-than operator must have the following four properties:


  1. 反射性 x <

  2. 反对称:如果x < y,则y <

  3. Transitivity :如果x < y和y < z,则x <
  4. :如果x和y无法比拟,y和z无法比较,那么x和z是无法比较的。 >
  1. Irreflexivity: x < x is always false.
  2. Antisymmetry: If x < y, then y < x is always false.
  3. Transitivity: If x < y and y < z, then x < z is always true.
  4. Transitivity of Equivalence: If x and y are incomparable and y and z are incomparable, then x and z are incomparable.

现在,您的订单不符合属性(2)或(3)。

Right now, your ordering doesn't obey properties (2) or (3).

*首先,(2)被以下内容违反:

*First, (2) is violated by the following:

(0, 4) < (2, 2) 
(2, 2) < (0, 4)

*第二,违反了(3),因为

*Second, (3) is violated, because

(0, 1) < (2, 0) < (-1, 1)

// but 

(0, 1) < (-1, 1) // Fail

要解决这个问题, ,而是使用像这样的 词典比较

To fix this, instead of using the comparison you currently have, instead use a lexicographical comparison like this one:

return std::lexicographical_compare(k1.orderID.begin(), k1.orderID.end(),
                                    k2.orderID.begin(), k2.orderID.end());

这种比较是一个严格的弱排序,是所有STL容器默认使用的。切换到此比较服从属性(1) - (4),并应该使一切正常工作。

This comparison is a strict weak ordering and is what's used by all the STL containers by default. Switching to this comparison obeys properties (1) - (4) and should cause everything to work correctly.

希望这有助于!

这篇关于STL较少运算符和“无效运算符”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆