1There is a method sort method in. list.Note that many methods of Vector are the same as those of list. However, this method does not exist in Vector.
(1). Sorting Integer Data
Void ListSortTest ()
{
List <int> num;
Num. push_back (1 );
Num. push_back (3 );
Num. push_back (2 );
Num. push_back (9 );
Num. push_back (5 );
Num. sort ();
List <int>: iterator vi;
For (vi = num. begin (); vi! = Num. end (); vi ++)
{
Cout <* vi <endl;
}
}
(2) Sort objects.Because list. sort () is sorted by default, the <operator must be overloaded. Therefore, we must reload this operator in the class object. Example:
Class student
{
Public:
Int age;
Student ()
{}
Student (int)
{
This-> age =;
}
Public:
Bool operator <(student B)
{
Return this-> age <B. age;
}
Bool operator> (student B)
{
Return this-> age> B. age;
}
};
Test Functions
Void ListSortTest ()
{
List <student> num;
Num. push_back (student (1 ));
Num. push_back (student (5 ));
Num. push_back (student (2 ));
Num. push_back (student (6 ));
Num. sort ();
// Sort (num. begin (), num. end ());
List <student>: iterator vi;
For (vi = num. begin (); vi! = Num. end (); vi ++)
{
Cout <vi-> age <endl;
}
Num. clear ();
}
In fact, list has two versions of sort member functions:
One is sort () without parameters, used for ascending order;
The other is with parameters.Sort (greater <T> pr)To implement descending order.
The latter's greater is actually a binary function (binary funtion) object prepared by VC,
See the source program in VC:
Template <class _ Ty>
Struct greater: binary_function <_ Ty, _ Ty, bool> {
Bool operator () (const _ Ty & _ X, const _ Ty & _ Y) const
{Return (_ X> _ Y );}
};
The member operator () of this binary function will call the ">" operator of the Data Type (student) corresponding to its parameters for mutual comparison.
Void ListSortTest ()
{
List <student> num;
Num. push_back (student (1 ));
Num. push_back (student (5 ));
Num. push_back (student (2 ));
Num. push_back (student (6 ));
List <student>: iterator vi;
Greater <student> pt;
Num. sort (pt );
For (vi = num. begin (); vi! = Num. end (); vi ++)
{
Cout <vi-> age <endl;
}
Num. clear ();
}
List <string> cannot be sorted in this way. I thought it was not sorted. Later I found that all files were not referenced. If the header file sting is included, I can use it.
2. Sort method of Algorithms
Void sort (iterator start, iterator end );
Void sort (iterator start, iterator end, StrictWeakOrdering cmp );
Bool cmp (int a, int B)
{
Return a> B;
}
Void VectorTest ()
{
Vector <int> num;
Num. push_back (1 );
Num. push_back (2 );
Num. push_back (3 );
Num. push_back (2 );
Num. push_back (9 );
Num. push_back (5 );
Sort (num. begin (), num. end ());
Sort (num. begin (), num. end (), cmp );
Vector <int>: iterator vi;
For (vi = num. begin (); vi! = Num. end (); vi ++)
{
Cout <* vi <endl;
}
}
This also realizes the sorting function of Vector.
How does list implement the sort method in Algorithms? I do not know yet.