Professional Documents
Culture Documents
Go ]
Contents
IntroducingC++VectorsandArrays :QuickReference :KeyFacts :Details :Example :Exercise :Arrays :Strings :Hint :Glossary :Errors Abreviations
IntroducingC++VectorsandArrays
ThisisashortintroductiontothestandardvectorsavailableinC++.Vectorsareapowerfulyetsimpledata structure.
QuickReference
Vectorsaregoodwhenwehaveanunknownsequenceofsimilaritemstostoreandwewanttoaccessthemby theirsequencenumbers. Vectorsareheldinaspeciallibraryandcanbeusedinafilethathas
#include<vector>
KeyFacts
Youneedtorememberthefollowingfactsaboutvectors: 1. Avectorisanobjectthatcontainsasequenceofotherobjectsinsideit.
www.csci.csusb.edu/dick/cs201/vectors.html
1/6
5/14/12
2. Theobjectsinsidemustalltakeupthesameamountofstorage. 3. Theyarenumberedstartingwith0. Ifthewholevectoriscalledvthentheitemsinitarewrittenv[0],v[1],v[2],... Thelastitemisv[v.size()1]NOTv[v.size()]. 4. Newitemscanbe"pushed"ontotheendofthevector. 5. Thelastitemcanbe"popped"offofavector. 6. Vectorscanthereforechangesize. 7. Wecanfindoutthecurrentsizeofavector:v.size() 8. Vectorscanbeempty.Ifsov.empty()istrue. 9. Ifavectorisemptythenv[i]andv.pop....crash. 10. Vectorsareempty.bydefault,whencreated. 11. Vectorsshoulsbepassedbyreferencewheneverpossible.
Details
SupposethatTisanytypeorclasssayint,float,double,orthenameofaclass,then
vector<T>v
findhowmanyitemsareinv:
v.size()
pushtinTontotheendofv:
v.push_back(t)
popthebackofvoffv:
v.pop_back()
Accessthei'thitem(0<=i<size())withoutcheckingtoseeifitexists:
v[i]
Assignacopyofv1tov:
v=v1
Example
Supposethatwewanttoinputanunknownnumberofnumbersandthenprintthemoutforwardsandthen
www.csci.csusb.edu/dick/cs201/vectors.html
2/6
5/14/12
Thenwedescribethemainprogram:
intmain() { }//main vector<int>v intnumber cout<<"Inputsomenumbersandthenendtheinput\n" while(cin>>number){ v.push_back(number)
Finallythetwoproceduresthatprintoutthedata:
voidprint_backwards(constvector<int>&a) { for(inti=a.size()1i>=0i) cout<<a[i]<<""
cout<<endl cout<<""<<endl
}//print_backwards
and
voidprint(constvector<int>&a) { }//print for(inti=0i<a.size()++i) cout<<a[i]<<""
cout<<endl cout<<""<<endl
www.csci.csusb.edu/dick/cs201/vectors.html
3/6
5/14/12
Exercise
Download(withashiftclick!)theabovecodefrom[vectors.cpp],testit,andmodifyittoprintoutallthe evennumbereditems(0,2,4,6,...)andthenalltheoddones(1,3,5,...).
Arrays
TheoldestexampleofaContainerinC++isanarray.InCyouhadarraysandyouwouldwritecodelikethis:
constintMAX=10 floata[MAX] ... for(inti=0i<MAX++i) ... process(a[i])
Strings
ThedesignersoftheC++librarymadesurethatthe<string>librarysharesalotofcommonfeatureswith <vector>andothersequentialcontainers.Themaindifferencesare(1)<string>scanonlyholdcharacters,and (2)<string>shavesomeusefulextraoperationsavailable.
Hint
Ithelpstodrawdiagramsofvectorsandworkoutbyhand,onthesediagramswhatanalgorithm,oryour programisdoing.Pretendingtobeacomputercanteachyoualotaboutacomplexcomputation.
Glossary
1. container::=Adatastructurewhichcontainsanumberofdataitemsthatcangainandloseitemsastheprogram runs.Examplesincludevectors,lists,stacks,... 2. increment::operation=movinganiterator/pointer/indexontothenextiterator/pointer/indexvaluecommonly symbolizedby++inClikelanguages. 3. operation::=somethingthatcanbeappliedtoanobjecttoextractinformationfromitortochangeitsstate. 4. random_access::=beingabletodothingstoitemsinacontainerinanunpredictableordertypicallybyusingan integerasanindexorsubscript.
www.csci.csusb.edu/dick/cs201/vectors.html
4/6
5/14/12
Errors
Youmustalways#include<vector>ifyouusethewordvector. Youmustbesurethatallindicesorsubscriptsstaybetween0andsize()1inclusive. Tryingtochangethesizeofanarraydoesnotwork. Ifaprogramcompiles,loads,crashes,andthereisasubscriptoperator([...])thenchecktoseeifthe subscripteditemhasbeenputintothecontainerbeforethesubscriptedelementisaccessed.Avery commonerroristodeclareavectorwithnolengthandtouse[...]asifitcreatednewelements.It doesn't.Use'push_back(..)'toaddnewelementstoavector. Ifyouareunabletoshowthatasubscriptisinrangethenuseaconditionlikethefollowingtoguard thing[i]fromerrors:
0<=i&&i<thing.size()
butyoumustputatleastonespacebetweenthetwo">"symbols.Thefollowingiswrong:
vector<vector<int>>matrix
.........(endofsectionErrors)<<Contents|End>> .........(endofsectionIntroducingC++VectorsandArrays)<<Contents|End>>
Abreviations
1. Gnu::="Gnu'sNotUnix",alongrunningopensourceprojectthatsuppliesaverypopularC++compiler. 2. KDE::="KommonDesktopEnvironment".
www.csci.csusb.edu/dick/cs201/vectors.html
5/6
5/14/12
End
www.csci.csusb.edu/dick/cs201/vectors.html
6/6