std :: sort与自定义比较器 [英] std::sort with custom comparator

查看:82
本文介绍了std :: sort与自定义比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,为什么所有三个 IntComparator() IntComparator2 IntComparator3 都充当的第三个参数sort()函数?它们不会具有不同的l值函数类型吗?基于 https://en.cppreference.com/w/cpp/algorithm/sort它说

In the following code, why do all three IntComparator(), IntComparator2 and IntComparator3 work as the 3rd parameter of the sort() function? Wouldn't they have different l-value function types? Based on https://en.cppreference.com/w/cpp/algorithm/sort it says

比较功能的签名应等效于以下:

The signature of the comparison function should be equivalent to the following:

bool cmp(const Type1& a,const Type2& b);

bool cmp(const Type1 &a, const Type2 &b);

哪个似乎更匹配 IntComparator2 ?

还有哪一个更可取?第三种选择似乎更简单,更直观.

Also which one would be preferable? Third option seems much simpler and more intuitive.


#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

struct IntComparator
{
  bool operator()(const int &a, const int &b) const
  {
    return a < b;
  }
};

bool IntComparator2 (const int &a, const int &b)
{
    return a < b;
}

bool IntComparator3 (int a, int b)
{
    return a < b;
}

int main()
{
    int items[] = { 4, 3, 1, 2 };
    std::sort(items, items+4, IntComparator());

    for (int n=0; n<4; n++) {
        std::cout << items[n] << ", ";
    }

    std::cout << "\n";

    int items2[] = { 4, 3, 1, 2 };
    std::sort(items2, items2+4, IntComparator2);

    for (int n=0; n<4; n++) {
        std::cout << items2[n] << ", ";
    }

    std::cout << "\n";

    int items3[] = { 4, 3, 1, 2 };
    std::sort(items3, items3+4, IntComparator3);

    for (int n=0; n<4; n++) {
        std::cout << items3[n] << ", ";
    }

    std::cout << "\n";

    return 0;
}

推荐答案

std :: sort 接受 functor .这是可以调用的任何对象(带有正确的参数).该功能通过使用以下模板来实现此目的

std::sort accepts a functor. This is any object that can be called (with the correct parameters). The function achieves this by using templates, like the following

template<typename Iter, typename Comp>
void sort(Iter begin, Iter end, Comp compare) { ... }

IntComparator1 ,2和3都是此比较器的有效函子,因为它们都可以使用带有2个整数的operator()进行调用.

IntComparator1, 2, and 3 are all valid functors for this comparator, since they can all be called using operator() with 2 integers.

也像您说的那样,第三个选项通常确实更直观.

Also like you said, the third option is indeed usually more intuitive.

这篇关于std :: sort与自定义比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆