如何使用自定义std::sort函数
How to use custom std::sort function?
Hi我有一个指针向量,实际上每个指针都是一个数组,其中每个数组是:
int a,int b,大小可变的整数序列。
无序矢量示例:
rows[0] => points to [1,2,...]
rows[1] => points to [2,1,...]
rows[2] => points to [3,1,...]
rows[3] => points to [1,4,...]
rows[4] => points to [1,1,...]
输出示例:
rows[0] => points to [1,1,...]
rows[1] => points to [1,2,...]
rows[2] => points to [1,4,...]
rows[3] => points to [2,1,...]
rows[4] => points to [3,1,...]
我需要以这种方式对这个向量进行排序,我创建了以下自定义比较函数:
bool cmpRow(unsigned int *a, unsigned int *b)
{
//Mesmo id word
if(a[0] == b[0])
{
return (a[1] < b[1]);
}
else
{
return (a[0] < b[0]);
}
}
我使用它的方式如下:
std::vector<unsigned int*> rows;
.
.
//Insert some stuffs
.
.
std::sort (rows.begin(), rows.end(), cmpRow);
但结果并不是我所期望的,有人能帮我解决这个问题吗?
编辑:
事实上,函数是可以的,问题出在循环中的一个函数中,这个函数调用排序函数的次数超过了必要的次数,所以结果不是预期的。
函数cmpRow
根据前两个成员按升序对给定数组进行排序(首先比较第一个成员,如果它们相同,则比较第二个成员)。这可以很好地工作,并产生您报告的结果,根据该逻辑,这些结果是正确的。如果这不是预期的结果,会得到什么结果?
这样更改代码?
bool cmpRow(unsigned int *a, unsigned int *b)
{
//You need to safeguard against empty/equal rows
//Mesmo id word
if(a[0] == b[0])
{
return cmpRow(a[1] < b[1]);
}
else
{
return (a[0] < b[0]);
}
}
相关文章:
- std::sort()函数无法对向量的一部分进行排序
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 为什么 std::sort 找不到合适的(静态成员)函数重载?
- 尝试使用谓词函数会导致错误:"std::sort"未找到匹配的重载函数
- 隐式转换为比较函数对象(函子)用于 std::sort 而不是 std::map?
- 使用类似的比较函数时,在 c++ 中为 std:sort 获得不同的结果
- 使用 vector.sort() 的非静态成员函数无效使用
- 在使用 std::sort() 和 lambda 函数按属性对 ADT 的向量进行排序时遇到问题
- 无法在 std::sort 中使用 cdef 函数作为比较函数
- std::sort 一个实现了移动构造函数的类
- 使用c 中的sort()函数对字符串进行排序的最坏情况是什么是什么
- sort() 方法 c++ 中的比较器函数.为大量数字获得不同的解决方案
- std :: sort函数上的编译器错误(GCC 4.4)
- C 使用与自定义类对象的列表容器,列表:: Sort函数实际上并未对我的数据进行排序
- c++ sort() 函数对于<algorithm>整数数组的大小(元素数)>10^7 个元素的大输入是否失败?
- 如何使用自定义std::sort函数
- 是否可以将std::sort与需要额外参数的sort函数一起使用
- Sort函数,它获取指向接口类的指针向量
- 为什么sort()函数用于一组类对象时会导致编译错误
- Sort函数在尝试对结构体a - z的文件进行排序时发生错误