如何将用户数据传递给 std::sort 的比较函数? [英] How to pass user data to compare function of std::sort?

查看:31
本文介绍了如何将用户数据传递给 std::sort 的比较函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

qsort()一样,C++的std::sort()似乎不允许将用户数据传递给排序函数.

Like qsort(), it seems that C++ std::sort() does not allow to pass user data to the sort function.

例如:一个结构数组,如 struct A { int version;整数索引;} array[100] 必须按顺序排序,但是使用这个数组 struct B { int value;} key[100] 作为排序键.struct A::index 索引数组 key.

For example: An array of structure like struct A { int version; int index; } array[100] has to be sorted in order, but using this array struct B { int value; } key[100] as the sort key. struct A::index indexes array key.

这是一个不起作用的排序函数.它需要有一个指向 key 数组的指针:

Here's a non-working sort function. It needs to have a pointer to the key array somehow:

bool comp(struct A *a1, struct A *a2) {
    return key[a1->index].value < key[a2->index].value;
}

如何使用 C++ 实现?如何将诸如 key 之类的非全局用户数据传递给排序函数?

How to achieve that using C++? How to pass non-global user data like key to a sort function?

我尝试将对象实例作为 std::sort 组合传递,但似乎只允许使用类似 qsort() 的函数.

I tried to pass an object instance as the std::sort comp, but it seems only qsort()-like functions are allowed.

(在 GNU C 中,可以使用嵌套比较函数来使用作用域变量,但 GNU C++ 不提供嵌套函数).

(In GNU C, a nested compare function could be used to use scoped variables, but GNU C++ does not offer nested functions).

推荐答案

函子不必是函数;它们可以是对象.

Functors don't have to be functions; they can be objects.

struct Comparator {
   Comparator(int* key) : key(key) {};
   bool operator()(struct A *a1, struct A *a2) {
      return key[a1->index].value < key[a2->index].value;
   }

   int* key;
};

/* ... */

std::sort(container.begin(), container.end(), Comparator(<pointer-to-array>));

这篇关于如何将用户数据传递给 std::sort 的比较函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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