您的位置:首页 > 运维架构

Implementing operator<() for strict weak ordering

2014-11-05 12:39 239 查看
http://musingstudio.com/2013/02/25/implementing-operator-for-strict-weak-ordering/


Implementing
operator<() for strict weak ordering





The latest edition of Overload Magazine (a publication by the ACCU) includes a recipe for implementing operator<, as is often required when you want store some class in an STL associative container.
bool operator<( const T& rhs ) const
{
if ( a != rhs.a ) return a < rhs.a;
if ( b != rhs.b) return b < rhs.b;
...
return false;
}


This assumes that operator!= exists on that class and in my view muddies the waters between equivalence (the property you test in a std::set or std::map with operator<) and equality (the test in std::vector or std::list with operator==). Of course, if operator==
exists, you can easily amend the recipe accordingly, but again neither operator== nor operator!= have default implementations so may not be provided.

Where necessary, you can fall back onto this more verbose recipe:
bool operator <(const T& rhs) const
{
if ( a < rhs.a )
return true;
else if (rhs.a < a)
return false;

if ( b < rhs.b)
return true;
else if (rhs.b < b)
return false;

// repeat for all child elements c, d, e etc
return false;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: