STL中sort函数的自定义排序问题

1 篇文章 0 订阅

定义

template<class _RanIt> inline
	void sort(_RanIt _First, _RanIt _Last)
template<class _RanIt,class _Pr> inline
	void sort(_RanIt _First, _RanIt _Last, _Pr _Pred)

提供两种调用方式,一种是使用默认的<操作符(升序)比较;一种可以自定义函数

使用

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;


void test01()
{
	vector<int> vec{ 2, 1, 3, 4, 5, 7, 8, 6, 0 };
	vec.push_back(2);
	sort(vec.begin(), vec.end());

	for (auto i = 0; i < vec.size(); i++)
	{
		cout << vec[i] << "  ";
	}
	cout << endl;

}

//注意:必须针对相等返回false
bool compare(int a, int b)
{
	return a < b;
}
void test02()
{
	vector<int> vec{ 2, 1, 3, 4, 5, 7, 8, 6, 0 };
	vec.push_back(2);
	sort(vec.begin(), vec.end(), compare);

	for (auto i = 0; i < vec.size(); i++)
	{
		cout << vec[i] << "  ";
	}
	cout << endl;

}
int main()
{
	test01();
	test02();
	system("pause");
	return 0;
}

结果:

0 1 2 2 3 4 5 6 7 8
0 1 2 2 3 4 5 6 7 8

注意,第二种方式,自定义函数时,容易出现错误。

错误程序

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

bool compare(int a, int b)
{
	return a >= b;      //没有重复元素时,这么写不会出错
}
void test01()
{
	vector<int> vec{2,1,3,4,5,7,8,6,0};
	vec.push_back(2);
	sort(vec.begin(),vec.end(),compare);

	for (auto i = 0; i < vec.size();i++)
	{
		cout << vec[i] << endl;
	}
}
int main()
{
	test01();
	system("pause");
	return 0;
}

原因:元素重复

当a与b相等时,compare返回了true,这是有问题的,如果,元素不重复,则可以如上所写。

修正程序

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

bool compare(int a, int b)
{
	return a > b;     //去掉“=”
}
void test01()
{
	vector<int> vec{2,1,3,4,5,7,8,6,0};
	vec.push_back(2);
	sort(vec.begin(),vec.end(),compare);

	for (auto i = 0; i < vec.size();i++)
	{
		cout << vec[i] << endl;
	}

}
int main()
{
	test01();
	system("pause");
	return 0;
}

结论:

采用第二种方式,自定义函数时,不要出现“>=”和“=<”的情况。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值