Tải bản đầy đủ - 0 (trang)
Chapter 80.  Prefer push_back to other ways of expanding a sequence

Chapter 80.  Prefer push_back to other ways of expanding a sequence

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

Summary

push_backallyoucan:Ifyoudon'tneedtocareaboutthe

insertposition,preferusingpush_backtoaddanelementto

sequence.Othermeanscanbebothvastlyslowerandless

clear.



Discussion

Youcaninsertelementsintosequencesatdifferentpointsusing

insert,andyoucanappendelementstosequencesinvarious

waysincluding:



vectorvec;//vecisempty

vec.resize(vec.size()+1,1);//veccontains{1}

vec.insert(vec.end(),2);//veccontains{1,2}

vec.push_back(3);//veccontains{1,2,3



Ofallforms,push_backalonetakesamortizedconstanttime.

Theotherforms'performancecanbeasbadasquadratic.

Needlesstosay,beyondsmalldatavolumesthatmakesthose

alternativespotentialscalabilitybarriers.(SeeItem7)

push_back'smagicissimple:Itexpandscapacityexponentially,

notbyafixedincrement.Hencethenumberofreallocations

andcopiesdecreasesrapidlywithsize.Foracontainer

populatedusingonlypush_backcalls,onaverageeachelement

hasbeencopiedonlyonceregardlessofthefinalsizeofthe

container.

Ofcourse,resizeandinsertcouldemploythesamestrategy,

butthatisdependentontheimplementation;onlypush_back

offerstheguarantee.

Algorithmscan'tcallpush_backdirectlybecausetheydon't

haveaccesstothecontainer.Youcanaskalgorithmstouse

push_backanywaybyusingaback_inserter.



Exceptions

Ifyouknowyou'readdingarange,evenattheendofa

container,prefertousearangeinsertionfunction(seeItem

81).

Exponentialgrowthisgenerouswithmemoryallocation.Tofinetunegrowth,callreserveexplicitlypush_back,resize,andthe

likenevertriggerreallocationiftheyhaveenoughspace.To

"right-size"avector,usetheshrink-to-fitidiom(seeItem82).



References

[Stroustrup00]§3.7-8,§16.3.5,§17.1.4.1



81.Preferrangeoperationstosingleelementoperations

Summary

Discussion

Examples

References



Summary

Don'tuseoarswhenthewindisfair(basedonaLatinproverb):

Whenaddingelementstosequencecontainers,prefertouse

rangeoperations(e.g.,theformofinsertthattakesapairof

iterators)insteadofaseriesofcallstothesingle-elementform

oftheoperation.Callingtherangeoperationisgenerallyeasier

towrite,easiertoread,andmoreefficientthananexplicitloop.

(SeealsoItem84.)



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

Chapter 80.  Prefer push_back to other ways of expanding a sequence

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

×