I am having a lot of trouble using the std::list::sort function, it works a majority of the time, however every once in a while it throws an assertion 'invalid operator<'. Looking into this issue I have realized it is because my sort function is not following strict weak ordering, however when I look at my code I do not understand why it is not following strict weak ordering as it seems correct, what is it I am missing here?
The purpose of this function is to sort a list of elements into a formula string based on the hill system, ie. Carbon First, Hydrogen Second, all others alphabetically. The FormulaStruct simply represents a single element and amount in the full formula.
struct FormulaStruct
{
FormulaStruct(const std::string & strSymbol, int nNum, bool bHasCarbon)
:
m_strSymbol(strSymbol),
m_nNum(nNum), m_bHasCarbon(bHasCarbon)
{
}
bool operator < (const FormulaStruct & rhs)
{
//If the symbols are equal
if(m_strSymbol == rhs.m_strSymbol)
return true;
if(m_bHasCarbon)
{
if(m_strSymbol == "C")
return true;
else
if(rhs.m_strSymbol == "H")
return false;
}
return m_strSymbol < rhs.m_strSymbol;
}
bool operator == (const FormulaStruct & rhs)
{
return m_strSymbol == rhs.m_strSymbol;
}
std::string m_strSymbol;
int m_nNum;
bool m_bHasCarbon;
};
list<FormulaStruct> FormulaList; //A list of FormulaStructs, assumed to be filled
FormulaList.sort();
EDIT bHasCarbon is the condition when there is carbon in the formula, as the hill system requires that if there is carbon in the formula than hydrogen will be next, otherwise everything is alphabetical including hydrogen, this is dictated in another section of my code.