c++ - std::sort 自定义比较器

标签 c++ sorting

在下面的代码中,为什么 IntComparator()IntComparator2IntComparator3 这三个都作为 的第三个参数排序()函数?他们不会有不同的左值函数类型吗?基于https://en.cppreference.com/w/cpp/algorithm/sort它说

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

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

最佳答案

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

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

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

也像你说的,第三种选择确实通常更直观。

关于c++ - std::sort 自定义比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56183031/

相关文章:

c++ - 运算符<<不匹配

c++ - 如何阻止 CMake 将特定于平台的标志传递给编译器?

linux - 在bash中对具有多个小数的数字进行排序

java - 按列表值对 Java Map 进行排序

无法删除二叉搜索树

java - 如何在 mapreduce 中对 map 端程序的输出进行排序?

c# - 如何让 LINQ 根据文化进行排序?

c++ - 当 ios::sync_with_stdio(0) 和 cin.tie(0) 写在循环内时奇怪行为的解释

c++ - 不是只打印一个字母就打印出所有字母,而是需要打印出输入的字母之后的每个字母

c++ - "std_lib_facilities.h"显示错误