Tải bản đầy đủ - 0 (trang)
Chapter 11.  Science and Mathematics

Chapter 11.  Science and Mathematics

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

Recipe11.15.ImplementingaConstant-SizedMatrix

Recipe11.16.MultiplyingMatricies

Recipe11.17.ComputingtheFastFourierTransform

Recipe11.18.WorkingwithPolarCoordinates

Recipe11.19.PerformingArithmeticonBitsets

Recipe11.20.RepresentingLargeFixed-WidthIntegers

Recipe11.21.ImplementingFixed-PointNumbers



Introduction

C++isalanguagewellsuitedforscientificandmathematical

programming,duetoitsflexibility,expressivity,andefficiency.

OneofthebiggestadvantagesofC++fornumericalprocessing

codeisthatitcanhelpyouavoidredundancy.

Historically,numericalcodeinmanyprogramminglanguages

wouldrepeatalgorithmsoverandoverfordifferentkindsof

numericaltypes(e.g.,short,long,single,double,custom

numericaltypes,etc.).C++providesasolutiontothisproblem

ofredundancythroughtemplates.Templatesenableyouto

writealgorithmsindependantlyofthedatarepresentation,a

techniqueknowncommonlyasgenericprogramming.

C++isnotwithoutitsshortcomingswithregardstonumerical

processingcode.ThebiggestdrawbackwithC++incontrastto

specializedmathematicalandscientificprogramming

languagesisthatthestandardlibraryislimitedintermsof

supportofalgorithmsanddata-typesrelevanttonumerical

programming.Thebiggestoversightsinthestandardlibraryare

arguablythelackofmatrixtypesandarbitraryprecision

integers.

Inthischapter,Iwillprovideyouwithsolutionstocommon

numericalprogrammingproblemsanddemonstratehowtouse

genericprogrammingtechniquestowritenumericalcode

effectively.Whereappropriate,Iwillrecommendwidelyused

open-sourcelibrarieswithcommerciallyfriendlylicensesanda

proventrackrecord.Thischapterintroducesthebasic

techniquesofgenericprogramminggraduallyfromrecipeto

recipe.

ManyprogrammersusingC++stilldistrusttemplatesand

genericprogrammingduetotheirapparentcomplexity.When

templateswerefirstintroducedintothelanguagetheywere



neitherwellimplementednorwellunderstoodbyprogrammers

andcompilerimplementersalike.Asaresult,many

programmers,includingyourstruly,avoidedgeneric

programminginC++forseveralyearswhilethetechnology

matured.

Today,genericprogrammingiswidelyacceptedasapowerful

andusefulprogrammingparadigm,andissupportedbythe

mostpopularprogramminglanguages.Furthermore,C++

compilertechnologyhasimprovedbyleapsandbounds,and

moderncompilersdealwithtemplatesinamuchmore

standardizedandefficientmanner.Asaresult,modernC++isa

particularlypowerfullanguageforscientificandnumerical

applications.







Recipe11.1.ComputingtheNumberofElements

inaContainer

Problem

Youwanttofindthenumberofelementsinacontainer.



Solution

Youcancomputethenumberofelementsinacontainerby

usingthesizememberfunctionorthedistancefunctionfromthe

headerasinExample11-1.



Example11-1.ComputingtheNumberof

ElementsinaContainer

#include

#include

#include

usingnamespacestd;

intmain(){

vectorv;

v.push_back(0);

v.push_back(1);

v.push_back(2);

cout<
cout<
}



TheprograminExample11-1producesthefollowingoutput:

3

3



Discussion

Thesizememberfunction,whichreturnsthenumberof

elementsinastandardcontainer,isthebestsolutionincases

wherethecontainerobjectisaccessible.Ialsodemonstrated

distanceinExample11-1,becausewhenwritinggenericcodeit

iscommontoworkwithonlyapairofiterators.Whenworking

withiterators,youoftendon'thaveaccesstothetypeofthe

containerortoitsmemberfunctions.

Thedistancefunction,likemostSTLalgorithms,isactuallya

templatefunction.Sincethetypeofthetemplateargumentcan

bededucedautomaticallybythecompilerfromthefunction

arguments,youdon'thavetoexplicitlypassitasatemplate

parameter.Youcan,ofcourse,writeoutthetemplate

parameterexplicitlyifyouwantto,asfollows:



cout<::iterator>(v.begin(),v.end())



Thedistancefunctionperformancedependsonthekindof

iteratorused.Ittakesconstanttimeiftheinputiteratorisa

random-accessiterator;otherwise,itoperatesinlineartime.

(IteratorconceptsareexplainedinRecipe7.1.)



SeeAlso

Recipe15.1







Recipe11.2.FindingtheGreatestorLeastValue

inaContainer

Problem

Youwanttofindthemaximumorminimumvalueinacontainer.



Solution

Example11-2showshowtofindtheminimumandmaximum

elementsinacontainerbyusingthefunctionsmax_elementand

min_elementfoundintheheader.Thesefunctionsreturn

iteratorsthatpointtothefirstoccurenceofanelementwiththe

largestorsmallestvalue,respectively.



Example11-2.Findingtheminimumormaximum

elementfromacontainer

#include

#include

#include

usingnamespacestd;

intgetMaxInt(vector&v){

return*max_element(v.begin(),v.end());

}

intgetMinInt(vector&v){

return*min_element(v.begin(),v.end());

}



intmain(){

vectorv;

for(inti=10;i<20;++i)v.push_back(i);

cout<<"mininteger="<
cout<<"maxinteger="<
}



TheprograminExample11-2producesthefollowingoutput:

mininteger=10

maxinteger=19



Discussion

Youmayhavenoticedthedereferencingofthereturnvalue

fromthecallstomin_elementandmax_element.Thisisbecausethese

functionsreturniteratorsandnotactualvalues,sotheresults

havetobedereferenced.Youmayfinditaminorinconvenience

tohavetodereferencethereturntype,butitavoids

unnecssarilycopyingthereturnvalue.Thiscanbeespecially

significantwhenthereturnvaluehasexpensivecopysemantics

(e.g.,largestrings).

Thegenericalgorithmsprovidedbythestandardlibraryare

obviouslyquiteuseful,butitismoreimportantforyoutobe

abletowriteyourowngenericfunctionsforgettingthe

minimumandmaximumvaluefromacontainer.Forinstance,

let'ssaythatyouwantasinglefunctionwhichreturnsthe

minimumandmaximumvaluesbymodifyingreference

parametersinsteadofreturningtheminapairorsomeother

structure.ThisisdemonstratedinExample11-3.



Example11-3.Genericfunctionforreturningthe

minimumandmaximumvalue

#include

#include

#include

usingnamespacestd;



template

voidcomputeMinAndMax(Iter_Tfirst,Iter_Tlast,Value_T&min,

min=*min_element(first,last);

max=*max_element(first,last);

}

intmain(){

vectorv;

for(inti=10;i<20;++i)v.push_back(i);

intmin=-1;

intmax=-1;

computeMinAndMax(v.begin(),v.end(),min,max);

cout<<"mininteger="<
cout<<"maxinteger="<
}



InExample11-3,IhavewrittenacomputeMinAndMaxfunction

templatewhichtakestwotemplateparameters,oneisthetype

oftheiteratorandtheotheristhetypeoftheminimumand

maximumvalues.Becausebothtemplateparametersarealso

functionparameters,theC++compilerisabletodeducethe

twoseparatetypes,Iter_TandValue_T,justasIdemonstratedin

Recipe11.1.Thissavesmefromhavingtospecifythetemplate

parametersexplicitlylike:



compute_min_max::iterator,int>(...)



Themin_elementandmax_elementfunctionsworkbyusingoperator<

tocomparethevaluesreferencedbytheiterators.Thismeans

thatifaniteratordoesnotreferenceatypethatsupports

comparisonthroughtheless-thanoperator,acompilererrorwill

result.Themin_elementandmax_elementfunctions,however,canbe

usedwithauser-definedcomparisonfunctor,i.e.,afunction

pointerorafunctionobject.



Functors

ManySTLalgorithmsacceptuser-definedfunctionobjectsorpointers.

Collectively,theseareknownasfunctors.Sometimesintheliterature,theterm

"functionobject"isusedinterchangeablywiththetermfunctor,butI'vereserved

theuseoffunctionobjectforreferingspecificallytoinstancesofclassesor

structsthatoverloadoperator().

Ofthetwooptions,whichoneshouldyouuse?Inthemajorityofcases,a

functionobjectismoreefficientbecausemostcompilerscanmoreeasilyinlinea

functionobject.

Anotherreasonforusingafunctionobjectisthatitcanhaveastate.Youcan

passvaluestoitsconstructor,whichitstoresinitsfieldsforuselateron.This

givesfunctionobjectsanexpressiveequivalencyaswiththeconceptofclosures

foundinotherprogramminglanguages.

Finally,functionobjectscanbedefinedwithinanotherfunctionorclass.Function

pointershavetobedeclaredinanamespacescope.



Thespecifickindoffunctorneededbymin_elementandmax_element

isonethattakestwovaluesofthetypereferencedbythe

iteratorandreturnsabooleanvalueifoneislessthantheother.

Afunctorwhichreturnsabooleanvalueisknownasapredicate.

Considerforinstancethecaseoffindingthegreatestelementof

asetofuserdefinedtypeinExample11-4.



Example11-4.Findingthemaximumelementfor

user-definedtypes

#include

#include

#include

usingnamespacestd;



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

Chapter 11.  Science and Mathematics

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

×