在一些管理系统中,经常需要对这种那种属性进行比较排序。可以通过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;
}