我有以下数据与运算符<实现:
enum eDataSetType
{
eData1,
eData2
};
struct LocationData
{
bool operator < (const LocationData& other) const
{
if (mFileName < other.mFileName ||
mDataSet < other.mDataSet ||
mChunkId < other.mChunkId ||
mAnimIndex < other.mAnimIndex)
{
return true;
}
return false;
}
eDataSetType mDataSet;
std::string mFileName;
Uint32 mChunkId;
Uint32 mAnimIndex;
};
但是在使用std::set<LocationData>::insert
时,我有时会收到以下消息:
---------------------------
Microsoft Visual C++ Runtime Library
---------------------------
Debug Assertion Failed!
Program: C:\Windows\system32\MSVCP120D.dll
File: C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xtree
Line: 1795
Expression: invalid operator<
For information on how your program can cause an assertion
failure, see the Visual C++ documentation on asserts.
(Press Retry to debug the application)
---------------------------
Abort Retry Ignore
---------------------------
为什么?
答案 0 :(得分:1)
首先,您必须确定如何订购商品,然后您必须确保您的功能提供严格的弱订单,而不是您的功能。
例如,您可以像这样重写您的函数:
friend bool operator < (const LocationData& a, const LocationData& b) const
{
if ( a.mFileName < b.mFileName ) // sort by filename...
return true;
else if ( a.mFileName > b.mFileName )
return false;
else {
if ( a.mDataSet < b.mDataSet ) // then by DataSet...
return true;
else if ( a.mDataSet > b.mDataSet)
return false;
else {
if ( a.mChunkId < b.mChunkId )
return true;
else if ( a.mChunkId > b.mChunkId )
return false;
else
return a.mAnimIndex < b.mAnimIndex;
}
}
}
答案 1 :(得分:1)
我只想使用std::tie
提供的词典比较 bool operator < (const LocationData& other) const
{
return std::tie(mFileName, mDataSet, mChunkId, mAnimIndex) < std::tie(other.mFileName, other.mDataSet, other.mChunkId, other.mAnimIndex);
}
您可以根据需要重新排列成员订单。