You are on page 1of 6

5/14/12

CS201: Introducing C++ Vectors and Arrays

[SkipNavigation][CSUSB]/[CNS]/[CompSciDept]/[RJBotting]/[CSci201]/vectors [Syllabus][Schedule][Glossary][Labs][Projects][Resources][Grading][Contact][Search Notes:[01][02][03][04][05][06][07][08][09][10][11][12][13][14][15][16][17][18][19][20] Labs:[01][02][03][04][05][06][07][08][09][10] TueSep1815:35:18PDT2007

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>

atitsbeginning. Declaration vector<type>v(initial_size) Accessors v.empty(),v.size(),v.front(),v.back() Mutators v.push_back(T),v.pop_back() Operators v[int],v.at(int),v1=v2,v1==v2

KeyFacts
Youneedtorememberthefollowingfactsaboutvectors: 1. Avectorisanobjectthatcontainsasequenceofotherobjectsinsideit.

www.csci.csusb.edu/dick/cs201/vectors.html

1/6

5/14/12

CS201: Introducing C++ Vectors and Arrays

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

declaresanewandemptyvectorcalledv.Givenobjectvdeclareliketheaboveyoucandothefollowing thingswithit: testtoseeifvisempty:


v.empty()

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

CS201: Introducing C++ Vectors and Arrays

backwards,usingavector.Wewillpushintsontothebackofavectorcalledv.Wewillthenprinteachitemin vinturn.Finallywewillprintthevectorbackwards.Youcandownloadthecodefrom[vectors.cpp]buthere arethehighlights.Firstwemustdeclarethefacilitieswewanttouse


#include<iostream> #include<vector> voidprint(constvector<int>&)//utilityfunctionoutputsavectorofints voidprint_backwards(constvector<int>&)

Thenwedescribethemainprogram:
intmain() { }//main vector<int>v intnumber cout<<"Inputsomenumbersandthenendtheinput\n" while(cin>>number){ v.push_back(number)

}//while(more) print(v) print_backwards(v)

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

CS201: Introducing C++ Vectors and Arrays

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])

Arraysarelikevectorsexceptthat: 1. 2. 3. 4. 5. Theyhaveafixedsizespecifiedinthedeclaration. Theyarefasterthanvectors. Youcannotaddordeleteitemsfromanarray. Thesyntaxissimpler. Theabsolutelynosafetybelt:ifanindexhaswrongvalue,youcrash.

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

CS201: Introducing C++ Vectors and Arrays

5. vector::container=avectorisasequentialcontainerthatisoptimizedtoallowefficientrandom_accessof itemsbyusinganindex.Vectorsarearegiveninacontiguousblockofstoragespace.Vectorsareuseful wheneverdatamustbestoredinoneorderaccessedinadifferentone.Avectorisadynamicarrayanarray thatcangrowwhenneeded.[Vectors]

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()

Ifaprogramcompiles,loadsandcrashesandithasapop_back,functionthanmakesurethatthereisan itemtobe"popped"!Incodeyoucanusetheemptyfunctiontoguardstatementsthatcontain"pop"from blowingup. Onsomeoldercompilersandlibrarieswhenyouneeda<string>aswellas<vector>youneedto


#include<string>

beforeincludingthelistorvectorratherinthereverseorder!Olderstringlibraryappeartodefinesome specialversionsofvectorandlistoperatorsandtheoldercompilerscannotmakeupitsmindwhichto use. Ifthestandard<vector>isnotfoundthenyouareusinganolderC++compiler. Youcanhavevectorsofvectors:


vector<vector<int>>matrix

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

CS201: Introducing C++ Vectors and Arrays

3. TBA::="ToBeAnnounced",somethingIshoulddo. 4. TBD::="ToBeDone",somethingyouhavetodo. 5. UML::="UnifiedModelingLanguage",[uml.html](beginner'sintroductiontotheUML).

End

www.csci.csusb.edu/dick/cs201/vectors.html

6/6

You might also like