functiontemplatenumericstd :3360 accumulate sum (1) template class hhdjy,classtaccumulate ) HHDjyfirst,hhdjy last,TiNi class T,classbinaryoperationtaccumulate (hhdjyfirst,hhdjy last,T init,binaryoperationbirate accumulatevaluesinrangereturng
thedefaultoperationistoaddtheelementsup,butadifferentoperationcanbespecifiedasbinary _ op。
thebehaviorofthisfunctiontemplateisequivalentto :
123456789 template class hhdjy,classtaccumulate(HHDjyfirst,hhdjy last,T init ) { while } first!=last(init=init*first; //or:init=binary_op(init,*first ) for the binary_op version first; } return init; }
Parameters first,lastinputiteratorstotheinitialandfinalpositionsinasequence.therangeusedis [ first,last,whichcontaintainsalsaled includingtheelementpointedbyfirstbutnottheelementpointedbylast.initialvaluefortheaccumulator.binary _ opbinaryoperation entandanelementintherangeassecond,andwhichreturnsavaluethatcanbeasignedtotypet。
thiscaneitherbeafunctionpointerorafunctionobject。
theoperationshallnotmodifytheelementspassedasitsarguments。
returnvaluetheresultofaccumulatinginitandalltheelementsintherange [ first,last。
example 123456789101121314151617181920223242526272829303132/accumulate example # include iostream//STD 3360360 cout # STD 33333330 STD : accumulateintmyfunction (intx,int y ) {return x 2*y; }struct myclass {int operator (() int x,int y ) ) {return x 3*y; }} myobject; int main () { int init=100; int numbers [ ]={ 10,20,30 }; STD : cout ' usingdefaultaccumulate : '; STD : cout STD : accumulate (numbers,numbers 3,init ); std:cout 'n '; STD : cout ' using functional ' s MINUS : '; STD : cout STD : accumulate (numbers,numbers 3,init,std:minusint ) ); std:cout 'n '; STD : cout ' usingcustomfunction : '; STD : cout STD : accumulate (numbers,numbers 3,init,myfunction ); std:cout 'n '; STD : cout ' usingcustomobject : '; STD : cout STD : accumulate (numbers,numbers 3,init,myobject ); std:cout 'n '; 返回0; } Edit Run
输出:
usingdefaultaccumulate 3360160 using functional ' s MINUS :40 usingcustomfunction 3360220 usingcustomobject 3360280 complexitylinnninial
dataracestheelementsintherange [ first,last ] are accessed (eachelementisaccessedexactlyonce )。
exceptionsthrowsifanyofbinary _ op,theassignmentsoranoperationonaniteratorthrows。
notethatinvalidargumentscauseundefinedbehavior。