Implementing operator<() for strict weak ordering
2014-11-05 12:39
239 查看
http://musingstudio.com/2013/02/25/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.
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:
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; }
相关文章推荐
- '<>' operator is not allowed for source level below 1.7
- '<>' operator is not allowed for source level below 1.7
- map key是结构体的find问题:小于号重载须注意的问题 strict weak ordering
- idea javaweb项目 jsp页面报错:'<>'operator is not allowed for source level below 1.7
- '<>' operator is not allowed for source level below 1.7
- Overloading the << Operator for Your Own Classes
- '<>' operator is not allowed for source level below 1.7
- 关于VS2008/2010中SORT,stable_sort的比较函数中strict weak ordering
- 小于号重载须注意的问题——strict weak ordering
- '<>' operator is not allowed for source level below 1.7
- std::sort strict weak ordering
- map key是结构体的find问题:小于号重载须注意的问题 strict weak ordering
- Strict Weak Ordering
- eclipse报错:'<>' operator is not allowed for source level below 1.7
- Eclipse '<>' operator is not allowed for source level below 1.7
- '<>' operator is not allowed for source level below 1.7
- <>' operator is not allowed for source level below 1.7
- 小于号重载须注意的问题——strict weak ordering
- '<>' operator is not allowed for source level below 1.7
- strict weak ordering