Tải bản đầy đủ - 0 (trang)
Chapter 86.  Use the right STL sort algorithm

Chapter 86.  Use the right STL sort algorithm

Tải bản đầy đủ - 0trang

Summary

Sort"justenough:"Understandwhateachofthesorting

algorithmsdoes,andusethecheapestalgorithmthatdoes

whatyouneed.



Discussion

Youdon'talwaysneedafullsort;youusuallyneedless,and

rarelyyouneedmore.Ingeneralorderfromcheapesttomost

expensive,yourstandardsortingalgorithmoptionsare:

partition,stable_partition,nth_element,partial_sort

(withitsvariantpartial_sort_copy),sort,andstable_sort.

Usetheleastexpensiveonethatdoestheworkyouactually

need;usingamorepowerfuloneiswasteful.

partition,stable_partition,andnth_elementruninlinear

time,whichisnice.

nth_element,partial_sort,sort,andstable_sortrequire

random-accessiterators.Youcan'tusethemifyouhaveonly

bidirectionaliterators(e.g.,list::iterators).Ifyouneed

thesealgorithmsbutyoudon'thaverandom-accessiterators,

considerusingtheindexcontaineridiom:Createacontainer

thatdoessupportrandom-accessiterators(e.g.,avector)of

iteratorsintotherangeyouhave,andthenusethemore

powerfulalgorithmonthatusingadereferencingversionof

yourpredicate(onethatdereferencestheiteratorsbeforedoing

itsusualcomparison).

Usethestable_versionsonlyifyouneedtopreservethe

relativeorderingofequalelements.Notethatpartial_sort

andnth_elementaren'tstable(meaningthattheydon'tkeep

equivalentelementsinthesamerelativeordertheywerein

beforethesort),andtheyhavenostandardizedstableversions.

Ifyouotherwisewantthesealgorithmsbutneedstability,you

probablywantstable_sort.

Ofcourse,don'tuseanysortingalgorithmatallifyoudon't

haveto:Ifyouareusingastandardassociativecontainer

(set/multisetormap/multimap)orthepriority_queue



adapter,andonlyneedonesortorder,theelementsinthe

containerstaysortedallthetime.



Examples

Example1:partition.Usepartitiontojustdividetherange

intotwogroups:allelementsthatsatisfythepredicate,

followedbyallelementsthatdon't.Thisisallyouneedto

answerquestionslikethese:

"WhoareallthestudentswithagradeofB+orbetter?"For

example,partition(students.begin(),

students.end(),GradeAtLeast("B+"));doesthework

andreturnsaniteratortothefirststudentwhosegradeis

notatleastB+.

"Whatarealltheproductswithweightlessthan10kg?"For

example,partition(products.begin(),

products.end(),WeightUnder(10));doestheworkand

returnsaniteratortothefirstproductwhoseweightis10kg

orless.

Example2:nth_element.Usenth_elementtoputasingle

elementinthecorrectn-thpositionitwouldoccupyiftherange

werecompletelysorted,andwithallotherelementscorrectly

precedingorfollowingthatn-thelement.Thisisallyouneedto

answerquestionslikethese:

"Whoaremytop20salespeople?"Forexample,

nth_element(s.begin(),s.begin()+19,s.end(),

SalesRating);putsthe20bestelementsatthefront.

"Whatistheitemwiththemedianlevelofqualityinthis

productionrun?"Thatelementwouldbeinthemiddle

positionofasortedrange.Tofindit,donth_element(

run.begin(),run.begin()+run.size()/2,run.end(),



ItemQuality);.

"Whatistheitemwhosequalityisatthe75thpercentile?"

Thatitemwouldbe25%ofthewaythroughthesorted

range.Tofindit,donth_element(run.begin(),

run.begin()+run.size()*.25,run.end(),ItemQuality

);.

Example3:partial_sort.partial_sortdoestheworkof

nth_element,plustheelementsprecedingthen-thareallin

theircorrectsortedpositions.Usepartial_sorttoanswer

questionssimilartothosenth_elementanswers,butwhereyou

needtheelementsthatmatchtobesorted(andthosethat

don'tmatchdon'tneedtobesorted).Thisisallyouneedto

answerquestionslike,"Whoarethefirst-,second-,andthirdplacewinners?"Forexample,partial_sort(

contestants.begin(),contestants.begin()+3,

contestants.end(),ScoreCompare);putsthetopthree

contestants,inorder,atthefrontofthecontainerandnomore.



Exceptions

Althoughpartial_sortisusuallyfasterthanafullsort

becauseithastodolesswork,ifyouaregoingtobesorting

most(orall)oftherange,itcanbeslowerthanafullsort.



References

[Austern99]Đ13.1[Bentley00]Đ11[Josuttis99]Đ9.2.2

[Meyers01]Đ31[Musser01]Đ5.4,Đ22.26[Stroustrup00]

Đ17.1.4.1,Đ18.7



87.Makepredicatespurefunctions

Summary

Discussion

Examples

References



Summary

Predicatepurity:Apredicateisafunctionobjectthatreturnsa

yes/noanswer,typicallyasaboolvalue.Afunctionispurein

themathematicalsenseifitsresultdependsonlyonits

arguments(notethatthisuseof"pure"hasnothingtodowith

purevirtualfunctions).

Don'tallowpredicatestoholdoraccessstatethataffectsthe

resultoftheiroperator(),includingbothmemberandglobal

state.Prefertomakeoperator()aconstmemberfunctionfor

predicates(seeItem15).



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 86.  Use the right STL sort algorithm

Tải bản đầy đủ ngay(0 tr)

×