STL Containers & Iterators
STL Containers & Iterators
&Iterators
Containers as a form of Aggregation
Fixed aggregation
An object is composed of a fixed set of component
objects
Variable aggregation
An object is composed of a variable set of
component objects
Containers
An object exists in its own rights but it is able to hold
other objects.
Generic Containers
Containerclassesarebuildingblocksusedtocreateobjectoriented
programs,andtheymaketheinternalsofaprogrammucheasier
toconstruct.
Acontainerclassdescribesanobjectthatholdsotherobjects.
Containerclassesaresoimportantthattheywereconsidered
fundamentaltoearlyobjectorientedlanguages.
TheC++approachtocontainersisbasedontemplates.The
containersintheStandardC++libraryrepresentabroadrangeof
datastructuresdesignedtoworkwellwiththestandardalgorithms
andtomeetcommonsoftwaredevelopmentneeds.
Standard Template Library
Thestandardtemplatelibrary(STL)contains
Containers
Iterators
Algorithms
Acontainerisawaystoreddataisorganizedinmemory,for
exampleanarrayofelements.
AlgorithmsintheSTLareproceduresthatareappliedto
containerstoprocesstheirdata,forexamplesearchforan
elementinanarray,orsortanarray.
Iteratorsareageneralizationoftheconceptofpointers,
theypointtoelementsinacontainer,forexampleyoucan
incrementaniteratortopointtothenextelementinanarray.
Containers in Software
Acontainerisusuallyinstantiatedasanobjectofcontainerclass
Acontainerclassobjectencapsulatesinsideitamechanismfor
containingotherobjects
Italsoprovidesthenecessarybehaviourforadding,removingand
accessingtheobjectsitcontains
Acontainerclassgivestheopportunityofreuseindifferent
programs:
thisfreestheprogrammerfromhavingtorecreatecomplexdata
structuresineveryprogramtomanagecomplexdatastructure
Some Containers Types
Sequentialcontainers:vector,listanddeque;Theystoreelements
inclientvisibleorder
Associativecontainers:map,multimap,setandmultiset
ContainersAdapters:queue,priorityqueueandstack
Sequence Containers
Asequentialcontainerstoreselementsinasequence.In
otherwordseachelement(exceptforthefirstandlast
one)isprecededbyonespecificelementandfollowedby
another,<vector>,<list>and<deque>are
sequentialcontainers
InanordinaryC++arraythesizeisfixedandcannot
changeduringruntime,itisalsotedioustoinsertor
deleteelements.Advantage:quickrandomaccess
<vector>isanexpandablearraythatcanshrinkor
growinsize,butstillhasthedisadvantageofinsertingor
deletingelementsinthemiddle
Sequence Containers
<list>isadoublelinkedlist(eachelementhastwo
pointerstoitssuccessorandpredecessor),itisquickto
insertordeleteelementsbuthasslowrandomaccess
<deque>isadoubleendedqueue,thatmeansonecan
insertanddeleteobjectsfrombothends,itisakindof
combinationbetweenastack(LIFO)andaqueue
(FIFO)andconstitutesacompromisebetweena
<vector>anda<list>
Associative Containers
Anassociativecontainerisnonsequentialbut
usesakeytoaccesselements.Thekeys,
typicallyanumberorastring,areusedbythe
containertoarrangethestoredobjectsina
specificorder,forexampleinadictionarythe
entriesareorderedalphabetically.
Associative Containers
A<set>storesanumberofitemswhichcontainkeys.The
keysaretheattributesusedtoordertheitems,forexample
asetmightstoreobjectsoftheclassBookswhichareordered
alphabeticallyusingtheirtitle
A<map>storespairsofobjects:akeyobjectandan
associatedvalueobject.A<map>issomehowsimilartoan
arrayexceptinsteadofaccessingitselementswithindex
numbers,youaccessthemwithindicesofanarbitrarytype.
<set>and<map>onlyallowonekeyofeachvalue,whereas
<multiset>and<multimap>allowmultipleidenticalkey
values
List
astandarddoublylinkedcontainer
supportsconstanttimeinsertionanddeletionofelementsatany
pointofthelist
Mostlistoperationareidenticaltothoseofavector
However,listdonotproviderandomaccesstoelements
Insert(),erase()runinconstanttimewhichmakeslists
Suitableforapplicationsthatperformmanyinsertionanddeletion
The use of containers
Theygiveuscontrolovercollectionsofobjects,
especiallydynamicobjects
Givesasimplemechanismforcreating,accessing
anddestroyingwithoutexplicitlyprogramming
algorithmstodotheseoperation
Container
Iteratormethodsallowusto
iteratethrowthecontainer addobject
findobject
removeobject
isempty
Requirements on elements in containers
Method Description Notes
Copy Copy Constructor creates a new Used every time you insert
Constructor element that is equalto safely be an element
destroyed without affecting
the old one
Heresanexampleusingthesetclasstemplate.
Thiscontainer,modelledafteratraditional
mathematicalset,doesnotacceptduplicate
values.
Thefollowingsetwascreatedtoworkwith
Int Set
#include<iostream> Intset.cpp
#include<iterator>
#include<set>
usingnamespacestd;
intmain(void)
{
set<int>intset;
for(inti=0;i<250;i++)
for(intj=0;j<24;j++)
intset.insert(j);
cout<<"SetSize"<<intset.size()<<endl;
cout<<"Contents"<<endl;
copy(intset.begin(),intset.end(),
ostream_iterator<int>(cout,","));
cout<<"\n";
}
Set
Theinsert()memberdoesallthework:
itattemptstoinsertanelementandignoresitifitsalreadythere.
Oftentheonlyactivitiesinvolvedinusingasetaresimplyinsertion
andtestingtoseewhetheritcontainsanelement.
Youcanalsoformaunion,anintersection,oradifferenceofsets
andtesttoseeifonesetisasubsetofanother.
Inthisexample,thevalues024areinsertedintotheset250
times,butonlythe25uniqueinstancesareaccepted.
The Copy Algorithm
Toprintoutthecontentsofthesetweuse,aspecial
algorithmcalledcopyInconjunctionwiththe
ostream_iterator
Weusethecopyalgorithmtoremovetheloopwecould
usetoaccesstheelementsoftheset.
andthebegin()andend()methodsofthesetto
gathertheextentsofthesettocopy.
iterator
vector<float>L;
for(vector<float>::iteratorp=L.begin();p<L.end();p++)
cout<<*p<<endl;
Different Iterators
Aniteratorisanabstractionforgenericity.
Itworkswithdifferenttypesofcontainerswithout
knowingtheunderlyingstructureofthose
containers.
Mostcontainerssupportiterators,soyoucansay
<ContainerType>::iterator
<ContainerType>::constiterator
toproducetheiteratortypesforacontainer.
Different Iterators
(*it).f();
or
it>f();
Shapes
shapes.cpp
A different way of Iterating
ShapeIterbegin=shapes.begin();
ShapeIterend=shapes.end();
shape2.cpp while(begin!=end)
{
(*begin)>draw();
++begin;
}
begin=shapes.begin();
end=shapes.end();
while(begin!=end)
{
delete(*begin);
++begin;
}
for_each
for_each allows us to call the same function
for each of the elements in the container
for_each(shapes.begin(),shapes.end(),mem_fun(&Shape::draw));
however we can only call for void methods (or
using more complex structures) for pointers to
containers or other unarray functions
Sorting
sorting.cpp
Reverse Iterators
the beginning").
erase(itorbegin,itorend) erase a
range of elements of the vector
insert(itorwhere,value)
Converting Between sequences
convert.cpp
The Singleton Pattern
Thesingletonpatterndefinesanobjectthatcanonly
existonce
Thisisdonebyimplementingthecodeinaparticular
waywiththeobjectknowingifithasbeencreated
Ifithasnotitwillcreateaninstanceofitself
Ifithasbeencreateditwillreturntheinstance.
Thispatternisagoodwayofstoringglobalstatedata
withinaprogram.
Global.h
#include<iostream>
classGlobal
{
private:
staticGlobal*m_pinstance;
intm_age;
inlineGlobal(){;}
inline~Global(){;}
inlineGlobal(constGlobal&_g){;}
public:
staticGlobal*Instance();
voidsetName(conststd::string&_name);
std::stringgetName();
voidsetAge(int_age);
intgetAge();
};
Global.cpp
Global*Global::m_pinstance=0;//initializepointer
Global*Global::Instance()
{
if(m_pinstance==0)//isitthefirstcall?
{
std::cout<<"newinstance\n";
m_pinstance=newGlobal;//createsoleinstance
}
std::cout<<"existingobject\n";
returnm_pinstance;//addressofsoleinstance
}
voidGlobal::setName(conststd::string&_name)
{
m_name=_name;
}
std::stringGlobal::getName(){returnm_name;}