0% found this document useful (0 votes)
55 views

STL Containers & Iterators

The document discusses the Standard Template Library (STL) containers, iterators, and algorithms. It explains that containers store and organize data in memory, iterators point to elements within containers and generalize pointers, and algorithms perform operations on container elements using iterators. It provides examples of common STL containers like vector, list, deque, set, and map, and how they organize elements sequentially or associatively. Iterators allow algorithms to iterate through container elements.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

STL Containers & Iterators

The document discusses the Standard Template Library (STL) containers, iterators, and algorithms. It explains that containers store and organize data in memory, iterators point to elements within containers and generalize pointers, and algorithms perform operations on container elements using iterators. It provides examples of common STL containers like vector, list, deque, set, and map, and how they organize elements sequentially or associatively. Iterators allow algorithms to iterate through container elements.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

STLContainers

&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

Assignment Replaces the content of an element Used every time to modify


operator with a copy of the source element an element

Destructor Cleans up an element Used every time you remove


an element.
Default Construct an element without any Required only for some
Constructor argument operations

operator == Compares two elements for Required only for some


equality operations

operator< Determines if one element is less Required only for some


than another operations
A simple Example

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

once we have the values to copy we need to copy it to


some place which in this case is the ostream_iterator
class template declared in the<iterator> header.

An ostream_iterator is an Output Iterator that performs


formatted output of objects of type T to a particular
ostream.

Output stream iterators overload their copy assignment


operators to write to their stream.

This particular instance of ostream_iterator is attached


to the output stream cout

It is possible to attach it to a file and get the results copied


to a file
iterator

Every copy assigns an integer from the set to cout


through this iterator, the iterator writes the integer to cout
and also automatically writes an instance of the separator
string found in its second argument, which in this case
contains a ,

It is just as easy to write to a le by providing an output le


stream, instead of cout
More Complex example: countw.cpp
usingnamespacestd;
voidCountUniqueWords(constchar*fileName)
{
ifstreamsource(fileName);
WriteaProgramtocountthenumberof
if(!source)
uniquewordsinatextfile
{cerr<<"erroropeningfile\n";
exit(EXIT_FAILURE);
}
stringword;
set<string>words;
while(source>>word)
words.insert(word);
cout<<"Numberofuniquewords:"<<words.size()<<endl;
copy(words.begin(),words.end(),ostream_iterator<string>(cout,"
}
intmain(intargc,char*argv[])
{
if(argc>1)CountUniqueWords(argv[1]);
else
cerr<<"Usage"<<argv[0]<<"filename"<<endl;
}
Iterators

Iteratorisagenerationofpointer

Itisanobjectbelongingtoaclasswiththeprefix*
definedonit

Sothat,ifpinaniteratoroveracontainer,*pis
anobjectinthecontainer.

Youcanthinkofiteratoraspointingtoacurrent
objectatanytime

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

Every container has a begin() member function that


produces an iterator indicating the beginning of the
elements in the container, and an end() member
function that produces an iterator which is the past-the-end
marker of the container.

If the container is const begin() and end() produce


const_iterators, which disallow changing the
elements pointed to (because the appropriate operators
are const).
Iterators II

All iterators can advance within their sequence (via


operator++) and allow == and != comparisons.

Thus, to move an iterator it forward without running it


off the end, you say something like:
while(it!=pastEnd)
{
//Dosomething
++it;
}

where pastEnd is the past-the-end marker produced by


the containers end() member function.
Iterators III

An iterator can be used to produce the container element


that it is currently selecting via the dereferencing operator
(operator*).

This can take two forms. If it is an iterator traversing a


container, and f() is a member function of the type of
objects held in the container, you can say either:

(*it).f();
or
it>f();
Shapes

The following example shows how we can use


the vector container and run-time
polymorphism to access different objects

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

the sort algorithm allows objects to be sorted.

sorting.cpp
Reverse Iterators

A container may also be reversible, which means that it can


produce iterators that move backward from the end, as well as
iterators that move forward from the beginning.

All standard containers support such bidirectional iteration.

A reversible container has the member functions:


rbegin( ) (to produce a reverse iterator selecting the end)
rend( ) (to produce a reverse iterator indicating "one past

the beginning").

If the container is const, rbegin( ) and rend( ) will produce


const_reverse_iterators.
#include<fstream> reverseit.cpp
#include<iostream>
#include<string> Example
#include<vector>
usingnamespacestd;
intmain(intargc,char**argv)
{
if(argc>1)
{
ifstreamin(argv[1]);
stringline;
vector<string>lines;
while(getline(in,line))
lines.push_back(line);
vector<string>::reverse_iteratorr=lines.rbegin();
vector<string>::reverse_iteratorend=lines.rend();
for(r;r!=end;r++)
cout<<*r<<endl;
}
}
Vectors

reserve() This method can be used to


reserve a predened amount of data space
for the vector

size() this reports how many elements in


the vector

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;}

You might also like