【问题标题】:Comparator for sort, specialization排序比较器,专业化
【发布时间】:2019-05-28 15:16:52
【问题描述】:

在模板函数中,std::vector 应该被排序。 T 可以是简单类型或 std::pair 例如,

std::vector<double> or 
std::vector<std::pair<int,Something> >

当 T 是一对时,只比较第一个元素。如何实现这两种情况的比较器?

我试过了:

template<typename T>
inline bool smaller(const T& a,const T& b)
{
    return a<b;
}

template<typename T,typename S>
inline bool smaller(
    const std::pair<T,S>& a,
    const std::pair<T,S>& b
    )
{
    return a.first<b.first;
}

template<typename T> inline void function(std::vector<T >& vVec)
{
...bla...
sort(vVec.begin(),vVec.end(),smaller<T>);
...bla...
}

但它不能以这种方式工作。我也尝试过专门化,但找不到合适的语法来专门化 small() 函数。

【问题讨论】:

  • 你试过sort(vVec)吗?
  • @Damien, sort(vVec.begin(),vVec.end()) 也会比较该对的第二个元素。这在应用程序中不是必需的,它需要一个 operator
  • 没有必要并不意味着它会成为问题,当然前提是您提到的第二个元素定义了运算符&lt;

标签: c++ templates


【解决方案1】:

你可以把它包装在一个 lambda 中:

std::sort(vVec.begin(),vVec.end(), [](const auto& a, const auto& b) { return smaller(a, b); });

【讨论】:

    【解决方案2】:

    一个简单的解决方法是将smaller 的两个函数都设为opeator()smaller 结构。使用

    struct smaller
    {
        template<typename T>
        bool operator()(const T& a,const T& b)
        {
            return a < b;
        }
    
        template<typename T, typename S>
        bool operator() (const std::pair<T, S>& a, const std::pair<T, S>& b)
        {
            return a.first < b.first;
        }
    };
    

    允许您将smaller 传递给sort 喜欢

    template<typename T> inline void function(std::vector<T >& vVec)
    {
        sort(vVec.begin(),vVec.end(),smaller{});
    }
    

    sort 中,重载解析将在两个较小的operator() 上起作用,对于任何std::vector&lt;std::pair&gt;,将调用std::pair 重载。

    【讨论】:

    • 我只能接受一个答案作为解决方案,并且我选择了下面较短的 lambda 答案。你的回答也能解决,非常感谢。
    • @Raffi 不用担心。很高兴能提供帮助。
    猜你喜欢
    • 2012-04-24
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 2020-10-08
    • 1970-01-01
    • 2011-02-19
    相关资源
    最近更新 更多