2016-06-12 106 views
-1

我已经与运营商<以下数据来实现:std :: set - 实现operator <?的正确方法?

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

您的运营商未定义订购。这是垃圾。你想如何订购物品? –

+1

E.g.在你的逻辑中,'(1,0)<(0,1)'和'(0,1)<(1,0)'是真的。 –

回答

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); 
} 

提供您可以重新排列成员为了在您需要逐一比较。

+0

谢谢这是真正简单的方法来做到这一点 – paulm

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; 
     } 
    } 
} 
+0

由于数据成员公开,你不需要'朋友' – coincoin

+0

@coincoin是的,我们不需要。现在,调查是否更好地移除“friend”或使某些成员为private ......可能会很有趣...... –

+0

当然,我总是对运算符<如此混淆,我希望设置used operator = =而不是 – paulm