使用自定义比较功能进行c ++排序 [英] c++ sorting with custom compare function

查看:115
本文介绍了使用自定义比较功能进行c ++排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类型的向量:

std::vector< std::pair< std::pair< int, int >, std::vector<float> > >  neighbors;

我想创建以下向量的排序方式

I would like to create sort the following vector as follows

std::sort( neighbors.begin(), neighbors.end(), myFunc(index) );

哪里

bool myFunc( const std::pair< std::pair< int, int >, float > &a, const std::pair< std::pair< int, int >, float > &b, const int index ){
     return ( a.second[index] > b.second[index] );
}

我知道语法是错误的,但是我希望提供一个索引,用于仅比较向量的该元素.

I know that the syntax is wrong but I wish to provide an index for comparing only that element of the vector.

我不确定如何将此参数传递给myFunc.

I am not sure how to pass this argument to myFunc.

推荐答案

Lambda:

std::sort(
    neighbors.begin(),
    neighbors.end(),
    [index](const std::pair< std::pair< int, int >, std::vector<float> > &a,  
            const std::pair< std::pair< int, int >, std::vector<float> > &b)
            { 
                 return ( a.second[index] > b.second[index] );
            }
);  

请参见 C ++ 11中的lambda表达式是什么?详细介绍.

这篇关于使用自定义比较功能进行c ++排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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