函数对象的简单应用

在一些管理系统中,经常需要对这种那种属性进行比较排序。可以通过stl容器跟函数对象将代码写的非常简洁。

简单的事例:

 

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

struct StudentInfo
{
public:
	struct SortHelper
	{
		enum SortField
		{
			kSortId = 0,
			kSortName,
			kSortScore,
		};
		SortHelper(SortField kField = kSortId, bool bSortUp = true) 
			: _kField(kField) 
			, _bSortUp(bSortUp) {}
		bool operator() (const StudentInfo& first, const StudentInfo& second) const 
		{
			bool bRet = true;
			switch (_kField)
			{
			case kSortId:
				{
					bRet = _bSortUp ? (first._Id < second._Id) : (first._Id > second._Id);
					break;
				}
			case kSortName:
				{
					bRet = _bSortUp ? (first._sName < second._sName) : (first._sName > second._sName);
					break;
				}
			case kSortScore:
				{
					bRet = _bSortUp ? (first._dScore < second._dScore) : (first._dScore > second._dScore);
					break;
				}
			}
			return bRet;
		}
	private:
		SortField _kField;
		bool _bSortUp;
	};
	explicit StudentInfo(int id, const char* sName, float score)
		: _Id(id),_sName(sName), _dScore(score) {}
	void print() const
	{
		printf("ID=%d,name=%s,score=%0.2f\n", _Id, _sName.c_str(), _dScore);
	}
private:
	int _Id;
	string _sName;
	float _dScore;
};
typedef vector<StudentInfo> StudentInfoList;
typedef StudentInfoList::iterator StudentInfoListIter;
typedef StudentInfoList::const_iterator StudentInfoListConstIter;

void print(const StudentInfoList& stuInforList)
{
	StudentInfoListConstIter iter(stuInforList.begin());
	for (; iter != stuInforList.end(); iter++)
	{
		iter->print();
	}
	printf("\n");
}

int _tmain(int argc, _TCHAR* argv[])
{
	StudentInfo info[] = 
	{
		StudentInfo(1, "zhang san", 59.0),
		StudentInfo(2, "li si", 61.0),
		StudentInfo(3, "wang ba", 100.0),
		StudentInfo(4, "zhao wu", 99.0),
	};

	StudentInfoList stuInfoList;
	stuInfoList.assign(info, info + sizeof(info)/sizeof(StudentInfo));
	print(stuInfoList);

	std::sort(stuInfoList.begin(), stuInfoList.end(), StudentInfo::SortHelper());
	print(stuInfoList);

	std::sort(stuInfoList.begin(), stuInfoList.end(), StudentInfo::SortHelper(StudentInfo::SortHelper::kSortName));
	print(stuInfoList);

	std::sort(stuInfoList.begin(), stuInfoList.end(), StudentInfo::SortHelper(StudentInfo::SortHelper::kSortScore));
	print(stuInfoList);

	std::sort(stuInfoList.begin(), stuInfoList.end(), StudentInfo::SortHelper(StudentInfo::SortHelper::kSortScore, false));
	print(stuInfoList);

	getchar();
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值