STL少运算符和“无效运算符”错误 [英] STL less operator and "invalid operator<" error
问题描述
我有一些在VS 10.0中编译好的代码,但是在将几个项目插入下面的订单图之后,我收到一个无效的运算符 Microsoft调试库中的错误。我的少操作符很简单,只是比较8字节的字符串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
不是 strict弱订单 ,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:
- 反射性: x < x总是假的。
- 反对称:如果x < y,则y < x总是错误的。
- 转移性:如果x < y和y < z,则x < z一直是真的。
- 等价的传递性:如果x和y是无法比拟的,并且y和z是无法比拟的,那么x和z是无法比拟的。 >
- Irreflexivity: x < x is always false.
- Antisymmetry: If x < y, then y < x is always false.
- Transitivity: If x < y and y < z, then x < z is always true.
- 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屋!