我如何 return 使用 std::min 和 std::less 的对象
How can I return an object using std::min with std::less
我有以下代码,我需要 return 具有特定最小元素的对象。我需要使用 std::greater 和 std::less。代码正在运行,但这不是我想要的。我想让 x3
具有最小 x
.
结构的 x
和 y
#include <iostream>
using namespace std;
struct X {
int x;
int y ;
};
class A {
public:
A(){}
template<typename T>
static X getValue(const X&x1,const X&x2) {
X x3;
x3.x = std::min(x1.x, x2.x,T());
return x3;
// x3 = std::min(x1.x, x2.x,T()); Wont work for sure.
}
};
int main()
{
X x1;
x1.x = 10;
X x2;
x2.x = 20;
cout<<A::getValue<std::less<int>>(x1,x2).x << std::endl;
cout<<A::getValue<std::less<int>>(x1,x2).y << std::endl;
return 0;
}
你可以这样写函数:
template<typename T>
static X getValue(const X&x1,const X&x2) {
return T{}(x1.x, x2.x) ? x1 : x2;
}
这是 demo。
或者,您可以将比较对象作为参数传递:
template<typename T>
static X getValue(const X&x1,const X&x2, T comp) {
return comp(x1.x, x2.x) ? x1 : x2;
}
并这样称呼它:
cout << A::getValue(x1, x2, std::less{}).x << std::endl;
这是 demo.
最好为 X
定义关系运算符
#include <tuple>
struct X {
int x;
int y ;
};
bool operator<(X lhs, X rhs) { return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y); }
bool operator>(X lhs, X rhs) { ... }
bool operator<=(X lhs, X rhs) { ... }
bool operator>=(X lhs, X rhs) { ... }
那你就可以了
template<class Pred>
X get_value(X x1, X x2) { return std::min(x1, x2, Pred()); }
你应该使用 std::less<>
和 std::greater<>
而不是 std::less<int>
和 std::greater<int>
因为 void
的模板专门用于做正确的事情.
编辑:
如果您不关心 X
的关系运算符,那么@cigien 的回答可能没问题
我有以下代码,我需要 return 具有特定最小元素的对象。我需要使用 std::greater 和 std::less。代码正在运行,但这不是我想要的。我想让 x3
具有最小 x
.
x
和 y
#include <iostream>
using namespace std;
struct X {
int x;
int y ;
};
class A {
public:
A(){}
template<typename T>
static X getValue(const X&x1,const X&x2) {
X x3;
x3.x = std::min(x1.x, x2.x,T());
return x3;
// x3 = std::min(x1.x, x2.x,T()); Wont work for sure.
}
};
int main()
{
X x1;
x1.x = 10;
X x2;
x2.x = 20;
cout<<A::getValue<std::less<int>>(x1,x2).x << std::endl;
cout<<A::getValue<std::less<int>>(x1,x2).y << std::endl;
return 0;
}
你可以这样写函数:
template<typename T>
static X getValue(const X&x1,const X&x2) {
return T{}(x1.x, x2.x) ? x1 : x2;
}
这是 demo。
或者,您可以将比较对象作为参数传递:
template<typename T>
static X getValue(const X&x1,const X&x2, T comp) {
return comp(x1.x, x2.x) ? x1 : x2;
}
并这样称呼它:
cout << A::getValue(x1, x2, std::less{}).x << std::endl;
这是 demo.
最好为 X
#include <tuple>
struct X {
int x;
int y ;
};
bool operator<(X lhs, X rhs) { return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y); }
bool operator>(X lhs, X rhs) { ... }
bool operator<=(X lhs, X rhs) { ... }
bool operator>=(X lhs, X rhs) { ... }
那你就可以了
template<class Pred>
X get_value(X x1, X x2) { return std::min(x1, x2, Pred()); }
你应该使用 std::less<>
和 std::greater<>
而不是 std::less<int>
和 std::greater<int>
因为 void
的模板专门用于做正确的事情.
编辑:
如果您不关心 X
的关系运算符,那么@cigien 的回答可能没问题