Vous êtes sur la page 1sur 2

CPSC 490 The <algorithm> file in C++

Sorting
#include<algorithm>
ThealgorithmfileinC++provideseveralcommonalgorithmsthatareveryuseful. Mostofthese
algorithmsoperateonarangeofelements,whichcanbespecifiedusingiterators.Themostcommon
algorithmisperhapssort.Thefollowingdemonstrateshowtosortavectorofintegers.

Example1:
vector<int>v;
v.push_back(3);
v.push_back(1);
v.push_back(2);
sort(v.begin(),v.end());//sortvinincreasingorder

Thesortfunctiontakestwoparameters,AandB,bothiterators,andsortstherange[A,B)inO(Nlog
(N))time,inincreasingorder.TherequirementisthatAandBarebothrandomaccessiterators,and
sowecannotusesorttosortalist,forexample.So,whatifwewanttosortindecreasingorder,orto
sortsomespecialdatastructure?Wecanalwaysdefineourowncomparisonfunctionandusethat.

Example2:
structobject{
intweight,cost;
};

structComparisonFunctor{
booloperator()(constobject&a,constobject&b)const{
if(a.cost!=b.cost)returna.cost<b.cost;
elsereturna.weight>b.weight;
}
};

vector<object>vo;
//...insertsomeobjectstothevector

//A.sortthevectorfirstbylowestcost,thenbygreatestweight
sort(vo.begin(),vo.end(),ComparisonFunctor());

//B.wecanalsodefineasetusingthefunctor.
//thefollowingcopiesthevectortotheset,whichwillbekeptin
//sortedorder(BinarySearchTree)
set<object,ComparisonFunctor>myset(vo.begin(),vo.end());

Weusea functionobject,or functor intheaboveexample. Thisallowsustouseitasaclassin


templatizedcontainers,likeset,orsimplyasacomparisionfunction.Notethatinthiscase,wehave
tohaveacomparatorbecausewithoutit,thecompilerwilltrytousethe<operatortocompareto
objects,andsincethereisnosuchoperatordefined,theprogramwillnotcompile.Ifyoudonotneed
thecomparisonfunctionasafunctor,thenjustcreateitasanormalfunction,like:

Example3:
boolcompare(constobject&a,constobject&b){
if(a.cost!=b.cost)returna.cost<b.cost;
elsereturna.weight>b.weight;
}
CPSC 490 The <algorithm> file in C++

//andtouseit...
sort(vo.begin(),vo.end(),compare);//nobracketsthistime

next_per m u t a t i o n()
#include<algorithm>
Anotherusefulfunctionin<algorithm>isnext_permutation().Onceagain,itstwoparametersare
iteratorsdefiningarange[A,B).Butfirst,weneedalittlebackgroundonpermutations.

GivenafinitesetS={1,2,...,n},therearen!waysoflistingtheelementsofthesetonalinen!
differentorderings(orpermutations)ofelements.Forexample,forasetof3elements,thereare3!=
6 different permutations: (1,2,3), (1,3,2), (2,1,3), (2,3,1), (3,1,2) and (3,2,1). Note that the 6
permutationsareorderedlexicographicallyfromthesmallest(asortedlist)tothelargest(thelist
sortedbackwards).Wecanextendthenotionofapermutationtocollectionswithdupilcateelements.
Forexample,thereare10permutationsof(1,1,2,2,2).Theyare(1,1,2,2,2),(1,2,1,2,2),(1,2,2,1,2),
(1,2,2,2,1),(2,1,1,2,2),(2,1,2,1,2),(2,1,2,2,1),(2,2,1,1,2),(2,2,1,2,1)and(2,2,2,1,1).Permutations
havemanyuses;especially,inbruteforcealgorithmswhereweneedtoenumerateallofthedifferent
orderingsofacollectionofelements.

Thenext_permutation()functiontakesarangethatcontainsapermutationandmodifiesthatrangeto
containthelexicographicallynextpermutation.

Example4:
vector<int>v;
v.push_back(2);v.push_back(2);v.push_back(1);v.push_back(2);
next_permutation(v.begin(),v.end());

Thevectorvstartsoutwith(2,2,1,2).Afterexecutingthefunction,vwillcontain(2,2,2,1).

So what happens when the input range already contains the largest permutation? In this case,
next_permutation()willwraparoundtoproducethesmallestpermutationagain.Itwillalsoreturn
falseinthiscase.Inallothercases,itreturnstrue.Hereishowwecanprintallthepermutationsofa
collection.

Example5:
vector<int>v;
//...fillinvwithsomeintegers
sort(v.begin(),v.end());
do{
for(inti=0;i<(int)v.size();i++)cout<<""<<v[i];
cout<<endl;
}while(next_permutation(v.begin(),v.end()));

First,weneedtosortvtogetthesmallestpermutation.Thenthedowhileloopwillrepeatthesetwo
stepsprintapermutationandproducethenextone.Whenwereachthelargestpermutation,wewill
printit,thenproducethesmallestoneagainandexittheloop.Therefore,aftertheloophasfinished,
v'selementsareonceagaininsortedorder.

Thereareotherveryusefulfunctionsin<algorithm>,likestable_sort()andlower_bound().Youcan
readaboutthemhere:http://www.sgi.com/tech/stl.Theymightcomeinhandy.

Vous aimerez peut-être aussi