- // SortTest.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <time.h>
- #include <sstream>
- #include <iostream>
- #include <list>
- #include <string>
- #include <algorithm>
- #include <map>
- #include <iterator>
- using namespace std;
- class RevFaxTask
- {
- public:
- std::string m_RevDateTime;
- };
- class CoreUserBox
- {
- public:
- std::list < RevFaxTask * > m_list;
- void CoreUserBox::pushback(RevFaxTask * p_task)
- {
- m_list.push_back(p_task);
- }
- };
- template<>
- struct std::less<RevFaxTask*>
- {
- bool operator()( RevFaxTask*_X, RevFaxTask* _Y) const
- {
- return (_X->m_RevDateTime < _Y->m_RevDateTime);
- }
- };
- void TestOut(RevFaxTask* p)
- {
- cout << p->m_RevDateTime << endl;
- }
- class find_func
- {
- public:
- ~find_func() {}
- find_func(string val) : m_val(val) {}
- bool operator()(RevFaxTask *arg)
- {
- if ( arg->m_RevDateTime > m_val )
- return true;
- return false;
- }
- private:
- find_func();
- string m_val;
- };
- int main(int argc, _TCHAR* argv[])
- {
- char buf[64];
- std::list<RevFaxTask *>::iterator pos;
- std::list<RevFaxTask *>::iterator pos1;
- std::list<RevFaxTask *>::iterator pos2;
- std::list<RevFaxTask *>::iterator pos3;
- CoreUserBox testList;
- RevFaxTask task[50];
- for(int i = 0; i<50; i++)
- {
- int year = 1899;
- int monthNum = 0;
- int dayNum = 0;
- int hour = 0;
- int minu = 0;
- int sec = 0;
- while(year < 1900)
- {
- year = rand()%2099;
- }
- while(monthNum == 0)
- {
- monthNum = rand()%12;
- }
- while(dayNum == 0)
- {
- dayNum = rand()%31;
- }
- hour = rand()%24;
- minu = rand()%60;
- sec= rand()%60;
- sprintf(buf,
- "%d-%02d-%02d %02d:%02d:%02d",
- year,
- monthNum,
- dayNum,
- hour,
- minu,
- sec);
- task[i].m_RevDateTime.assign(buf);
- testList.pushback(&task[i]);
- }
- long beginTime =clock();//获得开始时间,单位为毫秒
- testList.m_list.sort(less<RevFaxTask *>());
- for_each(testList.m_list.begin(), testList.m_list.end(), TestOut);
- for_each(testList.m_list.begin(), testList.m_list.end(), TestOut);
- pos1 = find_if(testList.m_list.begin(), testList.m_list.end(),find_func("1993-12-14 14:00:00"));
- pos2 = find_if(pos1, testList.m_list.end(),find_func("2089-12-14 14:00:00"));
- int iCount1 = 0;
- std::list<RevFaxTask *>::difference_type iCount = distance(pos1,pos2);
- _Distance(pos1,pos2,iCount1);
- }
前段时间在学习了点STL的皮毛,某天接到个上级下达的命令,要我写一个算法,实现list表中的成员按其成员属性排序..遂翻书,发现sort函数,但没发现针对表成员属性再排序,但发现个sort支持自定义的operation Function做为参数传入,即自定义排序准则,便自己按普通函数格式写了个,compile,error...not success.上网查阅资料,找到了方法,写出关键部分,以备以后参考: