c ++自定义比较函数std :: sort() [英] c++ custom compare function for std::sort()

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

问题描述

我想为std :: sort()创建自定义比较函数,对一些键值对进行排序std :: pair

I want to create custom compare function for std::sort(), to sort some key-value pairs std::pair

这里是我的函数



Here is my function

 template <typename K, typename V>
 int comparePairs(const void* left, const void* right){
        if((((pair<K,V>*)left)->first) <= (((pair<K,V>*)right)->first))
            return 1;
        else 
            return -1;
    }

然后,在一些类中,我有向量的类成员:

Then, inside some class I have vector of pairs class member:

vector<pair<K,V>> items;  

还有一些方法可以使用std :: sort

And some method for sort this vector by keys, using std::sort()

std::sort(items.begin(), items.end(), comparePairs<K,V>);

我在其中存在编译错误,表示

I have compilation errors within , which said

无法将参数编号从'std :: pair< _Ty1,_Ty2>'转换为'const
void *'

"cannot convert parameter number from 'std::pair<_Ty1,_Ty2>' to 'const void*'"

。什么是错误?

推荐答案

std :: pair 已经具有所需的比较运算符,其使用每对的两个元素执行词典性比较。要使用它,你只需要为类型 K V 提供比较运算符。

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

还要记住, std :: sort 需要严格弱转换 比较,并且< = 不满足。例如,对于 K V,您将需要小于< 。有了这个,你所需要的就是

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

如果你真的需要提供自己的比较函数, p>

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
  return lhs.first < rhs.first;
}

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

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