如何使用自定义比较器对数组进行排序
How can I sort an array using a custom comparator?
当我从下面的代码中调用build
函数时,我会得到以下编译错误:
error C3867: 'SuffixArray::cmp': function call missing argument list; use '&SuffixArray::cmp' to create a pointer to member
error C2780: 'void std::sort(_RanIt,_RanIt)' : expects 2 arguments - 3 provided
这是我的代码:
class A{
private:
std::string text;
std::vector<int> array;
bool cmp(int a, int b) {
return std::lexicographical_compare(text.begin() + a, text.end(),
text.begin() + b, text.end());
}
void build(const std::string &str, std::vector<int> &vec) {
// Some vector values actions.
std::sort(vec.begin(), vec.end(), cmp);
}
};
这里怎么了?我使用的是Visual C++编译器。
您的比较函数A::cmp
是A
的非静态成员。因此,它需要三个参数:除了显式声明的两个参数外,还需要一个指向A
的指针来成为隐式可用的this
。它还有一种不同于普通函数指针的类型:bool (A::)(int, int)
,当通过值传递时,它会衰减为bool (A::*)(int, int)
。
但是,您可以将函数std::bind()
转换为一个合适的对象:
std::sort(vec.begin(), vec.end(),
std::bind(&A::cmp, this, std::placeholders::_1, std::placeholders::_2));
@DietmarKühl的回答完美地解释了为什么您的代码没有编译。但由于C++11,您也可以使用lambda表达式,而不是定义比较函数或使其静态:
#include <vector>
#include <algorithm>
class A{
private:
std::string text;
std::vector<int> array;
void build(const std::string &str, std::vector<int> &vec) {
// Some vector values actions.
std::sort(vec.begin(), vec.end(), [this](int a, int b) {
return std::lexicographical_compare(text.begin() + a, text.end(),
text.begin() + b, text.end());
});
}
};
为了能够访问lambda表达式中的类成员text
,我捕获了this
指针。但是,如果您想要捕捉this
的替代方案,请查看此答案。
相关文章:
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 在 c++ 中对类中的 c 字符串动态数组进行排序的最佳方法是什么?
- 合并排序不排序自创建数组类 c++
- 带有枚举方向/类型的气泡排序结构数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 排序并行数组
- 如何在数组 c++ 中对字符串进行排序
- 为什么在此排序算法实现中,向量明显比数组慢?
- 如何对不在数组中的变量进行排序?
- C++数组与向量排序(在我的情况下,向量比数组慢~2.5倍(无优化))
- 按字母顺序对结构内数组变量中的名称进行排序
- 使用排序函数 c++ 对字符数组进行排序
- 使用 std::sort 对二维 c 数组进行排序
- 使用STL对用户输入数组进行排序的错误有什么解决方案吗?
- 使用 std::sort 对 C 样式的 2D 数组进行部分排序
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 对 0 、1 和 2 的数组进行排序