Research on STL Sort Algorithm

xiaoxiao2021-03-06  80

Sudaobo Sudaobo@21cn.com There are two types: ----------------------------------- -------------------------------- Template void sort (ranit fist, ranit last); template Void Sort (Ranit Fist, Ranit Last, PRED PR); ---------------------------------------------------------------------------------------------------------- --------------------------------------- First Template, Sort Rapid [First, The elements between the Last are generated, producing a sequence of Operate #include // include algorithms # include usingspace std; bool pr (Int S1, INT S2) {RETURN S1> S2;} int main (int Argc) , Char * argv []) {Vector :: Iterator i; vec.push_back (10); vec.push_back (3); vec.push_back (7); sort (vec.begin ), Vec.end (), pr); // sort the vectorfor (i = vec.begin (); i! = Vec.end (); i ) {cout << * i << endl;} returnograph; }

Example 2:

-------------------------------------------------- ------------------------------------

// tmp1.cpp: defines the entry point for the console application.//

#include "stdafx.h" #include #include // incrude algorithms # include #include

Using namespace std;

Class myless {

PUBLIC: BOOL Operator () (Const Int & a, Const Int & b) {Return A

INT Main (int Argc, char * argv []) {Vector vec; vector :: Iterator i; vec.push_back (10); vec.push_back (3); vec.push_back (7); sort (vec.begin (), vec.end (), myless ()); // sort the vectorfor (i = vec.begin (); i! = vec.end (); i ) {cout << * i <

Return 0;}

Example 3:

-------------------------------------------------- ----------------------

// tmp1.cpp: defines the entry point for the console application.//

#include "stdafx.h" #include #include // incrude algorithms # include #include

Using namespace std;

TYPEDEF STRUCT; STRING LAST;

Bool Sortbyfirst (Const Name & N1, Const Name & n2) {return (n1.first

Bool Sortbylast (Const Name & N1, Const Name & n2) {return (n1.last

INT main (int Argc, char * argv []) {Vector contacts; vector :: item j; name tmp; tmp.first = "liu"; tmp.last = "bei"; contacts.push_back (TMP);

Tmp.first = "zhao"; tmp.last = "yun"; Contacts.push_back (TMP);

Tmp.first = "gun"; tmp.last = "="; contacts.push_back (tmp);

Tmp.first = "zhang"; tmp.last = "fei"; Contacts.push_back (TMP);

COUT << "by first:" << endl;

Sort (Contacts.Begin (), Contacts.end (), Sortbyfirst);

For (j = contacts.begin (); j! = contacts.end (); j ) {cout << j-> first << "<< j-> last << endl;}

Cout << "by last:" << Endl;

Sort (Contacts.Begin (), Contacts.end (), Sortbylast;

转载请注明原文地址:https://www.9cbs.com/read-121535.html

New Post(0)