std :: sort与自定义比较器

BYS*_*YS2 11 c++ sorting

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

比较函数的签名应等效于以下内容:

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

哪个更匹配IntComparator2

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


#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;
}
Run Code Online (Sandbox Code Playgroud)

小智 6

std::sort接受一个functor。这是可以调用的任何对象(带有正确的参数)。该函数通过使用模板来实现此目的,如下所示

template<typename Iter, typename Comp>
void sort(Iter begin, Iter end, Comp compare) { ... }
Run Code Online (Sandbox Code Playgroud)

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

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

  • Lambda是另一种选择,可能更直观。 (3认同)
  • 只要它们简短且相对不言自明(并假设它们在您的代码中的其他地方没有用) (3认同)
  • 第一个(functor)和一个lamba也获得了显着的好处,即在std :: sort算法实现中*内联的可能性非常高,而另外两个都有效地指向函数,这两个都不是可能实现。它可以在性能上产生“巨大的”差异。出于这个原因,函子或lambda应该放在一个人的优先级列表上。 (3认同)