首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用std::rel_ops自动提供比较运算符?

如何使用std::rel_ops自动提供比较运算符?
EN

Stack Overflow用户
提问于 2013-02-08 00:52:20
回答 3查看 1.7K关注 0票数 6

如何从==<获取运算符>>=<=!=

标准标头<utility>定义了一个名称空间std::rel_ops,它根据运算符==<定义了上面的运算符,但我不知道如何使用它(诱使我的代码将以下定义用于:

代码语言:javascript
运行
复制
std::sort(v.begin(), v.end(), std::greater<MyType>); 

其中我定义了非成员运算符:

代码语言:javascript
运行
复制
bool operator < (const MyType & lhs, const MyType & rhs);
bool operator == (const MyType & lhs, const MyType & rhs);

如果我使用#include <utility>并指定using namespace std::rel_ops;,编译器仍然会报告binary '>' : no operator found which takes a left-hand operand of type 'MyType'..

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2013-02-08 01:04:17

我会使用头:

代码语言:javascript
运行
复制
#include <boost/operators.hpp>

struct S : private boost::totally_ordered<S>
{
  bool operator<(const S&) const { return false; }
  bool operator==(const S&) const { return true; }
};

int main () {
  S s;
  s < s;
  s > s;
  s <= s;
  s >= s;
  s == s;
  s != s;
}

或者,如果您更喜欢非成员运算符:

代码语言:javascript
运行
复制
#include <boost/operators.hpp>

struct S : private boost::totally_ordered<S>
{
};

bool operator<(const S&, const S&) { return false; }
bool operator==(const S&, const S&) { return true; }

int main () {
  S s;
  s < s;
  s > s;
  s <= s;
  s >= s;
  s == s;
  s != s;
}
票数 8
EN

Stack Overflow用户

发布于 2013-02-08 00:54:43

实际上,只有<应该足够了。如下所示:

a == b <=> !(a<b) && !(b<a)

a > b <=> b < a

a <= b <=> !(b<a)

a != b <=> (a<b) || (b < a)

对于对称情况,依此类推。

票数 1
EN

Stack Overflow用户

发布于 2013-02-08 00:56:21

代码语言:javascript
运行
复制
> equals !(<=)
>= equals !(<)
<= equals == or <
!= equals !(==)

像这样的东西?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14756512

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档