Research on STL Sort Algorithm [Reserved]

xiaoxiao2021-03-06  19

Author: sudaobo sudaobo@21cn.com2004-8-4

There are two sort templates: -------------------------------------------- ------------------------- Template void sort (ranit fist, ranit last); Template

Example: ------------------------------ // Tmp1.cpp: defines the entry point for the console application.//

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

Using namespace std;

BOOL PR (Int S1, INT S2) {RETURN S1> S2;}

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 (), pr); // sort the vector

For (i = vec.begin (); i! = vec.end (); i ) {cout << * i << endl;}

Return 0;}

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;

For (j = contacts.begin (); j! = contacts.end (); j ) {cout << j-> first << "<< j-> last << endl;} return 0;} for comparison Simple structures, preserving objects, do not use pointers,

Struct REC {REC (INT NID) {ID = NID;

Bool Operator> (Const Rec & Recarg) Const {Return ID

INT ID;

List M_List;

INT main () {m_list.push_back (REC (8)); m_list.push_back (REC (2)); m_list.push_back (REC (3));

M_List.Sort (Greater ()); cout << m_list.begin () -> id << Endl; system ("pause"); return 0;}

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

New Post(0)