Correction of the Sort function of std :: list in VC6
Xu Yanbai
Do you feel very good? Is it good to use the C standard library? I found such a problem in the process of doing the project, saved in my list is an object, I am sorting according to a keyword of the object in the process of using the list. You may say: This is not easy! There is a sort function in the list. Nice, standard C certainly supports custom operator sort functions, if you use VC7 or G , there is no problem, if you are using the program code using VC6.0, you can't compile:
#include
#include
#include
#include
Struct s {
Std :: string firstname;
Std :: string secondname;
Int ID;
}
Struct comp {
PUBLIC:
BOOL Operator () (S & A, S & B)
{
Return A.ID } } Int main (int Argc, char * argv []) { Std :: List Std :: List S a; A.firstname = "DFADF"; A.ID = 5; MYLIST.PUSH_BACK (a); A.firstname = "Get"; A.ID = 9; MYLIST.PUSH_BACK (a); A.firstName = "xxx"; A.ID = 7; MYLIST.PUSH_BACK (a); A.firstname = "GGGG"; A.ID = 25; MYLIST.PUSH_BACK (a); MYList.sort (Comp ()); For (iter = mylist.begin (); it! = mylist.end (); iTer) { Std :: cout << static_cast } Std :: cout << std :: endl; Return 0; } I have discovered the List document, there is such a line Typedef Greater <_ty> _pr3; And its Sort function is also using this definition operator. Void Sort (_PR3 _PR) ...... .. No wonder our program cannot use our own comparison operator function COMP. After this analysis, we want to use this feature, you must make changes to the definition. To know that the STL series file in VC6 is the old antique in 1998, it seems that there is no competition to develop the development of the software is unfavorable. I have modified the MERGE and SORT functions in the list file, and the specific code is as follows: Template sort (_ORDERING __COMP) { IF (2 <= size ()) {const size_t _maxn = 15; _Myt _x (allocator), _a [_maxn 1]; SIZE_T_N = 0; While (! EMPTY ()) {_X.SPLICE (_X.BEGIN (), * this, begin ()); SIZE_T_I; For (_i = 0; _i <_n&&! _a [_i] .empty (); _i) {_A [_i] .merge (_x, __comp); _A [_i] .swap (_X); IF (_i == _maxn) _A [_i] .merge (_x, __comp); Else {_A [_i] .swap; IF (_i == _n) _ n;}}} While (0 <_n) Merge (_A [--_ n], __comp);}} You can block the original two corresponding functions in the file. After this modification, our program can run correctly. Are you a heartbeat, try it. mylist; :: iterator it; (* it) .id << "/ t";