比较 3 个或更多对象
compare 3 or more objects
目前,要比较 3 个或更多整数,我们是这样做的。 (a < b) && (b < c)
。我知道,a < b < c
转换为 (a < b) < c
并将布尔值与整数进行比较。有什么办法可以在自定义 Class 上重载一些运算符来实现连续比较? python 等语言如何做到这一点?
更新: 根据接受的答案,我设法写了一个 piece of code。看看。
#include <iostream>
template <typename T>
class Comparator {
bool result;
T last;
public:
Comparator(bool _result, T _last) : result(_result), last(_last) {}
operator bool() const {
return result;
}
Comparator operator<(const T &rhs) const {
return Comparator(result && (last < rhs), rhs);
}
Comparator operator>(const T &rhs) const {
return Comparator(result && (last > rhs), rhs);
}
};
class Int {
int val;
public:
Int(int _val) : val(_val) {}
operator int() const {
return val;
}
Comparator<Int> operator<(const Int &rhs) {
return Comparator<Int>(val < int(rhs), rhs);
}
Comparator<Int> operator>(const Int &rhs) {
return Comparator<Int>(val > int(rhs), rhs);
}
};
int main() {
Int a(2), b(3), c(1), d(4), e(6), f(5);
std::cout << (a < b > c < d < e) << '\n';
// 2 < 3 > 1 < 4 < 6 > 5
return 0;
}
a < b < c
分组 为 (a < b) < c
.
如果 a
或 b
是您定义的类型,您可以将该类型的 <
重载为 return a proxy 对象,还为其定义了重载 <
。该代理对象将包含 b
的值以及 a < b
.
的结果
这有些麻烦,而且也不会使您的代码可读,因为所有 C++ 程序员都知道 a < b < c
应该做什么。
Python 有自己的语法和解释器。
目前,要比较 3 个或更多整数,我们是这样做的。 (a < b) && (b < c)
。我知道,a < b < c
转换为 (a < b) < c
并将布尔值与整数进行比较。有什么办法可以在自定义 Class 上重载一些运算符来实现连续比较? python 等语言如何做到这一点?
更新: 根据接受的答案,我设法写了一个 piece of code。看看。
#include <iostream>
template <typename T>
class Comparator {
bool result;
T last;
public:
Comparator(bool _result, T _last) : result(_result), last(_last) {}
operator bool() const {
return result;
}
Comparator operator<(const T &rhs) const {
return Comparator(result && (last < rhs), rhs);
}
Comparator operator>(const T &rhs) const {
return Comparator(result && (last > rhs), rhs);
}
};
class Int {
int val;
public:
Int(int _val) : val(_val) {}
operator int() const {
return val;
}
Comparator<Int> operator<(const Int &rhs) {
return Comparator<Int>(val < int(rhs), rhs);
}
Comparator<Int> operator>(const Int &rhs) {
return Comparator<Int>(val > int(rhs), rhs);
}
};
int main() {
Int a(2), b(3), c(1), d(4), e(6), f(5);
std::cout << (a < b > c < d < e) << '\n';
// 2 < 3 > 1 < 4 < 6 > 5
return 0;
}
a < b < c
分组 为 (a < b) < c
.
如果 a
或 b
是您定义的类型,您可以将该类型的 <
重载为 return a proxy 对象,还为其定义了重载 <
。该代理对象将包含 b
的值以及 a < b
.
这有些麻烦,而且也不会使您的代码可读,因为所有 C++ 程序员都知道 a < b < c
应该做什么。
Python 有自己的语法和解释器。