[英]merge sort with a comparator and a vector as arguments
我遇到的问题涉及编写使用合并排序对向量进行排序的函数,我还需要使用函子。 如何将比较器/函数用作合并排序函数对矢量进行排序的参数?
您可以这样定义比较运算符
struct MyLessThanFunctor
{
bool operator() (int i,int j)
{
return (i<j);
}
};
然后,实例化并使用它
MyLessThanFunctor comparator;
sort(elements, comparator);
!!!警告std :: sort不应是稳定的排序算法。 使用std :: stable_sort,大多数情况下它是作为合并排序实现的。
struct comparator
{
bool operator () (int i1, int i2) const { return i1 < i2; }
};
int main()
{
vector<int> v = {0,13,76,46,53,22,4,68,68,94,38,52,83,3,5,53,67 };
std::stable_sort (v.begin(), v.end(), comparator() );
for (auto e : v) cout << e << " " ;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.