Tải bản đầy đủ - 0 (trang)
Chapter 81.  Prefer range operations to single-element operations

Chapter 81.  Prefer range operations to single-element operations

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

Summary

Don'tuseoarswhenthewindisfair(basedonaLatinproverb):

Whenaddingelementstosequencecontainers,prefertouse

rangeoperations(e.g.,theformofinsertthattakesapairof

iterators)insteadofaseriesofcallstothesingle-elementform

oftheoperation.Callingtherangeoperationisgenerallyeasier

towrite,easiertoread,andmoreefficientthananexplicitloop.

(SeealsoItem84.)



Discussion

Themorecontextyoucangiveafunction,thebetterthe

chancesthatitcandosomethingusefulwiththeinformation.In

particular,whenyoucallasinglefunctionandpassitapairof

iteratorsfirstandlastthatdelimitarange,itcanperform

optimizationsbasedonknowingthenumberofobjectsthatare

goingtobeadded,whichitobtainsbycomputing

distance(first,last).

Thesameappliesto"repeatntimes"operations,suchasthe

vectorconstructorthattakesarepeatcountandavalue.



Examples

Example1:vector::insert.Let'ssayyouwanttoaddn

elementsintoavectorv.Callingv.insert(position,x)

repeatedlycancausemultiplereallocationsasvgrowsits

storagetoaccommodateeachnewelement.Worse,each

single-elementinsertisalinearoperationbecauseithasto

shuffleoverenoughelementstomakeroom,andthismakes

insertingnelementswithrepeatedcallstothesingle-element

insertactuallyaquadraticoperation!Ofcourse,youcouldget

aroundthemultiple-reallocationproblembycallingreserve,

butthatdoesn'treducetheshufflingandthequadraticnature

oftheoperation.It'sfasterandsimplertojustsaywhatyou're

doing:v.insert(position,first,last),wherefirstand

lastareiteratorsdelimitingtherangeofelementstobeadded

intov.(Iffirstandlastareinputiterators,there'snowayto

determinethesizeoftherangebeforeactuallytraversingit,

andthereforevmightstillneedtoperformmultiple

reallocations;buttherangeversionisstilllikelytoperform

betterthaninsertingelementsindividually.)

Example2:Rangeconstructionandassignment.Callinga

constructor(orassignfunction)thattakesaniteratorrange

typicallyperformsbetterthancallingthedefaultconstructor(or

clear)followedbyindividualinsertionsintothecontainer.



References

[Meyers01]Đ5[Stroustrup00]Đ16.3.8



82.Usetheacceptedidiomstoreally

shrinkcapacityandreallyerase

elements

Summary

Discussion

Exceptions

References



Summary

Useadietthatworks:Toreallyshedexcesscapacityfroma

container,usethe"swaptrick."Toreallyeraseelementsfroma

container,usetheerase-removeidiom.



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

Chapter 81.  Prefer range operations to single-element operations

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

×