【问题标题】:How can I return an object using std::min with std::less如何使用 std::min 和 std::less 返回对象
【发布时间】:2020-10-29 10:04:54
【问题描述】:

我有以下代码,我需要返回具有特定最小元素的对象。我需要使用 std::greater 和 std::less。代码正在运行,但这不是我想要的。我想让x3 同时拥有xy 结构中的最小x

#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;
}

【问题讨论】:

  • 一定要用std::min吗?似乎if 就足够了。
  • 我需要使用模板。如果使用模板怎么办?

标签: c++ templates min


【解决方案1】:

你可以这样写函数:

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

【讨论】:

    【解决方案2】:

    最好为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&lt;&gt;std::greater&lt;&gt; 而不是std::less&lt;int&gt;std::greater&lt;int&gt;,因为void 的模板专门用于做正确的事情。

    编辑: 如果您不关心X 的关系运算符,那么@cigien 的答案可能很好

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 2012-04-08
      • 2011-08-02
      • 1970-01-01
      • 2017-01-16
      • 2022-01-11
      • 1970-01-01
      • 2022-08-12
      相关资源
      最近更新 更多