35
Streams and IO Streams and IO Streams are pipe like constructors Streams are pipe like constructors used for providing IO. used for providing IO. When a programmer needs to handle When a programmer needs to handle input from or output to external input from or output to external entities,then streams are used by entities,then streams are used by c++. c++. The stream is the central concept The stream is the central concept of the iostream classes of the iostream classes

Unit v

Embed Size (px)

Citation preview

Page 1: Unit v

Streams and IOStreams and IO

Streams are pipe like constructors used for Streams are pipe like constructors used for providing IOproviding IO

When a programmer needs to handle input When a programmer needs to handle input from or output to external entitiesthen from or output to external entitiesthen streams are used by c++streams are used by c++

The stream is the central concept of the The stream is the central concept of the iostream classesiostream classes

Output streamsOutput streams

An output stream object is a destination for bytes An output stream object is a destination for bytes The three most important output stream classare The three most important output stream classare

ostreamostream ofstreamofstream and ostrstream and ostrstreamThe The ostreamostream class through the derived class class through the derived class

basic_ostreambasic_ostream supports the predefined stream supports the predefined stream objectsobjectscoutcout standard output standard output

cerrcerr standard error with limited buffering standard error with limited buffering clogclog similar to similar to cerrcerr but with full buffering but with full buffering

Input streamsInput streams

An input stream object is a source of bytes The three An input stream object is a source of bytes The three most important input stream classes are most important input stream classes are istreamistream ifstreamifstream

and and istrstreamistrstreamThe istream class is best used for sequential text-mode The istream class is best used for sequential text-mode

input You can configure objects of class istream for input You can configure objects of class istream for buffered or unbuffered operation All functionality of the buffered or unbuffered operation All functionality of the

base classios is included in istream You will base classios is included in istream You will rarelconstruct objects from class istream Instead you will rarelconstruct objects from class istream Instead you will generally use the predefined generally use the predefined cincin object which is actually object which is actually

an object of class an object of class ostreamostream In some cases you can In some cases you can assign assign cincin to other stream objects after program startup to other stream objects after program startup

Formatting IOFormatting IO Formatting using Ios functionsFormatting using Ios functions

Width()-It specifies the width for displaythe output will take up the Width()-It specifies the width for displaythe output will take up the width specifiedused in alignng vertical column of numeric itemswidth specifiedused in alignng vertical column of numeric items

Precision()-It specifies the precision of the floating point Precision()-It specifies the precision of the floating point numberDefault precision is six digits after decimal pointnumberDefault precision is six digits after decimal point

Fill()-it specifies the character for filling up the unused prion of the Fill()-it specifies the character for filling up the unused prion of the fieldIt is usually usd with the width member functionfieldIt is usually usd with the width member function

Setf()-The function specifies the format flags that controls output Setf()-The function specifies the format flags that controls output display like left or right justificationpadding after sign display like left or right justificationpadding after sign symbolscientific notation displaydisplaying abse of the numbersymbolscientific notation displaydisplaying abse of the number

Unsetf()-This function provides undo operation for above mentioned Unsetf()-This function provides undo operation for above mentioned operations with setfoperations with setf

The prototype of the function isThe prototype of the function is

ltltold value of streamgtfunction old value of streamgtfunction nameltspecified new valuenameltspecified new valuegtgt

The functions set new value to the stream and The functions set new value to the stream and retutn valueThe width function sets new width to retutn valueThe width function sets new width to

the argument specified and returns old widthThe the argument specified and returns old widthThe precision function sets new precision and returns precision function sets new precision and returns

old precisionold precision

Member functions of Ios

IO manipulatorsIO manipulators

Manipulators are special functions for Manipulators are special functions for formattingformatting

The choice between manipulators and ios The choice between manipulators and ios functions to solve formatting problems functions to solve formatting problems

sometimes depends upon the usersometimes depends upon the userEquivalent manipulators for some of the io Equivalent manipulators for some of the io

functions arefunctions areSetw()setprecision()setfill()setiosflags()reseSetw()setprecision()setfill()setiosflags()rese

tiosflagstiosflags()()

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 2: Unit v

Output streamsOutput streams

An output stream object is a destination for bytes An output stream object is a destination for bytes The three most important output stream classare The three most important output stream classare

ostreamostream ofstreamofstream and ostrstream and ostrstreamThe The ostreamostream class through the derived class class through the derived class

basic_ostreambasic_ostream supports the predefined stream supports the predefined stream objectsobjectscoutcout standard output standard output

cerrcerr standard error with limited buffering standard error with limited buffering clogclog similar to similar to cerrcerr but with full buffering but with full buffering

Input streamsInput streams

An input stream object is a source of bytes The three An input stream object is a source of bytes The three most important input stream classes are most important input stream classes are istreamistream ifstreamifstream

and and istrstreamistrstreamThe istream class is best used for sequential text-mode The istream class is best used for sequential text-mode

input You can configure objects of class istream for input You can configure objects of class istream for buffered or unbuffered operation All functionality of the buffered or unbuffered operation All functionality of the

base classios is included in istream You will base classios is included in istream You will rarelconstruct objects from class istream Instead you will rarelconstruct objects from class istream Instead you will generally use the predefined generally use the predefined cincin object which is actually object which is actually

an object of class an object of class ostreamostream In some cases you can In some cases you can assign assign cincin to other stream objects after program startup to other stream objects after program startup

Formatting IOFormatting IO Formatting using Ios functionsFormatting using Ios functions

Width()-It specifies the width for displaythe output will take up the Width()-It specifies the width for displaythe output will take up the width specifiedused in alignng vertical column of numeric itemswidth specifiedused in alignng vertical column of numeric items

Precision()-It specifies the precision of the floating point Precision()-It specifies the precision of the floating point numberDefault precision is six digits after decimal pointnumberDefault precision is six digits after decimal point

Fill()-it specifies the character for filling up the unused prion of the Fill()-it specifies the character for filling up the unused prion of the fieldIt is usually usd with the width member functionfieldIt is usually usd with the width member function

Setf()-The function specifies the format flags that controls output Setf()-The function specifies the format flags that controls output display like left or right justificationpadding after sign display like left or right justificationpadding after sign symbolscientific notation displaydisplaying abse of the numbersymbolscientific notation displaydisplaying abse of the number

Unsetf()-This function provides undo operation for above mentioned Unsetf()-This function provides undo operation for above mentioned operations with setfoperations with setf

The prototype of the function isThe prototype of the function is

ltltold value of streamgtfunction old value of streamgtfunction nameltspecified new valuenameltspecified new valuegtgt

The functions set new value to the stream and The functions set new value to the stream and retutn valueThe width function sets new width to retutn valueThe width function sets new width to

the argument specified and returns old widthThe the argument specified and returns old widthThe precision function sets new precision and returns precision function sets new precision and returns

old precisionold precision

Member functions of Ios

IO manipulatorsIO manipulators

Manipulators are special functions for Manipulators are special functions for formattingformatting

The choice between manipulators and ios The choice between manipulators and ios functions to solve formatting problems functions to solve formatting problems

sometimes depends upon the usersometimes depends upon the userEquivalent manipulators for some of the io Equivalent manipulators for some of the io

functions arefunctions areSetw()setprecision()setfill()setiosflags()reseSetw()setprecision()setfill()setiosflags()rese

tiosflagstiosflags()()

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 3: Unit v

Input streamsInput streams

An input stream object is a source of bytes The three An input stream object is a source of bytes The three most important input stream classes are most important input stream classes are istreamistream ifstreamifstream

and and istrstreamistrstreamThe istream class is best used for sequential text-mode The istream class is best used for sequential text-mode

input You can configure objects of class istream for input You can configure objects of class istream for buffered or unbuffered operation All functionality of the buffered or unbuffered operation All functionality of the

base classios is included in istream You will base classios is included in istream You will rarelconstruct objects from class istream Instead you will rarelconstruct objects from class istream Instead you will generally use the predefined generally use the predefined cincin object which is actually object which is actually

an object of class an object of class ostreamostream In some cases you can In some cases you can assign assign cincin to other stream objects after program startup to other stream objects after program startup

Formatting IOFormatting IO Formatting using Ios functionsFormatting using Ios functions

Width()-It specifies the width for displaythe output will take up the Width()-It specifies the width for displaythe output will take up the width specifiedused in alignng vertical column of numeric itemswidth specifiedused in alignng vertical column of numeric items

Precision()-It specifies the precision of the floating point Precision()-It specifies the precision of the floating point numberDefault precision is six digits after decimal pointnumberDefault precision is six digits after decimal point

Fill()-it specifies the character for filling up the unused prion of the Fill()-it specifies the character for filling up the unused prion of the fieldIt is usually usd with the width member functionfieldIt is usually usd with the width member function

Setf()-The function specifies the format flags that controls output Setf()-The function specifies the format flags that controls output display like left or right justificationpadding after sign display like left or right justificationpadding after sign symbolscientific notation displaydisplaying abse of the numbersymbolscientific notation displaydisplaying abse of the number

Unsetf()-This function provides undo operation for above mentioned Unsetf()-This function provides undo operation for above mentioned operations with setfoperations with setf

The prototype of the function isThe prototype of the function is

ltltold value of streamgtfunction old value of streamgtfunction nameltspecified new valuenameltspecified new valuegtgt

The functions set new value to the stream and The functions set new value to the stream and retutn valueThe width function sets new width to retutn valueThe width function sets new width to

the argument specified and returns old widthThe the argument specified and returns old widthThe precision function sets new precision and returns precision function sets new precision and returns

old precisionold precision

Member functions of Ios

IO manipulatorsIO manipulators

Manipulators are special functions for Manipulators are special functions for formattingformatting

The choice between manipulators and ios The choice between manipulators and ios functions to solve formatting problems functions to solve formatting problems

sometimes depends upon the usersometimes depends upon the userEquivalent manipulators for some of the io Equivalent manipulators for some of the io

functions arefunctions areSetw()setprecision()setfill()setiosflags()reseSetw()setprecision()setfill()setiosflags()rese

tiosflagstiosflags()()

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 4: Unit v

Formatting IOFormatting IO Formatting using Ios functionsFormatting using Ios functions

Width()-It specifies the width for displaythe output will take up the Width()-It specifies the width for displaythe output will take up the width specifiedused in alignng vertical column of numeric itemswidth specifiedused in alignng vertical column of numeric items

Precision()-It specifies the precision of the floating point Precision()-It specifies the precision of the floating point numberDefault precision is six digits after decimal pointnumberDefault precision is six digits after decimal point

Fill()-it specifies the character for filling up the unused prion of the Fill()-it specifies the character for filling up the unused prion of the fieldIt is usually usd with the width member functionfieldIt is usually usd with the width member function

Setf()-The function specifies the format flags that controls output Setf()-The function specifies the format flags that controls output display like left or right justificationpadding after sign display like left or right justificationpadding after sign symbolscientific notation displaydisplaying abse of the numbersymbolscientific notation displaydisplaying abse of the number

Unsetf()-This function provides undo operation for above mentioned Unsetf()-This function provides undo operation for above mentioned operations with setfoperations with setf

The prototype of the function isThe prototype of the function is

ltltold value of streamgtfunction old value of streamgtfunction nameltspecified new valuenameltspecified new valuegtgt

The functions set new value to the stream and The functions set new value to the stream and retutn valueThe width function sets new width to retutn valueThe width function sets new width to

the argument specified and returns old widthThe the argument specified and returns old widthThe precision function sets new precision and returns precision function sets new precision and returns

old precisionold precision

Member functions of Ios

IO manipulatorsIO manipulators

Manipulators are special functions for Manipulators are special functions for formattingformatting

The choice between manipulators and ios The choice between manipulators and ios functions to solve formatting problems functions to solve formatting problems

sometimes depends upon the usersometimes depends upon the userEquivalent manipulators for some of the io Equivalent manipulators for some of the io

functions arefunctions areSetw()setprecision()setfill()setiosflags()reseSetw()setprecision()setfill()setiosflags()rese

tiosflagstiosflags()()

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 5: Unit v

The prototype of the function isThe prototype of the function is

ltltold value of streamgtfunction old value of streamgtfunction nameltspecified new valuenameltspecified new valuegtgt

The functions set new value to the stream and The functions set new value to the stream and retutn valueThe width function sets new width to retutn valueThe width function sets new width to

the argument specified and returns old widthThe the argument specified and returns old widthThe precision function sets new precision and returns precision function sets new precision and returns

old precisionold precision

Member functions of Ios

IO manipulatorsIO manipulators

Manipulators are special functions for Manipulators are special functions for formattingformatting

The choice between manipulators and ios The choice between manipulators and ios functions to solve formatting problems functions to solve formatting problems

sometimes depends upon the usersometimes depends upon the userEquivalent manipulators for some of the io Equivalent manipulators for some of the io

functions arefunctions areSetw()setprecision()setfill()setiosflags()reseSetw()setprecision()setfill()setiosflags()rese

tiosflagstiosflags()()

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 6: Unit v

IO manipulatorsIO manipulators

Manipulators are special functions for Manipulators are special functions for formattingformatting

The choice between manipulators and ios The choice between manipulators and ios functions to solve formatting problems functions to solve formatting problems

sometimes depends upon the usersometimes depends upon the userEquivalent manipulators for some of the io Equivalent manipulators for some of the io

functions arefunctions areSetw()setprecision()setfill()setiosflags()reseSetw()setprecision()setfill()setiosflags()rese

tiosflagstiosflags()()

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 7: Unit v

Unlike Iosmanipulators do not return the Unlike Iosmanipulators do not return the previous statusprevious status

Manipulators can write our own manipulator Manipulators can write our own manipulator and use it in the programmarksheet printing and use it in the programmarksheet printing

program can use it for printingprogram can use it for printingIos functions are singleThey cannot be Ios functions are singleThey cannot be

combined to have multiple effects combined to have multiple effects togetherWhen a large set of formatting togetherWhen a large set of formatting

options are usedmanipulators are used to options are usedmanipulators are used to write and produce more readable codewrite and produce more readable code

Ios functions need ltiotsreamgtwhereas Ios functions need ltiotsreamgtwhereas manipulators need ltiomanipmanipulators need ltiomanipltlt

Difference between ios and manipulators

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 8: Unit v

include ltiostreamhgtinclude ltiostreamhgtinclude ltfstreamhgtinclude ltfstreamhgt

Input using cin Input using cin

int main () int main () char myline[256] char myline[256]

int lc = 0 int lc = 0

ofstream outfile(demotxtiosapp) ofstream outfile(demotxtiosapp)

ifstream infile(stdcodesxyz) ifstream infile(stdcodesxyz) if ( infile) if ( infile)

cerr ltlt Failed to open input filen cerr ltlt Failed to open input filen exit(1) exit(1)

while (1) while (1) infilegetline(myline256) infilegetline(myline256)

if (infileeof()) break if (infileeof()) break lc++ lc++

outfile ltlt lc ltlt ltlt myline ltlt n outfile ltlt lc ltlt ltlt myline ltlt n

infileclose() infileclose() outfileclose() outfileclose()

cout ltlt Output ltlt lc ltlt records ltlt endl cout ltlt Output ltlt lc ltlt records ltlt endl

Example program

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 9: Unit v

Object SerializationObject Serialization

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 10: Unit v

Object SerializationObject Serialization

Simple persistence method which provides a Simple persistence method which provides a program the ability to read or write a whole object program the ability to read or write a whole object

to and from a stream of bytesto and from a stream of bytesAllows Java objects to be encoded into a byte Allows Java objects to be encoded into a byte

stream suitable for streaming to a file on disk or stream suitable for streaming to a file on disk or over a networkover a network

The class must implement the The class must implement the SerializableSerializable interface (interface (javaioSerializablejavaioSerializable) which does not ) which does not

declare any methods and have accessors and declare any methods and have accessors and mutators for its attributesmutators for its attributes

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 11: Unit v

Object Serialization example pgmObject Serialization example pgm

create output streamcreate output stream

File file = new File file = new File(teams_serializeser)File(teams_serializeser)

String fullPath = filegetAbsolutePathString fullPath = filegetAbsolutePath()()

fos = new FileOutputStream(fullPath)fos = new FileOutputStream(fullPath)

open output stream and store team t1open output stream and store team t1

out = new ObjectOutputStream(fos)out = new ObjectOutputStream(fos)

outwriteObject(t1)outwriteObject(t1)

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 12: Unit v

Object persistenceObject persistence

One of the most critical tasks that applications One of the most critical tasks that applications have to perform is to save and restore datahave to perform is to save and restore data

PersistencePersistence is the storage of data from working is the storage of data from working memory so that it can be restored when the memory so that it can be restored when the

application is run againapplication is run againIn object-oriented systems there are several In object-oriented systems there are several

ways in which objects can be made persistentways in which objects can be made persistentThe choice of persistence method is an The choice of persistence method is an

important part of the design of an applicationimportant part of the design of an application

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 13: Unit v

C++ NamespacesC++ Namespaces

A mechanism for logically grouping A mechanism for logically grouping declarations and definitions into a common declarations and definitions into a common

declarative regiondeclarative region

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 14: Unit v

C++ NamespacesC++ Namespaces

The contents of the namespace can be The contents of the namespace can be accessed by code inside or outside the accessed by code inside or outside the

namespacenamespacendashUse the scope resolution operator to access Use the scope resolution operator to access

elements from outside the namespaceelements from outside the namespacendashAlternatively the Alternatively the usingusing declaration allows the declaration allows the

names of the elements to be used directlynames of the elements to be used directly

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 15: Unit v

C++ NamespacesC++ Namespaces

Creating a namespaceCreating a namespacenamespace smallNamespacenamespace smallNamespace

intint count = 0 count = 0 voidvoid abc abc()()

end smallNamespaceend smallNamespace

Using a namespaceUsing a namespaceusingusing namespacenamespace smallNamespace smallNamespace

count +=1count +=1abcabc () ()

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 16: Unit v

STD NamespacesSTD Namespaces

Items declared in the C++ Standard Library Items declared in the C++ Standard Library are declared in the are declared in the std std namespacenamespace

C++ C++ includeinclude files for several functions are in files for several functions are in the the std std namespacenamespace

ndashTo include input and output functions from the To include input and output functions from the C++ library writeC++ library write include ltiostreaminclude ltiostreamltlt

usingusing namespacenamespace std std

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 17: Unit v

Ansi string objectsAnsi string objects

The ANSI string class implements a first-class character string data type that avoids

many problemsassociated with simple character arrays

(C-style strings) You can define a string object very

simply as shown in the following example

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 18: Unit v

Ansi string class syntax pgmAnsi string class syntax pgm

include ltstringltusing namespace stdstring first_name = Bjarnestring last_namelast_name = Stroustrupstring names = first_name + + last_namecout ltlt names ltlt endlnames = last_name + + first + first_namecout ltlt names ltlt endl

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 19: Unit v

Ansi string class member functionsAnsi string class member functions

Member functionsThe string class defines many member functions A few of the basic

ones are described belowA string object may defined without an initializing value in which case

its initialvalue is an empty string (zero length no characters)string str1A string object may also be initialized with1048698 a string expressionstring str2 = str1string str3 = str1 + str2string str4 (str2) Alternate form1048698 a character string literalstring str4 = Hello there

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 20: Unit v

Standard Template LibraryStandard Template LibraryThe standard template library (STL) containsThe standard template library (STL) contains

ndashContainersContainersndashAlgorithmsAlgorithmsndashIteratorsIterators

A A containercontainer is a way that stored data is organized in is a way that stored data is organized in memory for example an array of elementsmemory for example an array of elements

AlgorithmsAlgorithms in the STL are procedures that are applied to in the STL are procedures that are applied to containers to process their data for example search for containers to process their data for example search for

an element in an array or sort an arrayan element in an array or sort an arrayIteratorsIterators are a generalization of the concept of pointers are a generalization of the concept of pointers

they point to elements in a container for example you they point to elements in a container for example you can increment an iterator to point to the next element in can increment an iterator to point to the next element in

an arrayan array

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 21: Unit v

Containers Iterators AlgorithmsContainers Iterators Algorithms

Container

AlgorithmIterator

Container

Iterator

Algorithm

Objects

Iterator

Iterator

Algorithm

Algorithms use iterators to interact with objectsstored in containers

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 22: Unit v

ContainersContainers

A container is a way to store data either built-in dataA container is a way to store data either built-in data types like int and float or class objectstypes like int and float or class objectsThe STL provides several basic kinds of containersThe STL provides several basic kinds of containers

ndashgtgtvectorgt one-dimensional arrayvectorgt one-dimensional arrayndashgtgtlistgt double linked listlistgt double linked listndashgtgtdequegt double-ended queuedequegt double-ended queuendashgtgtqueuegt queuequeuegt queuendashgtgtstackgt stackstackgt stackndashgtgtsetgt setsetgt setndashgtgtmapgt associative arraymapgt associative array

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 23: Unit v

Sequence ContainersSequence ContainersA sequence container stores a set of elements inA sequence container stores a set of elements in

sequence in other words each element (exceptsequence in other words each element (except for the first and last one) is preceded by onefor the first and last one) is preceded by one specific element and followed by another ltvectorspecific element and followed by another ltvectorltlt

gt gt listgt and ltdequegt are sequential containerslistgt and ltdequegt are sequential containersIn an ordinary C++ array the size is fixed and canIn an ordinary C++ array the size is fixed and can

not change during run-time it is also tedious tonot change during run-time it is also tedious to insert or delete elements Advantage quick insert or delete elements Advantage quick

randomrandom accessaccess gtgtvectorgt is an expandable array that can shrink orvectorgt is an expandable array that can shrink or

grow in size but still has the disadvantage ofgrow in size but still has the disadvantage of inserting or deleting elements in the middleinserting or deleting elements in the middle

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 24: Unit v

Sequence ContainersSequence Containers

gtgtlistgt is a double linked list (each element haslistgt is a double linked list (each element has points to its successor and predecessor) it ispoints to its successor and predecessor) it is quick to insert or delete elements but has slowquick to insert or delete elements but has slow random accessrandom accessgtgtdequegt is a double-ended queue that means onedequegt is a double-ended queue that means one

can insert and delete elements from both ends itcan insert and delete elements from both ends it is a kind of combination between a stack (last inis a kind of combination between a stack (last in first out) and a queue (first in first out) and constitutes first out) and a queue (first in first out) and constitutes

a compromise between a ltvectorgt anda compromise between a ltvectorgt and a ltlista ltlistltlt

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 25: Unit v

Associative ContainersAssociative Containers

An associative container is non-sequential but An associative container is non-sequential but usesuses

a a keykey to access elements The keys typically to access elements The keys typically a number or a string are used by the a number or a string are used by the

container to arrange the stored elements in a container to arrange the stored elements in a specific orderspecific order

for example in a dictionary the entries are for example in a dictionary the entries are orderedordered

alphabeticallyalphabetically

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 26: Unit v

Associative ContainersAssociative ContainersA ltsetgt stores a number of items which contain keysA ltsetgt stores a number of items which contain keys

The keys are the attributes used to order the itemsThe keys are the attributes used to order the items

for example a set might store objects of the classfor example a set might store objects of the class

Person which are ordered alphabetically using their namePerson which are ordered alphabetically using their nameA ltmapgt stores pairs of objects a key object andA ltmapgt stores pairs of objects a key object and

an associated value object A ltmapgt is somehowan associated value object A ltmapgt is somehow

similar to an array except instead of accessing itssimilar to an array except instead of accessing its

elements with index numbers you access them withelements with index numbers you access them with

indices of an arbitrary typeindices of an arbitrary typegtgtsetgt and ltmapgt only allow one key of each valuesetgt and ltmapgt only allow one key of each value

whereas ltmultisetgt and ltmultimapgt allow multiplewhereas ltmultisetgt and ltmultimapgt allow multiple

identical key valuesidentical key values

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 27: Unit v

vectorltintgt

array_

IteratorsIteratorsIterators are pointer-like entities that are Iterators are pointer-like entities that are

used toused to

access individual elements in a containeraccess individual elements in a containerOften they are used to move sequentially Often they are used to move sequentially

from element to element a process called from element to element a process called iteratingiterating through a container through a container

17

4

23

12

size_ 4

vectorltintgtiterator

The iterator corresponding tothe class vectorltintgt is ofthe type vectorltintgtiterator

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 28: Unit v

IteratorsIteratorsOne can have multiple iterators pointing to One can have multiple iterators pointing to

different or identical elements in the different or identical elements in the containercontainervectorltintgt v

array_ 17

4

23

12

size_ 4i3

i1

i2

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 29: Unit v

IteratorsIteratorsinclude ltvectoinclude ltvectorrltlt

include ltiostreaminclude ltiostreamltlt

int arr[] = 12 3 17 8 standard C arrayint arr[] = 12 3 17 8 standard C array

vectorltintgt v(arr arr+4) initialize vector with C arrayvectorltintgt v(arr arr+4) initialize vector with C array

for (vectorltintgtiterator i=vbegin() i=vend() i++)for (vectorltintgtiterator i=vbegin() i=vend() i++)

initialize i with pointer to first element of vinitialize i with pointer to first element of v

i++ increment iterator move iterator to next elementi++ increment iterator move iterator to next element

cout ltlt i ltlt rdquo rdquo de-referencing iterator returns thecout ltlt i ltlt rdquo rdquo de-referencing iterator returns the

value of the element the iterator points atvalue of the element the iterator points at

cout ltlt endlcout ltlt endl

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 30: Unit v

File handling in CFile handling in C++++

Introduction to File HandlingIntroduction to File HandlingndashData entered once required later againData entered once required later againndashSame Data to be used by othersSame Data to be used by othersndashData required again by the same programData required again by the same program

Files and StreamsFiles and Streams

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 31: Unit v

IO StreamsIO Streams

StreamDescription

cinStandard input stream

coutStandard output stream

cerrStandard error stream

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 32: Unit v

ofstreamofstream

Output file stream ClassOutput file stream Classopen() is a member function of the class ofstreamopen() is a member function of the class ofstreamInherited functions of ofstream class from the class Inherited functions of ofstream class from the class

ostream areostream arendashputput()()ndashwritewrite()()ndashseekpseekp()()ndashtellptellp()()

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 33: Unit v

fstreamfstream

It supports files for simultaneous input and outputIt supports files for simultaneous input and outputfstream is derived fromfstream is derived from

ndashifstreamifstreamndashofstreamofstreamndashiostreamiostream

They are parent classes and fstream is the child classThey are parent classes and fstream is the child classMember functions of the class fstreamMember functions of the class fstream

ndashopenopenndashcloseclosendashclose allclose allndashseekgseekgndashseekpseekpndashtellgtellgndashtellptellp

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 34: Unit v

This program creates a file called ldquomessagedatThis program creates a file called ldquomessagedatrdquordquoinclude ltfstreamhgt include ltfstreamhgt Required for file IORequired for file IO

int mainint main()()

ofstream myfile (ldquomessagedatrdquo)ofstream myfile (ldquomessagedatrdquo)If (myfile)If (myfile)

check if the file is opened or notcheck if the file is opened or not

coutltltn Cannot open this filecoutltltn Cannot open this filereturn 1return 1

myfile ltltldquoWhen an apple fell Newton was disturbed nmyfile ltltldquoWhen an apple fell Newton was disturbed nrdquordquo

myfile ltltldquobut when he found that all apples fell nmyfile ltltldquobut when he found that all apples fell nrdquordquomyfile ltltldquomyfile ltltldquoit was gravitation that attracts them downit was gravitation that attracts them downnnrdquordquo

myfile ltltldquomyfile ltltldquohe was satisfied he was satisfied nnrdquordquomyfileclose()myfileclose()close the fileclose the file

return 1return 1

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++
Page 35: Unit v

Function in CFunction in C++++

Function PrototypeFunction PrototypeFunction CallFunction CallFunction DefinitionFunction Definition

  • Streams and IO
  • Output streams
  • Input streams
  • Formatting IO
  • Slide 5
  • IO manipulators
  • Slide 7
  • Slide 8
  • Object Serialization
  • Slide 10
  • Object Serialization example pgm
  • Object persistence
  • C++ Namespaces
  • Slide 14
  • Slide 15
  • STD Namespaces
  • Ansi string objects
  • Ansi string class syntax pgm
  • Ansi string class member functions
  • Standard Template Library
  • Containers Iterators Algorithms
  • Containers
  • Sequence Containers
  • Slide 24
  • Associative Containers
  • Slide 26
  • Iterators
  • Slide 28
  • Slide 29
  • File handling in C++
  • IO Streams
  • ofstream
  • fstream
  • Slide 34
  • Function in C++