//二元谓词
class MyCompare
{
public:
bool operator()(const int va11, const int val2)
{
return va11 > val2;
}
//---------------------------------
sort(v.begin(), v.end());
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
//使用函数对象 改变算法策略,变为排序规则为从大到小
sort(v.begin(), v.end(), MyCompare()); //MyCompare() here
//STL内建仿函数 大于仿函数
//sort(v.begin(), v.end(), greater<int>()); // include functional header file
cout << "-----------------------" << endl;
for (vector<int>::iterator it = v.begin(); it != v.end(); it++)
{
cout << *it << " ";
}
cout << endl;
};
利用仿函数 改变 sort排序方式 sort 默认 由小到大
最新推荐文章于 2023-03-11 12:59:53 发布
这段代码展示了如何在STL的`sort`函数中使用自定义比较函数对象`MyCompare`,实现从大到小的排序。首先,通过`sort`函数对整数向量进行默认升序排序,然后利用`MyCompare`或内置的`greater<int>`函数对象进行降序排序,从而改变排序策略。
摘要由CSDN通过智能技术生成