Вы находитесь на странице: 1из 172

1: /I This PIOQram asks the user for information aIxltt 2: /I class Ilisto!y. ana then. '4Iites'tIii$«liectlGl~ 3: # indude<fstJeam.

h) 4:

5: class history

6: (

7: protected: 8: thar name[30]; 9: char ~[30]; 10: int age;

11: publk: void)

12:-·void getData( .

1,.· f . . ,', dn» name;

" 'Enter name, , ....

4' cout« " 011»..".., . 1, ~.t « "Enter age, '.", Cin» degree; 15: ,~ < "Enterdegee. ,

16:"cout< ,

17; }

18: }; 19:

20' main( r~ate a historY

' II",· forhistOlY

21: { person; /lGet~

22: histo~ getOata( ); ' ..

23: perso '. ~zed(pe<S(tlJ)'

24: ~,~

~ vmre!<:h>f "l&JJ!f'

. 26: outfi!e.

27:}

\

\.

-, \'-\/

e

.. !

CHAPTER 11 CLASS TEMPLATES

11.1. Create a Generic Function 10

11.2. Search an Array Using a Generic Function 14

11.3. A Simple Class Template 16

11.4. Default Values for Parameters

of a Specific Type 17

11.5. Using a Linked-list Template 19

11.6. Partial Template Specialization 27

CHAPTER 12

STANDARD C++ LIBRARY

Cornple-':·4 e

~~_.~~_ ..... "..,_:.-""":,,,,,, I h)"'hi,;.,ciit'i .. · ... 1W·;t1·t·~ j .. .,.......~~.~..l.: .• ~~~."' .......... ;./

..... ~ .. -, ~ ....

29

12.2. The string Member Functions 12.3. Formatted Output

12.4. Output Member Functions 12.5. Input Member Functions

37 39 48 50

CHAPTER 13

FILE I/O STREAMS

13.1. The fstream Class

13.2. Appending to an Output File 13.3. Avoiding to Open an Existing File 13.4. The ofstream( ) Function

13.5. Reading Strings from a File

13.6. Reading until End-of-File

58 59 60 61 63 64

t Co~ple

~.r'_, ,,'t '. ,..:. tis' , ... :? '~.-.....-':tIJoN""._ :j~'a'·¥(",J."~·~.IC~_, ..

13.7. The seekg( ) Member Function 13.8. The tellg( ) Member Function

13.9. Read and Write a Stream File 13.10. Opening and Closing a Stream File 13.11. Objects I/O

CHAPTER 14 SEQUENCES

14.1. The vector Class Template 14.2. Sorting a Vector of Integers 14.3. The deque Class Template 14.4. The list Class Template

14.5. The stack Container Adaptor

65 66 67 69 70

75 85 87 94 102

14.6. The queue Container Adaptor 104

14.7. The priority_queue Container Adaptor 106

CHAPTER 15

ASSOCIATIVE CONTAINERS

15.1. The set Class Template 108
15.2. The multiset Class Template 116
15.3. The map Class Template 124
15.4. The multimap Class Template 133
15.5. User-Defined Predicates 141 CHAPTER 16

GENERIC ALGORITHMS

16.1. Using the adjacent_find() Function
16.2. Using the count( ) Function
16.3. Using the for _each( ) Function
16.4. Using the fill( ) Function
16.5. Using the random_shuffle( ) Function
16.6. Using the partition( ) Function
16.7. Using the rotate( ) Function
16.8. Using the sort( ) Function 144 146 147 149 150 152 154 156

16.9. Using the partial_sort( ) Function 158

16.10. Using the merge( ) Function 160

16.11. Using the accumulate( ) Function 164

16.12. Using the inner_product( ) Function 165

16.13. Using the partial_sum( ) Function 167

16.14. Using the adjacent_difference( ) Function 168

template ~OY)~ generic function G(J)d3 create C\)bQ88<J:::D:~lm container

L L 0 L L "I L l:j D

c '1' '1r;::c ref ti 0 'c 0 d to' 0, CrJ'!. • ~ 0 C

(J)0~01011 G'tf9 genenc unc Ion d:[>OY)O)GE>jJ::r.Y.)C\)1I :DwC\( a a ~l:i~d:[>o;?(OO)tj: 8<J~:tjl~9.G8<J")C

'f ct" C r;:: C '1 C " f cti COt C coo 0 C "I

G~CO'):O? un Ion (J)0~tf001(J)WII genenc un Ion (J)0~or execu e or0~wd:[>~~9c comp, er

o)G'i'::D9Gof.,a} data type o?G§:~JoS~: 8<J~:§l~:'f-'0111 ~2fJ())') generic function Go;?o)G'i' ~. ~8<JGC\)n05 overload C\)b::D'):m::DG::r.Y.)G01 I ~(J')a5:D:C\)'):1I generic function (J)S~d3 create

L "'- L 0 0 0 L IL L L

~M template ~a} keyword d2ro~G9.:9.01~oSll (J)S'i'~:8<J"):§9 template ~OY) generic function

C?-t; ::r.Y.)C\)bQ~oS~O'Y.)~G<.OT~m framework (J)S~c8Gr,"'Q8 ~g):01:D:1I program (J)S~c0:8<J(J)05

.. L -1 L L lj 0 L LO Lj..,.l -L J lL L L 0

8ch C C C C "I' cr;::c '1' tit c, • • 0 '1

:rh~ C\(09.~U? G'dC\(00y)0'i'Go;?o) cornp: er 9_.0'Y.)0'i'tf0':(-l01011 emp a e (J)0~9_.y00) G'dyC\(0111

template return type {

<class x»

function name (parameter list)

/ / body of function

}

Class Templates

00.0

Create a Generic Function

I I Listing 11.1: Creating a generic function #include <iostream>

template <class x>

void swap (X& a, X& b) {

X temp = a; a = b;

b = temp;

}

int main() {

int i1= 100, i2= 500;

float f1= 25.55, f2= 75.84;

cout « "\n\tBEFORE SWAP:"

« "\n\t\tFirst integer number = ,. « i1 < < "\n\t\tSecond integer number = ,. < < i2

< < "\n\t\tFirst float number = n < < f1

« "\n\t\tSecond float number ="« f2 «endl;

swap (il, i2); swap(f1, f2);

II swapping integers I I swapping floats

cout « "\n\tAFTER SWAP:"

« "\n\t\tFirst integer number = ,. « i1 « "\n\t\tSecond integer number = ,. « i2 « "\n\t\tFirst float number = ,. « f1

« "\n\t\tSecond float number ="« f2 «endl;

return 0;

}

Class Templates

00

Exl101.cpp 62 GC\?C\Y)§~~oS~q8 x IJY) data type fJ4C{5c-h qeneric function (),)G~ fJ4~:§lo? placeholder 01" ~~'J~~62 function body cD~c\)~: fJ4~:§l~q010')oS" program 62 run o?fJ4Q19q8 compiler (),)G~ actual data type O')Sy62 placeholder G~Ef>~ fJ4ID'J:CD~Go:~olo" class ~O')'J()') keyword 01" Exl101.cpp program IJY) variable (2) yq.O')~~:GC{5 G~Ef>~8:G~8:

" " f cti COt C r;:c '1 C -, C C C C • ~ -,

GO:O;> genenc un Ion O')Q)yO[> crea e C\(OGO:~t:100IO')())" program q.C\(0~~:C\(0(J)~1JY) fJ4~:ijlO;>

variable fJ4Ji[:fJ4ID'J:GO')GoT ~~~O')~Sol8J:" ~ program d5 run c3c-h~oS;;S6:l8 U (00. 0) ~ ~CD'J:O)

iJ 0 J IL C IL L L L -1 L J lj 0

Create a Generic Function 'Larger'

/ / Listing 11.2: Creating a generic function 'Larger' #include <iostream>

template <class X>

Class Templates

X Larger (X a,X b) {

return a > b ? a : b;

}

int main() {

cout «"\n\tLarger integer number = "« Larger(12,345)

« "\n\tLarger float number = "« Larger(12.34, 456.78)

« "\n\tLarger character = "« Larger('W','V')

« endl;

return 0;

}

Exll02.cpp program d5 run c{?xf)ldoSdSQt {] (00. J) !d')r:CXY):ci)~~t: r:tQ!d')oll1

L L L "I L J l:j 0 L LJ -lJ

CIIQuincy99

Defining More than One Generic Data Type

. f t' edt ty C 0 C 013<. • r: ceo 00 edt ty

011 genenc unc Ion O')ID?,? a a pe O')IDIdJl:com«t1: ~~:t1l~cO')Q)a::car,~9c a a pe

G0;5O? comma Q[§: GE>fco~9t9010')oSll y (00. ?) ,?GUlT§CXY):o} Exll03.cpp program 0)')~9t generic data type (2) JJl:O?~~:§l[§: create or0CXY):o} function O')S?olol1

Class Templates

/ / Li sti ng 11 .3: Defi ni ng m ore than one generi c data type

#i ncl ude <i ostream >

tem pi ate «I ass Xl ,(I ass X2>

void myTemp(Xl a, X2 b) {

(out «"\n\ta ="« a

«''\n\tb ="« b « endl « endl;

int maine ) {

myTemp (1 O,"COMPLETE C++"); myTemp (0.123456, 56789);

return 0;

1111

l

IiiiIQuincy 99

Class Templates

::xl ~03.c:pp program ~ GC\>(\)')§~qt myTemp( ) function !:rPCfJd) instance GCfJd? o:l r;.rieJ C"? generate oroa?!:rP~l'f' placeholder type (2) y§Sa} Xl ~ X2 a?G'l'Ef>'f' (int, char) ~ (double, int) data type GCfJ~ !:rP1D'J:o?:!:rP~:§l~:olcS~bloSll 81~qt generic function GCfJOY.l overloaded function Goog, d)tmblG~~:(\),):1I d)tGQY)d)toloooS , 81GobloSbloool~:1I ~')~lcSc\)

o T· IL T IL 0 0 IL IL L:1 LO

~GQY) function GoodS overload (\)oa)!:rP~lO)1Qt function ooS~~lt:~~ body cOb)') blooa)!:rP(\)oGoodS

L· 0 L L 0 iJ -L L t.I -p j IL 0 L 0 L

ceo co') C ') C • f t· . . t· 0 , C 0 co,)

(\)OGd)')C~C:(\)QOloo()')1I 8IGObl()') generic unc Ion OJIGQY) 0000 ac Ion GOOOJO (\)O~C:(\)Qb)')OIlI

L L LO -L a iJ a L IL 0 L L L LO -LJ

Search an Array Using a Generic Function

II Listing 11.4: Searching an array for an object #include <iostream>

#include <cstring>

template <class X>

void find(X obj, X *list, int size) {

for (int i=O; i<size; i++) if (list[i] == obj) {

cout « "\n\t" « obj « " is PRESENT.\n"; return;

}

cout « "\n\t" « obj « " is ABSENT.\n";

}

int main() {

int

a[ ] = {10,14,18,25,56};

Class Templates

char *c = "This is a test";

double d[] = {1.1,5.5,10.6,25.9};

find(14,a,5);

find('b',c,(int) strlen( c));

find(0.5,d,4);

return 0;

}

~~GroSo?, Exll04.cpp program o?GC\lC\Y.)6~(,)uSa?9.t generic function find( ) rom parameter list '{J argument (3) ~l:O? pass 0(8cY,9.G8d'Jt0(8QY)wloouSll 2°(,)') find(14,a,5) cY,

o cr~ c r;;: c []' I t (5) , 14 0 ,. '1 C c '1 0 c 0 c ~

G9.:0(m~c:8d'J:[j9 array a rom e emen yro'{J ~O?<j>OIOOOOlDyOIc\y'):~ IDIDG;:n:yC:tj:

ul~9.t find( ) mG<j> 14 is PRESENT. a?o? message o? prompt 0(8§'{Joll1 (')G06.~:a?9.t 14 is ABSENT. a3 display m8~ula3~(,)uSll ~£~:G<ld5t: G£'x-f)ro8 find( ) function GooG<lm8m8::D'):o

LO L L:::f. TC L T 0 L L 0 L

o r,::;:::: c .n GOO ceo c • ( ) ~ 'oc ~c r;;:c '1 c

O(GC\lC\Y.)e1~O"1 :3 program 0( run 0(m(,)O)~9.c <2 00. J '{JtjQY):O?G<lO(c: t:JCE>'['{J[jIDOIOOO)II

Class Templates

oo.~ A Simple Class Template

" f ct" 0 d fi C[9 • §. 0 C [9 0 C "I 0

generrc un Ion eeoc» e me (\)0 : Gd::D: [om s':n(\):J.)OYJ: a:)QC generrc c ass cox»

o l l l l l Teo l "I 0 l

C r;:;::::c C "I c" If 0")

a:)mGCVC\)')~2;;9G8d')CII generrc c ass cn0YE>!. genera arm m GdyC\(OIIi

template <class dtype> class className

{

I I ..... public:

II .....

};

I I Listing 11.5: Creating a class template #include <iostream>

template <class Ll, class l2> class Area

{

Ll length;

l2 width;

public:

Area (ll I, l2 w)

{ length = I; width = w; }

float display() {

cout «"\n\tlength ="« length « " inches"; cout «"\n\tWidth ="« width «" feet"; return length*width/12;

}

};

Class Templates

int main() {

float float

a = 12345; b = 67.89;

II inches II feet

Area <float, float> mt( a, b);

cout «"\n\n\tArea ="« mt.display( ) « " sq ft\n";

return 0;

}

Ex1105.cpp program d3 run cSd)~oS~Q8 0 (00. (5) g:)~(X)'):cD8'dd38: ~8Qg:)oll1

L L L -L L J lj • L l::J "I J

DlQuincy 99

y (00. (5)

Default Values for Parameters of a Specific Type

~t~a:f.>o?, class template O')S~o? create C\(8a?8'd~1'P template parameter list rom default argument O')S~d3 O')~a:::Dd)~d)Go:(X)')~cSQolO')oSlI ClOg:) Exll06.cpp program (J)')~Q8

L. L T L J 1.O -L C L -L

Class Templates

Exll05.cpp program d2 §l§too'):O)')oll1 template parameter list,,? oo03OJG§:>a5 argument d5 integer c8 type ~oS",oS~: value d5 10 c8~oS",oSGo:(D'):oloooSll

L La Jt1 L La J

I I Listing 11.6: Default values for parameters of a specific type #include <iostream>

template <class Ll, class L2, int add = 10>

class Area

{

Ll length;

L2 width;

public:

Area (Ll I, L2 w)

{ length = I + add; width = w + add; }

float display() {

cout «"\n\tLength ="« length « " inches"; cout «"\n\tWidth ="« width «" feet"; return (length*width/12);

}
};
int maine )
{
float a = 12345; I I inches
float b = 67.89; II feet Area <float, float> mt1(a, b);

cout «"\n\tArea ="« mt1.display( ) « " sq ft\n";

Area <float, float,100> mt2(a, b);

cout «"\n\tArea ="« mt2.display( ) « " sq ft\n";

return 0;

}

Class Templates

Exll06.cpp program d? GC\>C\)')§~98 maine ) function cD'{> a = 12345 t b = 67.89 d3 initialize ro6Go:CO'):~: mt1(a, b) ~m template function d3 call GQTo1moSil G1~Q8

L L t1 L 0 L L-l

class Area cDo8C\)')~: length = I + add<default> = 12345 + 10 = 12355 t width = w +

add <default> = 67.89 + 10 = 77.89 c8 assign ro6Go:ooo111 default value d3 G';l~:bl~lQ,8:D:~Q8

LD L J L L lj 1..1 It. L-l

mt2(a, b) d? call GQT901bloSil G1~98 length = I + add = 12345 + 100 = 12445 t width = w

+ add = 67.89 + 100 = 167.89 ~G~i')05mS~l: assign 0(6Go:'{>o1ol1 template definition co default value 10 d3G';l~:bl~lGO)')o1:D:1I Exll06.cpp program d3 run c805bloS~Q8 0 (00. n) 00

L L L:f 0 IL L L L-L L (. J

II Quincy 99

=e

Using a Linked-list Template

II Listing 11.7: A Linked ist of integers #include <iostream>

#include "linklist.h"

int maine ) {

Class Templates

Lin ked List <int> IntList;

for (int i = 0; i < 10; i++) IntList.AppendEntry(i) ;

int* ip = IntList.FirstEntryO; cout « "\n\t";

while (ip) {

cout « *ip « ' ';

if (*ip == 0 II *ip == 5 II *ip == 8) IntList. RemoveEntryO;

ip = IntList.NextEntryO;

}

cout « "\n\n\t";

while ((ip = IntList.NextEntryO) != 0) cout « *ip « ' ';

cout < < endl; return 0;

}

Ex1107.cpp program c12 GO?C\Y.)§~~uSa?~§~8 LinkedList object ooSyc12 type (int) parameter G<l~:§l[§: declare or80100uSil 1D1D~8: for loop ro,,? AppendEntry( ) c12 call GQT[§: list roc12 integer (10) yc12 co~Go:o100uSll list rom first integer c12 FirstEntry( ) function ~ point or8[§: while loop ro,,? ooSy~8: display or8~8:o100uSll 0 I 5 ~ 8 ~c12GOJ.~8 RemoveEntryO call GQw,: (J),d;oSQo100uSll NextEntry( ) call O'Y) list romGs')d;~ integer G<lc8ruG:GQT GO:::D'):~o1ol1

)1'1 lj 'J 0 T L J 0 J

G<l'):ru:~:::D'):c8 Gs')d;ooSr;::QG list rom integer GoodS display ru8~8:Q8 integer (3) Qm o1~~())a5

l.. t1 0 1.O T U 0 L L L -L L J L

GOY:).o1~:1I LinkedList.h header c12 ooS::nd;ID')~d;p,,? G(J)T§(X)'):o100uSll Exll07.cpp program

#" I dilL" k dl,i t h" 0 ceo 0 f)~

"? Inc u e In e IS. orG~:co~Go:~c program or run C\(,~Olijll

Class Templates

JO

II linklist.h

#ifndef LINKLIST _H #define LIN KUST _H

template <class T> class LinkedList; template <class T>

I I The linked-list entry. class ListEntry

{

T thisentry; listEntry* nextentry; ListEntry* preventry; ListEntry(T& entry);

friend class LinkedList<T>;

};

template <class T>

I I Construct a linked-list entry. ListEntry<T> :: ListEntry(T &entry) {

thisentry = entry; nextentry = 0; preventry = 0;

}

template <class T> I I The linked list. class Li n ked List

{

II The list head. ListEntry<T> * firstentry; ListEntry <T> * lastentry; ListEntry<T>* iterator;

void RemoveEntry(ListEntry<T> *Ientry);

void InsertEntry(T& entry, ListEntry<T> *Ientry);

Class Templates

public:

Linkedl.istr); rvLinkedListO;

void AppendEntry(T& entry); void RemoveEntry(int pos = -1);

void InsertEntry(T& entry, int pos = -1); T* FindEntry(int pes):

T* CurrentEntryO; T* FirstEntryO;

T* LastEntryO;

T* NextEntryO; T* PrevEntryO;

};

template <class T>

/ / Construct a linked list. LinkedList<T> :: LinkedList( ) {

iterator = 0; firstentry = 0; lastentry = 0;

}

template <class T>

/ / Destroy a linked list LinkedList<T> :: rvLinkedListO {

while (firstentry) RemoveEntry(firstentry);

}

template <class T>

/ / Append an entry to the linked list.

void LinkedList<T>:: AppendEntry(T& entry) {

ListEntry<T>* newentry = new ListEntry<T>(entry); newentry->preventry = lastentry;

if (lastentry)

Class Templates

JJ

lastentry->nextentry = newentry; if (firstentry = = 0)

firstentry = newentry; lastentry = newentry;

}

template <class T>

/ / Remove an entry from the linked list.

void LinkedList<T>:: RemoveEntry(ListEntry<T>* lentry)

{

if (Ientry == 0) return;

if (Ientry == iterator)

iterator = lentry->preventry;

/ / Repair any break made by this removal. if {Ientry->nextentry)

lentry->nextentry->preventry = lentry->preventry; if (lentry- > preventry)

lentry->preventry->nextentry = lentry->nextentry;

/ / Maintain list head if this is last and/or first. if (Ientry = = lastentry)

lastentry = lentry->preventry; if (Ientry == firstentry)

firstentry = lentry->nextentry;

delete lentry;

}

template <class T>

/ / Insert an entry into the linked list.

void LinkedList<T>:: InsertEntry(T& entry, ListEntry<T>* lentry) {

ListEntry<T>* newentry = new ListEntry<T>(entry); newentry->nextentry = lentry;

J?

Class Templates

if (Ientry) {

newentry- > preventry = lentry- > preventry; lentry->preventry = newentry;

}

if (newentry- > preventry)

newentry- > preventry- > nextentry = newentry; if (Ientry = = firstentry)

firstentry = newentry;

}

template <class T>

/ / Remove an entry from the linked list.

void LinkedList<T>:: RemoveEntry(int pos) {

FindEntry(pos); RemoveEntry(iterator) ;

}

template <class T>

/ / Insert an entry into the linked list.

void Linkedlist<T>:: InsertEntry(T& entry, int pos) {

FindEntry(pos) ; InsertEntry( entry, iterator);

}

template <class T>

/ / Return the current linked-list entry. T* LinkedList<T>: :CurrentEntryO

{

return iterator ? &(iterator->thisentry) : 0;

}

template <class T>

/ / Return a specific linked-list entry.

Class Templates

J9

~~~"SI.~~-~l))~Th'1~Th J)"\:>'S) {

if (pos != -1) {

iterator = firstentry;

if (iterator) {

while (pos--)

iterator = iterator->nextentry;

}

}

return CurrentEntryO;

}

template <class T>

/ / Return the first entry in the linked list. T* LinkedList<T> :: FirstEntryO

{

iterator = firstentry; return CurrentEntryO;

}

template <class T>

/ / Return the last entry in the linked list. T* LinkedList<T> :: LastEntryO

{

iterator = lastentry; return CurrentEntry();

}

template <class T>

/ / Return the next entry in the linked list. T* LinkedList<T>::NextEntry( )

JJ

Class Templates

{

if (iterator = = 0)

iterator = firstentry;

else

iterator = iterator->nextentry;

return CurrentEntry( );

}

template <class T>

/ / Return the previous entry in the linked list. T* LinkedList<T> :: PrevEntry( )

{

if (iterator == 0)

iterator = lastentry;

else

iterator = iterator->preventry;

return CurrentEntryO;

}

#endif

BlQuincy99

Class Templates

Ji,

oo.G

Partial Template Specialization

template partial specialization ~aYJ primary class template ~ G'd(.x{:,d5W::D:G:::D~ro:)_~:

L -Lo c.:.. L u, L c:,

paramter G(1)<.:f)') G'dJI:bI(1)a) special parameter G(1)d5G'd::D:r,:lco'):a) template Jl:d5~c801(1)oSll

o iJl IL 0 0 L L l:j 0 iJ L L L

eo~ primary class template (1)Sy'[-l object (2) yo? parameter GqsG'dG,,~ pass 0(0g9BlCO'):[§:

~~ object G(1)d5m~olllaYJ~ display ro0c8Q(1)oS~01SI1 (1)SmoSc8 !3~W object G£Q')bI') char

o LoT iJ J L LO "I L LO LO L T -L - J

value (1)Syo?G~8:CO'):[§: integer value G'dG,,~ OCObi object '[-l co~Go18:Go:~8o? template blJl:

d5 create ro0~bloS~Q8 ~~ClI!Y.)d5 template partial specialization c8G@Tol(1)oSll Exll08. cpp

L L 0 l "I CQ) L LO

program o?GC\lro')§~oll1

/ / Listing 11.8: Template partial specialization #include <iostream>

template <class Tl, class T2> class MyTemp

{

Tl objl; T2 obj2;

public:

MyTemp (Tl 01, T2 02) : objl(ol), obj2(02){ }

void display()

{

cout « n\n\tOBJECT DISPLAY\n\t--------------\nn

« n\tObject 1: n « objl « n\n\tObject 2: n «obj2 «endl «endl;

}

};

template <class T> class MyTemp <T, char> {

T objl, obj2; public:

MyTemp(T 01, char c) : objl(ol), obj2(01) {obj2 += (int) c;}

J'2

Class Templates

void display() {

cout « "\n\tOBJECf DISPLAY\n" < < "\t-------------- \n"

« "\tObject 1: " « obj1 « endl « "\tObject 2: " « obj2 « endl « endl;

}

};

int main() {

MyTemp <int, int> mU(10, 20);

MyTemp <int, char> mt2(10, 'B');

II 'B' = 66

mt1.display( ); mt2.display( ); return 0;

}

Exll08.cpp program d5 run c805ldoS£Slt 6 (:::>:::>. (;l) Id')r.:cm:a) (3dcfS8: r.:8Slld')oll1

L L L "I L C. J l:j 0 L LJ "I J

III Quincy 99

Class Templates

JIfl

BASIC language a?4)OO8GotCOO~~gp:8dGft C language a? ala)ruoSGotCOO§o} aJ~l C r,p string operator G068d§Suloto} strcpy( ) ~ strcmp( ) function 8?8ac (2) ya?0G06. Qm8dooa) aJ'J:g03aJ'J:gQ~S~~uloouSll :i5G~ru:lS: C mGS C++ d3 ala)ruoSGrucoo~m8d~lg')

-to 0 L -lCj.Lj LO c:. T L .~. J

3aJ'J:s:lS:~loSGOO8d,):ru: GUrJoSmuS::lY):Q')')d3GOO Qg')ull1 C++ g')ulotm string class (:r.mi3Qt

TC iJ 0 L IJ- 0 -0- L Qo-lJ J 0 L-l

string object GD6~uaS::Da)I9: aJ§~?~:C\(8Gu:~tI9Grull 2ug') string object G06a? construct ru8guS I assign ru8guS I concatenate ru8guS I compare ru8guS I search ru8guSd3Qt <string>

L L L L L L-L

h do. Ide " ceo "1 o c C

ea er or program r,p me U e C\(UGu:Q')')~ 8dorfC\(u0?,9ulru-:g().)1I

o J.O The string Class

JI ~ (OJ. 0) r,pGlOT§CX)'):o} Ex1201.cpp program OJ')~98 string G06 construct C\(8f~: 3';jgJl:gJl:o?G9:§a)':}:o} program ooSy§SuloouSll 4)4)~J8:r,p string sl; ~G9:a)':}:o} statement mGf empty string ooSYa? construct C\(8G<..>:r,pulll GPoSooSf~:m string s2("This is a string");

J~

Standard C++ Library

o r.::e r,;:e e" tri bt t t· bt t 2 0 t t c '1 o c c

~Gq:[jc:an:1j'9 06c:rom s nng 0 ~ec mG~ S nng 0 ~ec s 0( cons ruc C\(0GO:OI(\)';l(,lO)II

c c 0 h[] h t c r,;: c c 0 c tri 3( h) 0 0 c " tri

0)0mO)~ C em C arac er array 0)0YIj'0(,l0)~qC s nng s c ; ~Gq:C\(mO)')'f. S nng

object s3 em construct §S~'):~: content m ch[ ] ~. character array o§S':polll

II Li sti ng 12.1: Constructi ng stri ngs #i ncl ude <i ostream >

#include <string>

int main() {

string s l :

string s2("Thi sis a stri ng");

cout «"\n\ts2 ="« s2 « endl;

II Construct a string object from a character array

char ch[] = "Thl sis a character array";

string s3 (ch);

cout «"\n\ts3 ="« s3 « endl;

return 0;

E 120 1 0 0 c c 0 c • ( ) ~ " 0 c ~ c '1

JII X .cpp program 0( run C\(m(,lO)~qc « :) J. J '{-'t:fCX)'):O?~OCc: BCq'{-'OIIi

1ItQuincy 99

Standard c++ Library

Assigning Strings

t . b· tat t c~ ~ 0 C c.... C • §c c a '1 c

5 ring a jec GO)O) cons ruc (\)0 : ;:DQC 0)0)<;)£0)0)<;) assign £(\)OGO:(\)QOIO)Q)II

OL L L-l LTo L TL Lo-l

eo~ string s2("This is a string"); d2 construct or8~:q8 string 51 = 52; 8dG"t assign

Oil

/ / Listing 12.2: Assigning strings #include <iostream>

#include <string>

int main() {

string 51;

string s2("This is a string");

cout «"\n\ts2 ="« 52 « endl;

51 = 52;

cout «"\n\ts1 ="« 51 « endl; string 53 = "A different string";

cout «"\ts3 ="« 53 « endl;

return 0;

}

DlQuincy99

Standard C++ Library

Concatenating Strings

st . bi ct 0 t tl t +" + 0 0 0 ~ ~ c" c c

011 ring 0 Je G06o( conca ena Ion opera or ~ = O?O(mo.r:l:::1ll:::1: 0)0y~(m)ya:::>mGO:

~S)()lO)uSll Ex1203.cpp program d2G(\)(\Y.)§~()ll1

II Listing 12.3: Concatenating strings #include <iostream>

#include <string>

int main() {

Standard C++ Library

?J

string string string

s4("Helio "); s5("Complete C++"); 56 = 54 + 55;

cout «"\n\ts4 ="« 54 «"\n\ts5 ="« 55

«"\n\ts6 ="« 56 « endl; 54 += 55;

54 += '!';

cout «"\n\ts4 ="« 54 « endl; return 0;

}

Subscripting Strings

011 string object O')S~o)'G£ single character O')S~d5Q)05U)~oSll 81~~(J)05 character O')S~

L T L L L IL J L L

o?Gi'':la5 character O')Sy~ Gd0'):d2:Go:~J8q8 subscript operator [ ] ~~or05 at(int) member

function a?Gd~:§lqo1~oSll Ex1204.cpp program a?GC\?(\)')[§~o111

/ / Listing 12.4: Subscripting strings #include <iostream>

#include <string>

int main() {

string s4("Helio Complete C++! "); char ch1 = s4[1];

char ch2 = s4.at(2);

s4[5] = ',';

cout « "\n\tch1 = " « chi « "\n\tch2 = " « ch2

«"\n\ts4 ="« s4 « endl; s4.at(0) = 'Z';

cout «"\n\ts4 ="« s4 « endl; return 0;

}

E 1204 0 0 C' C' 0 C' • ( ) r,: ... 0 C' r,: C' ')

JII X .cpp program err run C\(O)~U)~qc « oJ. J 'f-'r:fQ)'):O?GdO(c: ljCq'f-'OIIi

tiilQuincy99

Standard C++ Library

Subtrings

:)11 string object cnS:;lmGs substring cnS:;lcB ~CDaSo'):;l18Q8 substr( ) function cB~::D:~lQ

L T L L 0 L IL ij -I L L t1 -I

ol~oSll Ex1205.cpp program a?GC\?CIY)§t§oln

II Listing 12.5: Substrings #include <iostream> #include <string>

III QUincy 99

_IDJ..?!J

int main() {

string s4("Hello,Complete C++!");

cout « "\n\ts4.substr(6,8) =" «s4.substr(6,8); string s7(s4.substr(0,5));

cout «"\n\ts7 ="« s7 « endl; cout « "\n\tLength of string s4 = "

« s4.length( ) « endl;

string s8(s4.substr(s4.length( )-4,4)); cout «"\n\ts8 ="« s8 « endl; return 0;

}

JII

Ex1205.cpp program cB run c8aS~oSJ3Q8 0 (:)Jo G) ~~ClJ'):o)~~8: ~8Q~oll1

L L L -1 L J l:1 0 L ~ -1 J

Standard C++ Library

Searching Strings

011 standard c++ library rom string class ~ find( ) I rfind( ) a:?o? overloaded function GcndS (X) "'GO: coos 01 cnoS II find( ) function dS9d~:~l~: string object ror.n matching substrlnqi

o L et L l t1t1 J

single character ~~0(05 character array ~o? string 9d0mG'i'0~: forward search C\(8~801cnoSll

cnSmoSc8 search argument dS .::n~GmO'):~Q8 -1 value dS return C\)8Go:01c8o~oSll repeated

LO L jl- -6 It L -L L L •

search argument ~~8q8 rfind( ) function o?9do.?:§lq8q01cnoSll Ex1206.cpp program o?

G<\l(\)')6~0111

II Listing 12.6: Searching strings #include <iostream>

. #include <string>

int main() {

string s4("Helio ");

string s5("Complete C++ "); s4 += s5;

s4 += '!';

s4[5] = ',';

s4.at(0) = 'Z';

I I Searching strings

int n = s4.find("C++n);

cout «"\n\tn = II « n « endl; n = s4.find(II');

cout «"\n\tn ="« n « endl; n = s4.rfind('I');

cout «n\n\tn ="« n « endl; n = s4.find(nbyen);

cout «"\n\tn ="« n « endl;

return 0;

}

Standard c++ Library

E 1206 0 0 C C 0 C • ( ) ~ " o c ~c 'I

JI X .cpp program ar run C\(m~().)~~c cr oJ.? 'Pt:1CXYJ:0?!:nO(c: t::lC~'P()11I

1.11 Quincy 99

Comparing Strings

011 Ex1207.cpp program <n string object GO') ~8:().)2c s~~:d5 program O')So> GQ:~CXYJ:ulO')oSl

J 0 JL J T c.:. L L -1 t1

/ / Listing 12.7: Comparing strings

#include <iostream> #include <string>

int main() {

string string

sl("C++ "); s2("Programming ");

if ("Bye II < 51)

if (52 == "Programming ")

Standard C++ Library

if (52 > 51) {

string s3("Complete ");

string 54 = 53 + 51 + 52;

cout « 54 « endl;

}

return 0;

}

o J. J The string Member Functions

::>11 standard c++ string class r.p member function (4) (,)Jl: 01 §oloooS II (::l) dean ) (j) empty( ) (?) length( ) ~ (9) data( ) function a?,§ S§oloo .S II clear( ) function <JY) string object GoocB zero length oo~8:~SGG';n8 clear ru8Go:~801oooSll empty( ) function mGO')')

o L TLLl L L 0

string object ooSy<JY) empty §S(,)§Sd? check or8Go:o1(')oSll empty §Sq8 true bool data d?

return or8Go:r.po111 empty (,)crr_chq8 false Goll1 length( ) function m string object r.polo8o? character fJdGQfJdoocbcB GQOOcbGo:Q')olol1 string data buffer ooS~cB point ru8Gscf) canst

-L 0 L -L 0 J L L L T 0

painter ooSyo? return or8Go:~J8q8 data( ) member function d? fJd~:§l~qo1oooSll function

G"6 fJd~:§l1'~:d? Ex1208.cpp program r.pG<9T@OYJ:01oooS I G~C\Y.)§t&oll1

Standard c++ Library

/ / Listing 12.8: Using the string member functions #include <iostream>

#include <string>

int len = str.length( );

void test (const string& str) {

if (str.empty( ))

cout « "\n\tThe string is empty\n";

else

{

cout « "\n\tThe string has"

« len « " characters.\n\t\"" « str « "\"\n";

}

}

int main() {

string str; test(str);

str = "C++ Programming"; test(str);

str.clear( ); test(str);

return 0;

}

;tandard C++ library

FormaHed Output

The ios: :width( ) Function

;'1 Cs-+ program (J)S~d5 run cSch~: output d5 fixed column width (J)S~cOG') GoT C\Y.)GID

L L L t1 L L J

~8~8 width() member function ~O'd~:§l~ol~oSlI Ex1209.cpp program "fJ array x[ ] value

;'CJ~ column width (10) ~o? column cO"fJ fixed format ~~O(aS scientific format ~ righta ign or8~: display or8§~8:CXY):ol(J)oSlI

II Listing 12.9: Using width( ) member function #include <iostream>

int main() {

static double x[] =

{ 0.00000012, 1.23, 345.678, 56789012.34 };

cout.setf(ios: :fixed, ios: :scientific ); for (int i = 0; i < 4; i++)

Standard c++ Library

{

cout, width(10);

cout « x[i] « endl;

}

return 0;

}

E 1209 0 0 ceo c. ( ) ~ " 0 C ~ C ') 0 C C

X .cpp program 0( run O(o)blo)~9.C« oJ. 00 '{-'l:fCO'):O?8<lO(C:t::JC9.0ICD~blo)"

t Icc C 0 C 0 c~" ') C • t'f' f t "d' I

argumen va ue IJ.Y) 8<lCl6'fCo)blo) ~blO(O') ::D0t:j:O?8<lQ!O)J9.c seen I IC orma 'f. ISP ay

O(O§ '{-'ol " argument value 0)~'f~~9.8 column width a:)(f.>blGo)?o?8<lQ1'f') fixed format ~ display O(o§ol~~bloS" column width CX)a5GO)?qr->:9.8G~ argument value 62 round (6 decimal places) CDoGo:{,l')ol"

L J

J"

alQuincy99

The setw( ) Manipulator

0" data display 0(00')')62 table form 8<lG'f~G(J)T§QJ89.8 setw( ) manipulator 628<l~:§l[9: column width ~O')SG£Q')Q,8: adjust CDoGO:~QolO)oS" setw( ) function ~8<l::D:~lg8a8<l0)a5

l T "T iJ L to -L L L l:f L LO 0

<iomanip> header ~ program (,l') include CDoGo:QolbloS" cout.setf(ios: :fixed) ~8<l::D:~l~Q8

L J L "I L L L:1 0 "I

argument value IJ.Y) ~OCoSG~o?8<lQl'{-' o.r~Go;?OG(J)T§Go:ol~~bloS" Ex1210.cpp program 62

GC\?C\)')§~ol"

Standard c++ Library

/ / Listing 12.10: The setw( ) manipulator #include <iostream>

#include <iomanip>

int main() {

static double x[] =

{ 0.00000012, 1.23, 345.678, 56789012.34 };

static char *ch[] =

{"ZARNI" "ARKAR" "AYELWIN" "POZAW"}'

, , , ,

cout.setf(ios: :fixed); cout « endl;

foro (int i = 0; i < 4; i++)

cout < < setw(10) < < ch[i] «setw(20) «x[i] «endl;

return 0;

}

JI

E 1210 0 0 C C 0 C • ( ) § " o c BC '1

X .cpp program m run cococcococc 0 oJ. 00 If.) <XY):cnG';lcnc: C@lf.)OIIl

L L L -1 L J 0 L -lJ

fit QuincV99

?II cout.setf(ios: :fixed) G';lW: cout.setf(ios: : scientific) o?G';l~:§l~oSa?98 ~ (oJ. oj) 'P§

C:O?:O)G';ld38:~8@~?oll1

o L l:J -lJ

Standard c++ Library

Standard C++ Library

9J

The ios: :fill( ) Function

011 program <n fill( ) function d58d:::D:r:l(doS~Q8 output <n display ro8r:(doS value Go)~

J L L lj L -l J L lj • o-~

G~mC)?05o? G~~Go;?'f' fill() function argument ~8dI!Y):<V- G[p8:Go:~:'f'§SolO)oSll Ex1211.cpp

program o?GC\?C\Y.)6t§oll1

II Listing 12.11: The fill( ) function #include <iostream>

int main() {

static double x[] =

{ 0.00000012, 1.23, 345.678, 56789012.34 };

cout < < endl;

for (int i = 0; i < 4; i++) {

cout.width(10); cout.fill('*');

cout < < x[i] < < endl;

}

return 0;

}

Output Justification

011 ~ (OJ. OJ) 'f'8CO'):o? program output 'f'P~~G"6o? left-justified C\(8G(j:~8q8 setiosflags

(ios:: left) manipulator a? Q)~Gq:G0:q8q(jlo)(i311 Ex1212.cpp program d2GO?C\)')§~(jll1

II Listing 12.12: The output justification #include <iostream>

#include <iomanip>

int main() {

static double x[] =

{ 0.00000012, 1.23, 345.678, 56789012.34 };

static char* ch[] =

{"ZARNI" "ARKAR" "AYELWIN" "POZAW"}'

, , , ,

cout « endl;

for (int i = 0; i < 4; i++)

9?

Standard c++ Library

Standard c++ Library

99

{

cout < < setiosflags(ios:: left) «setw(12) «ch[i]

«setw(15) «x[i] «endl;

}

return 0;

}

E 1212 0 0 ceo c • ( ) ~ , 0 C ~ C '1

JI X .cpp program 0( run C\(mgQ)~9_c y 0 Jo 09 'f't:fOYJ:O?mO(c: t:::lC9_'f'()11I

II Quincy 99

The setprecision Manipulator

011 6 (oJ. 09) ~~OYJ:aJ program output ~ 8d3Q)G~rom value Gcnci3 right-justified I

L J t:f • J L 0 L

setprecision (1 decimal place) ~G0T§Gu:~89_8 Ex1213.cpp program mcJ28: G9_:G():9_()lguSll

II Listing 12.13: The setprecision manipulator #include <iostream>

#include <iomanip>

int main() {

static double x[] = {0.00000012, 1.23, 345.678, 56789012.34 };

static char* ch[] =

{"ZARNI" "ARKAR" "AYELWIN" "POZAW"}·

, , , ,

cout < < endl;

for (int i = 0; i < 4; i++) {

cout « setiosflags(ios::left) « setw(lO) « ch[i]

< < setiosflags(ios: :right)

« setw(lO) « setprecision(2) < < x[i] < < endl;

}

return 0;

}

II Quincy 99

Aligning Decimal Points

011 ~ (0 J. OJ) 'fJG<9T[9cm:o} program output 'fJ td3o)G~rom floating-point value G06d2

decimal-aligned C\(8Go:aJ8Eq8 Ex1214.cpp program 'fJ G~cm:o?8'i)o?8:G~o111

9J

Standard C++ Library

static double x[] =

{ 0.00000012, 1.23, 345.678, 56789012.34 }; static char* ch[ ] =

{"ZARNI", "ARKAR", "AYELWIN", "POZAW"};

II Listing 12.14: Scientific and fixed notation #include <iostream>

#include <iomanip>

int main() {

cout « setiosfJags(ios::left) « setw(10) « ch[i]

« resetiosflags(ios::left) « setiosflags(ios::fixed) «setiosflags(ios::right) «setw(12)

« setprecision(l) « x[i] « endl;

cout « endl;

for (int i = 0; i < 4; i++) {

}

return 0;

}

Standard C++ Ubrary

The Table of Square Roots and Squares

011 Ex1215.cpp program ())')~9.8 2 mG'i' 10 G'da3 OC1l)~: (9) ~:d2 square root ~ square

G06~~: (_b.W'):~0~ display C\(8§~8:a? program §S()lmoS I GC\?C\Y.)§~()ll1

/ / Listing 12.15: A table of square roots and squares #include <iostream>

#include <iomanip>

#include <cmath>

int main() {

double x;

cout < < "\n\t X

sqrt(X)

X*X\n\n";

for (x = 2; x <= 10; x++) {

cout < < resetiosflags(ios: : left) «setw(12) «setprecision(l) « x

< < setiosflags(ios: :fixed) «setw(12) «setprecision(4)

« sqrt(x)

< < setiosflags(ios: :fixed)

< < setw(12) < < setprecision(l) « x*x « endl;

}

return 0;

}

E 1215 0 0 ceo C • ( ) r: '- o c ~c '1

jll X .cpp program ere run C\(mblu)~9.c cr oJ. 0'2 'Pt1(X)'):a?G'dO(c: [3C9.'P()11I

9'2

Standard c++ Library

o J.~ Output Member Functions

011 std::ostream class rol.fJ single character 62 display or8§o} put( ) member function ~ output object stream G0662 display or8§~~ overloaded < < insertion operator ~()108§()1 moSll Ex1216.cpp program 62GO?(\)')§~()111

/ / Listing 12.16: Output member function #include <iostream>

int main() {

cout, put('C'); cout.put('+'); cout.put('+'); cout « endl;

Standard c++ Library

cout < < 'C'; cout « '+'; cout « '+'; cout < < endl;

return 0;

}

JI

E 1216 0 0 C C 0 C • ( ) § " 0 C §c 'I

X .cpp program m run CDmblWa:)QC () oJ. 01)) bl') CO':l:OOG'dOOC: C Qbl')() III

L L L -L L J • l -L J

\,11 write( ) member function ooSY()Y.) output data d? binary format G'dG'l't. stream cD d38G(): ()1 00 uS II Ex1217.cpp program d3 run cSa5Q8 message d3 display G'dQ8CD8~~: alarm

L lO L L -L L -L L ljl:j

§ C • o~ 'I ~<;'[§ xt I' 0 0 0 'I o c C

cococo :Qbl')()11I G£'XD : ne me c» G'dCDCDm::).)'):()ICDblblWIl

c.:. L -LJ T l L L IL 0 0

II Listing 12.17: Output member function #include <iostream>

int maine )
{
static struct
{
char ch[40];
int alarm;
int eol; Standard c++ Library

} msg = {"Complete C++ Programming",'\a','\n'};

cout.write (reinterpret_cast <char*>(&msg), sizeof msg); return 0;

}

OJ.9 Input Member Functions

011 c++ program GOO'=Y.) > > extraction operator ~8'd~:~l~: data input (l.)8~oS08c3gQt

o J L L lj r:1 L L LO jl -L

87.l:soS:QI0500SQa) data input '=Y.) white space Gooo1C\Y.)Qt data c3~w;:;00 Ga)'>:'::D'J:01c3G~oSll

Tc.:.. iJ L J 0 -L L.O IL aJ 0 0

~~o?~GCT.(]~G0~tqz:~q8 get( ) member function o?8'd~:§lqo1~oSll Ex1218.cpp program

"P > > extraction operator f. get( ) function o?o?~8:Uj>2§(XY):o1oooS I GC\'C\Y.)§~o111

II Listing 12.18: Input member function #include <iostream>

int main() {

Standard c++ Library

char line[25], ch = 0, *Ip;

cout « "\n Type a line terminated by 'x'" « "\n > "; Ip = line;

while (ch ! = 'x') {

cin » ch;

*Ip++ = ch;

}

*Ip = '\0';

cout « ' , « line;

cout « "\n\n Type another onexn > "; Ip = line;

ch = 0;

while (ch ! = 'x') {

cin.get(ch); *Ip++ = ch;

}

*Ip = '\0';

cout « line « endl;; return 0;

}

E 1218 0 0 ceo C • ( ) r,:. " 0 C r,:. C '"'I

X .cpp program 0( run C\(m(dOJa:r~c <r o J. JO ':rt:Jcm:O?~O(c:tlC~':r()'1I

rIIQuincy99

~ (:) J. JO)

Standard c++ Library

Standard C++ Library

JJ

C C 0 COO C~' t d t cENTER 0 C 0 C " t t

?II 0')0<Y.lWO(. ++ program ac run C\(<Y.ltj: mpu a a OJ~ I ~oC\(<Y.lO)')'f. ou pu

display C\(8§G0~898 Ex1219.cpp program 'fJ G9:cm:o?G<lJ28:G9:9o1~oSl

II Listing 12.19: Input member function #include <iostream>

int main() {

char liner 40];

cout « "\n Type a line terminated by carriage returnxn > "; cin.get(line, 40);

cout «"\n "« line « endl;

return 0;

}

C co· t d t d coo C C t t d' I Ch 0

911 G'f,)<Y.l0')0~l:<Y.l InPU a a 'fJ passwor 0')0yacEt1<Y.lOJ~Go:'i ou pu ISP ay C\(otjO)')~l:

§SG0~J8S[8 Ex1220.cpp program 'fJ§cm:o?G<lJ28:GS[:oln

/ / Listing 12.20: Input member function #include <iostream>

int maine) {

char liner 40];

cout « "\n Type a line terminated by 'q'\n > "; cin.getline(line, 25, 'q');

cout «" "« line « endl;

return 0;

}

III Quincy 99

More on the get( ) Function

II Listing 12.21: More on the get( ) function #include <iostream>

int main()

{

char ch;

while ((ch = cin.get( )) != EOF)

cout « "ch = " « ch « endl; cout « endl « "Bye!" « endl;

return 0;

}

E 1221 _0 0 ceo C • ( ) ~ " o c ~c ') <.:l

X .cpp program 0( run C\(O')blQ)~E>tC « o J. JJ ':Pt:1cxn:O?adO(C:GC9.':PolII 3

o r;::;::: C c" t() 0 • ~ ~ trl b" ct C h ct c. C 0

program orGC\?(\),)t:.j~9.C cm.ge orad~:t:1lb: S ring a ~e adOJO') c ara er 0)0C\(:~C:or

display C\)8~:xY):010)oSll ENTER key d3~8ci3mO)dJ ch = <blank> (JY) ~dJGoT (\)')0)')0111 data

Lt:10 LJ' 0

Standard c++ Library

Standard c++ Library

J9

input <BC\)a5~o1G~:O)oSll CTRL + Z +ENTER key GO)<B~8Q8Goy) Bye! ~o) message <B

L 0 L J -L· L • L

display C\(8§@: program stop §S~:o1@11

IIQuincv 99

Using the get( ) Function with Parameters

II Listing 12.22: Using the get( ) function with parameters #include <iostream>

int main() {

char ch1, ch2, ch3;

cout < < "\n\tEnter three letters : "; cin.get( ch 1 ).get( ch2).get( ch3);

cout « "\n\tchl = " « chi « end I < < "\n\tch2 = " < < ch2 < < end I « "\n\tch3 = " « ch3 « endl;

return 0;

}

E 1222 0 0 ceo c • ( ) ~ .... o c ~c '1

X .cpp program 0( run orm~Q)arqc c.c 0 Jo J~ 'f't:lcm:O?8'dO(c: t:::lCq'f'011l

Using the peek( ), putback( ), and ignore( ) Functions

II Listing 12.23: Using peek( ), putback( ), and ignore( ) functions #include <iostream>

int main() {

char ch;

cout « "Enter a sentencein":

Standard C++ Library

while (cin.get(ch)) {

if (ch == 1#1)

cin. putbackf'Z'):

else

cout « ch ;

while (cin.peek( ) == 111) dn.lqnore/I,'!'):

}

return 0;

}

E 1223 0 0 ceo c • ( ) ~ , 0 C ~ C "\

X .cpp program ac run C\(m~warE»c « o J. J9 '?tI coo: O? 8'dO(c:l::jc E»'?o III

Standard C++ Library

data GO')65 disk 11tGO')mGMa5().)~oS i5~c..:na5 disk 11tGO')GoT 65 GQ:co~C;;GO:~ltO')oS

aLL a T IL LO L L a L "I U I,j

~~§qt c++ input/ output system o?~'):ru~~o?olO')oSll standard c++ library r.p disk ~t

GO')65 manage ru6aGdO')~ I/O class GO')Gd~',):GdI,'''"':ol~olO')oSll C++ Q I/O operation GO')~

aLL (_O 0 a iJ t1.J J -[0 0 J

o • t ", t 0 d t fl C 0 c. rr -r- C

GdGmGdml;;o:mGO')') S ream 01011 s ream ceo» a a ow O')<D~m Gdru().)m;;o: G~I Gal O')Gd~~)

tJL 0 L LL a ILL 0 c.:.

O')S~~SolO')oSll GdJI:Gd<D'):~O')a) stream GO')(J)')d3Qt ml,'''"':~:s'):a) data flow Gdru6GO')65ru6Go:

Llj IJl IL 0 0 L -L oL:::1..J L1J T 0 L aLL

~~olll stream d5t:~::D~d38Q') class GO')gGsolO')oSll m~ class GO')oom member function

~ J L J L -L- 0 jl T 0

GO') I definition GO')(J)')::D~d3tQ') stream GO')65c8~:~'l6Go:::D'):~~SolO')oSll ooco ifstream class

o 0 LT OLTiJ OJL::1 c

object (J)') input disk atGO')~ write ru6aGdO')~Gd::D:hlolO')oSll extraction > > operator m

L OJ L LO a Lr:1

istream class q. member O')Sy§S::Do? insertion < < operator (J)') ostream class q. member

O')S~~SolO')oSll istream ~ ostream class GO')(J)')ru~S: ios class mGS derive ru6CD')a) derived

Llj To a c:.:. T L 0

class GO')OGrull at input! output Gdru6GO')~ ml~G~d5ga5ot<D'):dJ: class GO')m input atGO')

aLL OJ dJT LG L a L 0

GdO')~d3Qt ifstream ~ output atGO')GdO')~ ofstream class object GO')~SolO')oSll G1Go~oS

a L -l To L 0 0 OLJ 0

<of stream > ~ <ifstream> class object a?,(J)') <fstream> header ~tO')SyO')~: Gd~:§lO')')~

qolO') oS II

Standard C++ Library

o~.o The fstream Class

011 GGr.>aS'flGtPT§CXY:>:o} Ex1301.cpp program em test.txt ~o} output ~8OJS1'fl string

it c" r;;: c '"l c ~ c '"l

Go;? wn e orOGo:O? program [j'IDOIOJo) I GC\?C\Y)e:1~OIIl

II Listing 13.1: Writing strings to a file #include <fstream>

int main() {

cout « "Creating file ... \n" ; ofstream outfile("test.txt"); cout « "Writing to file ... \n" ;

outfile « "\n\tReaching new heights in global education. \n"; return 0;

}

jll Ex1301.cpp program o?GC\?C\Y)§~~oS~~8 outfile o?,GQT 0} of stream class object instance OJSQc?J construct ruO~: OJS~~OJ~:~o 3 object c?J test.txt g8~ initialize ruoGo:CXY:>:

L L L lj tJT c.::.. J L L To L

OY)c?J~~oll1 3 program c?J run c8aSo?~Q1OJIQ8 output OJ screen ~~GoTolJ):1I test.txt g8

L ~ Ci.. L L 0 tJ "I J IL L

Reaching new heights in global education.

Standard C++ Library

O~.J

Appending to an Output File

• ( ) m;; 't ttxt t t o c tri C' 0 0 0 C' C' • 0

011 yO? 0 'flGto'ljCXY):a;> ex. ou pu Cfc'fl S ring 0)0~l.orO(:GO:~CS[C lOS: :app or

GS[:cx)~Go:S[tS[o10)oSll Ex1302.cpp program d2GCI?ro')§~o111

/ / Listing 13.2: Appending to an output file #include <fstream>

int maine) {

cout < < "Opening file ... \n" ;

ofstream outfile("test.txt", ios::app); cout « "Writing to file ... \n" ;

outflle « "\n\t.. .. here more to come!"; return 0;

}

JI Ex1302.cpp program d2 run 6?05o}G<lQ1CY.ljS[t output CD screen 'fl~GoT o1~:11 test.txt

:l';- , tri C' ~C' 0 0 '1 o c C' • ( ) o~ C' '1

,(c'flo S ring 0)0G~-,C: O(:G'fO)')orGo;?S[Olro~~o)lI YO? J or~e.:0lll

Reachi ng new hei ghts in global educati on . .... here m ore to com e!

Standard c++ Library

o~.~ Avoiding to Open an Existing File

Standard c++ Library

(So

I I Listing 13.3: Avoiding opening an existing file #include <fstream>

int main() {

cout < < "Opening file ... \n" ;

ofstream outfile("test.txt", ios: :noreplace);

if (outfileJail( ))

{

cout « endl « "File already exists!\n" « "Delete it (YIN)?" « endl;

char ch; cin » ch;

if ((ch == 'Y') II (ch == 'y')) {

ofstream outfile("test.txt"); outfile « "These are test data.\n" « "New file created.\n";

}

else

cout « "File not opened.\n";

}

cout < < endl; return 0;

}

jll Ex1303.cpp program d2 ~ (o~. ~) '{J run BCX)')w1moSll fail( ) member function OJG'f message prompt (\)bGo:m8<JQ1m N dS~bm8<Jmch test.txt 88CfY) override 8<Jr.;:S(')QQGOY.)ol:r.m

L 0 J L J 0 0 L lj -L 0 IL

fIIQuincy99

The ofstream< ) Function

:)11

Ex1304.cpp program lYY)a?q8 file pointer tellp( ) ~ put( ) function o?,d28'tl~:§lB:

~rR:::D'):88OJSQd5 input data 8'tl:).)S~ override (\)6Go:o10JoS" screen GoT g)(\)~~: inputdata

Jt:j L L L To L J c:.

/ / Listing 13.4: Using ofstream( ) member function #include <fstream>

#include <string>

int main() {

string str("This is a test");

/ / Create an output stream object ofstream outfile;

/ / Associate a file with the stream outfile.open("test.txt");

Standard C++ Library

/ / Write a string one character at a time for (int x=D; x<14; ++x)

{

cout « "File pointer: II « outflle.tellpt ); outfile.put(str[x]);

cout «" "« str[x] « endl;

}

II Close up the file. outfile.close( );

return 0;

}

JI Ex1304.cpp program d? run o?a5~oSa?q8 ~ (0". 9) 'f-'§ CX)'): a} Gdd?8: §8q'f-'oll1 file pointer mG'\'a?~a} input data O)Sy~J8:d? screen "p display C\(8§G,\,ol[911 test. txt ~8d2~96~~8 ~rumgm information GO)d5 This is a test 08mroG~8:m override ru8::xn:CJ.r)d5Go) Qg)oll1

IL jl • 0 L L" ~J L 0 L 0" -LJ

--
FUr. po intel': (') T
Filt: 1'" ill tel': 1 h
Fi 11'. rninte .. : 2 i
Fi1~ pu intel': J s
Fih, pointe .. : ..
File po Ln t e r-: l) i
Fih: p'J dn t e r e f. s
·UP. po intel': ?
Fil.., P" int:c}': N n
File pn i n t e r-: 9
File pn in tel': 1111 1-
iIt: .",intel·: 11 (:
·ile po intl:l': 12 s
File }Hl intel': 13 t
Any kt: v to r-e t ur-n t" 'ju inc y ••• Standard C++ Library

Reading Strings from a File

011 Ex1304.cpp program d2 run J?d)c{?,S[a? test.txt ~tm data G06d2 read §~C\(8~tS[t

!)(l;;)a3ru8a3Qo1moSll Gm'Jd)ooGQ:r:CXYJ:m Ex130S.cpp o3GruC\)')~~o111

L L L LO -L J -L L:1 0 LOU t:.i.

/ / Listing 13.5: Reading strings from a file #include <fstream>

int main() {

const int MAX = 80;

char buffer[MAX];

ifstream infile("test.txt"); while (infile)

{

infile.getline (buffer/MAX); cout < < buffer;

}

cout < < endl; return 0;

}

.J Ex130Scpp program d2 run J?d)~oS~S[t ~ (O? J) 'j'J§CXYJ:o?md2t:§tS['j'Jo111 test.txt

8tm data 03 program m(j)a5w~: screen 00 display ru8r:O)')o1ol1

L L ILL::1 J L L:1

II Quincy 99

Standard C++ Library

char ch;

o~.B Reading until End-of-File

/ / Listing 13.6: Testing End-of-file #indude <fstream>

int main() {

ifstream outfile("test. txt");

while (!outfile.eofO) {

outfile.get( ch);

if (!outfile.eof( )) cout « ch;

}

cout < < endl; return 0;

}

SlQuincy99

Standard c++ Library

O~.7 The seekg( ) Member Function

a8mS~6S open cu8~:a8cOm information Gm6S user ~ld)(:i)G£Q')mG£ 0(j)a5~:GOJ')

L L L L lj L 0 L ~. T -l- T l:j 0

screen 'f') display or8~8:~J8q8 seekg( ) member function a?8'd~:§lqol~oSli Ex1307.cpp

o ~ C' 'I Q 0 0 C' C' 0 C' • ( ) ~ " OC' ~C' 'I C'

program orGC\>(\)')e_j~OIIi !3 program or run orm~<.Darqc c.r o~.? ~ijCO'):O?8'dO(C:t::jCqOI~<.D11

II Listing 13.7: Seeking within a file #include <fstream>

int main()

{

ifstream outfile("test.txt"); outfile.seekg( 4);

while (!outfile.eofO)

{

char ch; outfile.get( ch);

if (!outfile.eof()) cout < < ch;

}

cout < < endl; return 0;

}

II Quincy 99

Standard C++ Library

O~.6) The tellg{ ) Member Function

o c c " . t: t· ceo c" C hlt 0

(J)C(),)0QOJO') mrorma Ion g) 0')1£GOY.l()')<:Y)QIC()')00':)(),)0Q ooco W I e space G£Q')G(),)O')<:Y) L L J 61T L.Ojl-'J oCc LC T-L- 0 LJI-

Go:~8S[8 tellg( ) member function o?8'd~:§lS[ol~oSll Ex1309.cpp program o?GO?C\)')§~oll1

011

char c1; f1.get( c1);

if (!f1.eof( ))

cout < < c1;

/ / Listing 13.8: The tellg( ) member function #include <fstrearn>

int main() {

ifstream f1(ltest.txt"); while (!f1.eof())

{

}

cout < < endl < < endl;

ifstream f2(ltest.txt"); while (!f2.eof( ))

{

char c2;

streampos here = f2.tellgO; f2.get(c2);

if (c2 == ' ')

cout « "Position II « here « II is a spacexn'':

}

cout < < endl; return 0;

}

Standard c++ Library

Read and Write a Stream File

O)S~lO)SQg) program O)S~8t)G£.i a80)S~~(JI8o)8t)~lmIQ8 readl write access Q~ac8

-LJ L T To L L Loa 0 iJ -L -LJ LO L

") C' d t b 080 dOC' C' ~C' C' OC' ~C' C' 0 0 C' C'

OIO)()J1I eOg) a a ase Cf "(jl:G0'6'f> recor G0'6O((JIO)~()J I ljC~()J1I Cfc'f>lj'i"G~:~()J~OY.)"(jl: C\(a~~()J

C' OC' C' 0 dl 't C' C C' C' ' d

~0(0)c\),):1I CfCo)CDyO( rea wn e access 9.G8t)')cC\(aGm~c~c program 'f> lOS: :openmo e

argument d? ifstream constructor 'f>G~:co~Gm~al~oSll lY:Ga:Y:1,~8 ostream object instance O')S~~ declare C\)8~: constructor ~ ifstream: :rdbuf( ) member function Q return value .i

L L L lj L -to T.

, 't' I' C' ,,") 0 C' t b' tOO C' it C' 0 C' . § 0 "lY Q 0 iru ra ize C\)aGmQg)alll 81aJQC os ream 0 ~ec c: (JIC wn e C\)a(JI8t)O)m 8t)8.): lC\)Qal II eoeoco

L -LJ L -L L L L La 0 L LO -L C() L

Ex1309,cpp program 'f>G~:§CO'):olO)oS I GC\?C\)')6~alll

II Listing 13.9: Reading and writing a stream file #include <fstream>

#include <cctype>

int main() {

char* fname = "test. txt"; I I Read the file into an array,

ifstream infile(fname, ios::in I ios::out I ios::binary);

Standard c++ Library

This is a test TH IS IS A TEST

ostream outfile(infile.rdbufO); char ch[lOO];

int i = 0;

/ / Write the array from the file while (linfile.eof'() && i < sizeof ch) infile.get(ch[i++ J);

/ / Write the array to the file outfile.seekp(O, ios: :end); outfile « I\\r\n";

for (int j = 0; j < i-l; j++)

outfile. put( static_cast<char> (toupper( ch [jJ)));

return 0;

}

JI Ex1309.cpp program d2GcvC\Y)6~q8 1D1D~8:'f-l test.txt ~8d2 fname ~ point C\(8~8: an:olO)oSll G£')oS~:8884o)oS read/write access d3 define C\)8Go:olO)oSll while (!infile.eof( )

T tfL 0 L L

&& i < sizeof ch) infile.get(ch[i++ J); statement <JY) test.txt 8800m information d3 ch[ ]

L L

, c c ~ ,,. d t 0 I tt r,:c c h C 'I C ~ C

array ro(j)O)ro~GO:tf: 848 a a G060C uppercase e er G06t:::JIDG84'JCGtf')c:OIO)()')1I tf:GW1qc

test.txt ~8oom information 'f-l updated data d2;;ooSGq:ro~olO)oSll Ex1309.cpp program d3 run c3oSQ8 output a: screen ('y')~GoT ol~:11 test. txt a8(,Y.)o information "O)b d3:G£O)')d3Go)

L L -L J n, L J L L T L 0°

qolc3~~oSll y (O? @) d26~oll1

Standard c++ Library

Opening and Closing a Stream File

011 c++ program 0)6y,? ifstream d?,~O(oS ofstream object G06Q 'f')~~~o1o~ declare

C 0 'I c ,e 0 d I C 0 C C bi t 0 ~ 'I C bi ct' C c, 0 C 0

0(00?,90'O)w" 8'dG<=,? ec are <=,?o<=,?m9c 0 jec m§1G'ftfll GIGO~O;> 0 ~e <f.~m~wO? <t'CGOY.).~~

G:::D::n:Go111 880)6;;);;)~~oS::DoSGO:;;)18Q8 open( ) member function d58'd~:~IQ~o111 88~8'd~oS

Il 0 L L L To 0 '" -1 1. l tj -lJ L To

8Cl~oS§oS;;)J898GOY.). close( ) member function Q8'd~:~l901~oSll Ex3010.cpp program '?

outfile J3ci) ofstream object 0)6;;)d5 declare C\J8~: testl.txt I test2.txt 88 (2) ;;)~ 0)6;;);;)18:

LO LL Lt1 L LTo LI.I

C c@ C C • 0 c~ 'I C § c 'I

~m::DW :GO)') 8'dC\JOC\JO ::D':lwm coc CO'JW 100W I GC\JC\)') ~)O III

o 0 LLOLL 0 U

II Listing 13.10: The open( ) and close( ) member functions #include <fstream>

#include <cctype>

int main() {

I I An ofstream object without a file. ofstream outfile;

cout « "Creating the testl.txt file ... \n"; outfile.open("testl.txt");

outfile < < "This is TEST1";

outfile.close( );

cout « "Creating the test2.txt file ... \n"; outfile.open("test2.txt");

outfile « "This is TEST2";

outfile.close( );

return 0;

}

Standard C++ Library

::J test l EJ@Jt;j
T'his is TESTl ~ :
~test2""'" ,,, J ~.~~ ''''''''ga]fj
T'his is TEST2 "
.
'.'
. " jll

Ex1310.cpp program d5 run 03d;Qt output m screen g)~G()T ()1::n:n prompt GO)O

L L-l J IL 0

test 1. txt ~ test2.txt I1tGo)g) ~~03 write C\)8~:~SGsO)")d5Go) Qg)()111 0 (0:::>0 00) d5~:::>S()111

To L 0 J L L L lj L1 T L 0° -lJ L \" L~C!..

Objects 1/0

9 C' '1 C' 0 bt t a a C' C' a 't C' C' "g a C'

80)Q)~IGs')m;;o: GC\)C\)')g)m 0 ~ec GO)m <PCGo)g)::nWC\) wn e C\)()~W I ~G<PCGO)mGS

T 1. 0 J 0 L L OJ L L LoT

C' 0hC' C' "0,, C' a ~C' '1 C' E 3011 I h' t

::nwC\(t1'f<PO)~C\)~O?'f~:GD60(GO;>C\)')~[jQ)()lo)WII X .cpp program ()'l) c ass IS ory

b· ct C'" C' C'" d t a h' t d t a C' 't C' C'B d' I §o c

O ~e O)Q)~S()O)8)mO) a a GO)m IS ory. a occo wn e ~QCc\)() : screen g) ISP ay ~c:

L To 0 0 L L J -1 L J L

011

Standard C++ Library

II Listing 13.11: liD with multiple objects #include <fstream>

class history {

char name[30]; char degree[30];

int age;

public:

void getData() {

cin > > name > > age > > degree;

}

void showData() {

cout < < "\nName =" < < name < < endl

« "Age =" «age « endl

< < "Degree =" < < degree < < endl;

}

};

int main() {

char ch;

history person; fstream file;

file.open("history.dat", ios: .app] ios: .out] ios: :in); do{

person.getData( );

file.write((char*) &person, sizeof person); cout « "\nEnter another person (Yin)? "; cin » ch;

} while (ch == 'y');

file.seekg(O);

Standard c++ Library

file.read((char*) &person, sizeof person); while (!file.eof( ))

{

cout < < "\n Person : "; person.showData( );

file.read((char*) &person, sizeof person);

}

return 0;

Standard c++ Library

'2J

}

J"

Ex1311.cpp program d5 run cSoS~: data Gmd5 historv.dat a8oolf.> write C\)8~8:~:

L L t1 0 L I I' L J L L L:1

III Quincy 99

?II Ex3012.cpp program (J)')~q8 history.dat ~8cO'f-'0lo? person data GD6m o;sJ~G~~

° c, C c,· I' t' ° oCr? d' I ChOC ~c ') C

::D~CO?C)(0)0GQ)')mq. inrorma Ion O(C\(m~t1: screen 'f-' ISP ay C\(0t1yC:O)')lj00IOJOOIl

II Listing 13.12: Seeking a particular object in a file #include <fstream>

class history
{
char name[30];
char degree[30];
int age; public:

void showData() {

cout < < "Name =" < < name < < endl

« "Age = "« age « endl

< < "Degree =" < < degree < < endl;

}

};

int main() {

history person; ifstream infile;

infile.open("history.dat") ; infile.seekg(O, ios: :end);

int endpos = infile.tellg( );

int n = endpos/sizeof (history);

cout « "\nThere are" « n « " persons in file"; cout « "\nEnter person number: ";

cin » n;

Standard C++ Library

Standard c++ Library

?9

int pos = (n-l)*sizeof (history);

infile.seekg(pos);

infile.read((char*) &person, sizeof person); person.showData( );

cout « endl;

return 0;

}

911 ~ (O? O?) UY)~98 Ex1312.cpp program cPr run d?oSl§: person number : 2 cPr

history.dat g8oog')g)~8:~:Go:n information d3 screen g') display C\)8h~8:CXY.):o:n()1011

L J j'- L t1 a L J L L::f L

sequence ~C1Y) Standard Template Library (STL) ~0108o? container class template O')S~r;;:S~: 8'd~b3'dl!Y):O')d5m obiect 8'dGQ8'dO')J)O')S~d3 linear organization 00£ ::DeC(,¥.)

L l:j t1 iJL IL c..:. II J -L 0 L L L To It!' J

t c '1 C •• , c c , '1'

sore 0(0QY.):010')0)1I eo('¥') array «0<j!::D0')<y0')QY.):0? name Go;?oy') sequences 01011 sequence

type GD6o? ( 0) vector (j) deque (?) list (9) stack (J) queue ~ (G) priority_queue type ~B: (6) ~l:ro8~QY.):010')oSll G0)')8:B 1 "6J~GroSa?, vector class type oo0B: sequence GD6o?O')Sy~8:

rr;. c c

GC\?(\)')e1~ E>[G8'd,)c II

0<;.0 The vector Class Template

011

vector class template coxzo array element GO')d3 random access (\)8Go:~8m8'd0~:

o OL L L II 0

o '1 C ,. I t or;;: c c ~ ceo c ct c~c '1 c

~10')0)1I sequence E1,8'dar:G,,9='~ e emen GD6O?[j~~O) 1 [jj_O')~O)arE>[c ve or 0y')8'dq?"r:J,,010')0)1I

-, 0 C C eeoc C 0 C C C or;::;:::,... '1 E 1401

sequence E1,8'd0 ~~urO') 8'd(\)o)G,,9='Go;?~ 8'dO(oO(Oyc:~O)arE>[c "~:"~:«e1J~OIIl X .cpp

Program OY.) vector obiect O')S~d3 create (\)8~: content GO')d3 screen (,¥.) display (\)8~~8:m

J LL Ltf OL J Ll:jL II

Sequences

/ / create a to-element vector object,

/ / of which all the elements are initialized to 15 vector <int> intVec(10, 15);

/ / Listing 14.1: Creating a simple vector #include <iostream>

#include <vector>

int main() {

/ / initialize vector element count to zero int kount = 0;

/ / iterator object iter points to an element stored in the container vector <int>: :iterator iter;

/ / display the content of the vector object cout « endl;

for (iter= intVec.begin( ); iter != intVec.end( ); iter++)

cout « "\tElement #" « kount++ « ": " « *iter « endl;

return 0;

}

JII Ex1401.cpp program o?GC\?C\)')§~goS~qt IDID@Jbp tu-element o1oto? intVec ~o? vector object mS@d) create ru6~: element d)t:Q m~a:d) 15 r,;:SGant initialize ru6cxn:01moSll

l. l L t1 L -Lo T L L l:j L

program mGt iterator object §So? iter o?8'd~:§l[§: vector object m element G06o?mSy@Jt:

access ru6~:o1moSll mSmoSGCfY) iterator ~CfY) container oom element mS@@lt:d) point

LOll L L'-I l

C\(6~8o? pointer mSy~ §8§~~qo1moSll for loop 00'fJ begin( ) member function a? call

G@Tc8a5CfY)£ vector object cr: first element d) point ru6G£m iterator mS@d) return ru6Go:o1

L To l L T 0 L l L

c8GgoSll d5£~:m end( ) member function d) call G@Tc8a5Qt vector Q last element d) point

o l T c.:.. Il l l -L -1-0 L

ru6m iterator d) return ru6Go:~o1ol1 0 (090 0) ~ Ex1401.cpp program d) run ~cxn:01moSll

LO L L J l J L t1

vector element an:o?:()')') 15 @J~:o§So?8'd06a5 output 'fJ 15 G060GoT Gt CfY)§So1moS II

Sequences

rIIQuincy99

Adding Elements to a Vector

:)11 G8d.ld)I?G<.llT§OY:l:o? Ex1402.cpp program <:fY) empty vector object mSy~ sequence I? new element G06d? push_back( ) member function oo~:§lB: insert ~8G():o? program mSy§S()1mo) I GC\?ro:>i§ei()111

II Listing 14.2: Adding elements to a vector #include <iostream>

#include <vector>

int main() {

I I create an empty vector object vector<char> charVec;

I I initialize vector element count to zero int kount = 0;

Sequences

Ell Quincy 99

/ / populate the sequence with the characters W through 'J' for (int j=O; j<lO; ++j)

charVec.push_back(65 + j);

vector<char>:: iterator iter; cout < < endl;

II display the content of the vector object

for (iter= charVec.begin( ); iter != charVec.end( ); iter++)

cout « "\tElement #" « kount++ « ": II « *iter « endl;

return 0;

}

JI Ex1402.cpp program o?Ga;>C\Y.)§~~oS~E>[8 00~8:'P charVec ~a? <char> type vector obiect mS~d5 create (\)6~: element Gmd5 'A' OOGS 'J' GeldS character Gmg, assign

J L L L lj 0 L T 010

(\)6Go:g')o111 push back() member function Gel::D:~od5 :Dd5~'~~o111 GelQ8a:,::D8:m data d5

L J - L L1t L L l:jle.ju, "I L 0 6 L

first element GelGS~:Da5~a501moSli display (\)6Q8(\)~: GelGoT -;n: i3~lDa5 G~ a:,:g')gGsg')o111

T T. J L -L c.:. L LO L jlo L J jl T J

:;equences

Inserting Elements anywhere in a Vector

Oil ~~O')S;:;,10')8~gJmGoy) insert( ) member function dS~::D:~l~: vector object O')S;:;,~

L l::1 J 0 L L L::1 L::1 L -Lo

sequence 't') element G06o?0loSo?G'l"9':>'f') insert ar8G():o?'l"~:o?0')8§()1~uSll Ex1403.cpp program o?GC\'C\Y)6~()111

II Listing 14.3: Inserting elements in a vector #include <iostream>

#include <vector>

int main() {

I I Create and populate the vector vector<char> charVec;

for (int j=D; j<10; ++j) charVec.push_back(65 + j);

I I Display the starting vector cout « "\n\tOriginal vector : "; vector<char>:: iterator iter;

for (iter= charVec.begin( ); iter != charVec.end( ); iter++) cout < < *iter;

cout « endl « endl;

I I Insert five Xs into the vector starting from the front vector-cchar>: :iterator start = charVec.begin( ); charVec.insert(start, 5, '*');

I I Display the result

cout < < "\tResultant vector : ";

for (iter = charVec.begin( ); iter != charVec.end( ); iter++) cout « *i;

cout < < endl;

return 0;

}

Sequences

Sequences

(flO

jll Ex1403.cpp program 'P insert( ) member function 8d~:§l~d2 8Jd5§l§~oll1

vector<char>: :iterator start = charVec.begin( ); charVec.insert(start, 5, '*');

II QUincy 99

Removing Elements from a Vector

011 G8'no)'PG(J)T[9ClY):o? Ex1404.cpp program (J)')a?9.t ABCDEFGHIJ a?o? sequence ~ Gl'oo)a?:mG<j'> element mSy~t:d2 §laS~Go:qp:o? program §SolmoSll pop_back( ) function 8d::D:~lod3 G(\)C\Y)r,:;:::~oll1

L L:1 L L 0 ~o.

II listing 14.4: Removing vector elements #include <iostream>

#include <vector>

int main() {

vector<char> charVec;

for (int j=O; j< 10; ++j) charVec.push_back(65 + j);

int size = charVec.size( ); cout « endl;

for (int k=O; k<size; ++k) {

charVec.pop_back( ); vector<char>:: iterator iter; cout « '\t';

for (iter= charVec.begin( ); iter != charVec.end( ); iter++) cout « *iter;

cout < < endl;

}

return 0;

}

JI Y (09· 9) '? Ex1404.cpp program d2 run §CXY.):ulmoSll

• Quincy 99

Sequences

vector<char>:: iterator charVec.erase(start);

start = charVec.begin( ); I I erase forward

Removing Elements Anywhere within a Vector

011 pop_back( ) member function a?08'd~:§la?qO')')()') erase( ) member function §Sol mo5lI G8'd')a5~G(9T§CO'J:o? Ex1405.cpp program ~ ABCDEFGHIJ ~o? sequence Sr. G~.~:(),)G~ element mSy~8:d2 ~a5Go:~:o? program 0111 erase( ) function 8'd~:§l0d2 GC\'C\Y.)6~0111

II Listing 14.5: Removing elements anywhere within a vector #include <iostream>

#include <vector>

int main() {

vector<char> charVec;

for (int x=O: x<10; ++x) charVec.push_back(65 + x); int size = charVec.size( );

cout < < endl;

for (int x=D; x-csize; ++x) {

vector-cchar>: :iterator iter;

cout « '\t';

for (iter= charVec.begin( ); iter! = charVec.end( ); iter++) cout < < *iter;

cout « endl;

}

return 0;

}

JII Y (09' J) ~ Ex1405.cpp program d2 run §CO'J:01mo5lI

Sequences

O"lJ

Comparing Vectors

011 Gana5cpG<JlT[90Y.>:0 Ex1406.cpp program (J)')~q8 <char> vector object (2) :room

::Y)oS~0')m~:cD£O')")<1> ~8:())8~8:m program ~SolO)oS I GC\)(\)')~~oll1

c() e:1 L L JL JCL· tj • ~Ci.

/ / Listing 14.6: Comparing vectors #include <iostream>

#include <vector>

int main() {

/ / Create two vector objects. veetor<char> charVec1;

for (int x=D; x<10; ++x)

charVec1.push_back(65 + x); veetor<char> charVec2;

for (int x=D; x<10; ++x) charVec2.push_back(66 + x);

Sequences

// Display the vectors.

cout « "\n\tVector 1: "; vector<char>: :iterator iter;

for (iter= charVec1.begin( ); iter != charVec1.end( ); iter++)

cout < < *iter; cout « endl;

cout « "\n\tVector 2: ";

for (iter= charVec2.begin( ); iter != charVec2.end( ); iter++) cout « *iter;

cout < < endl;

/1 Compare the vectors.

if (charVec1 == charVec2)

cout < < "\n \tvector1 = = vector2"; else if (charVec1 < charVec2)

cout « "\n\tvector1 < vector2";

else

cout « n\n\tvector1 > vector2"; cout « endl;

return 0;

}

JI Y (09- (5) "p Ex1406.cpp program d? run §(X)')wloooSll

II Quincy 99

Sequences

09.J Sorting a Vector of Integers

011 G87.loS<pGtoT§c::oo:o? Ex1407.cpp program em rand( ) function 8'do.?:§l~: generate

c ". t t c 0 c c:~ 0 C rt c" c

"(oc::oo:O? -crn > vec or sequence mOC1Dt:GOJO? cO)Q)2LJ:,,(m so 0?OGo:O? program ooQ)y

eSo1OOd)1I sort( ) function 8'do.?:§l~a? G(\)(:\)')6~oll1

II Listing 14.7: Sorting a vector of integers #include <iostream>

#include <iomanip>

#include <vector>

#include <algorithm>

int main() {

int n; int i;

cout « "\n\tHow many integers? "; cin » n;

vector<int> intVec;

for (i=O; i < n; i++) intVec.insert(intVec.end( ), rand( ));

cout < < "\n\t--- Unsorted ---\n"; vector<int>: :iterator iter;

int k=O;

for (iter = intVec.begin( ); iter != intVec.end( ); iter++) {

if «(k%4) == 0) cout« endl; k++;

cout « setw(8) « *iter;

}

Sequences

cout « "\n\n\t--- Sorted ---\n"; sort(intVec.begin( ), intVec.end( »;

for (iter = intVec.begin( ); iter! = intVec.end( ); iter++) {

if «k%4) == 0) cout « endl; k++;

cout < < setw(8) < < *iter;

}

cout « endl; return 0;

}

JI Ex1407.cpp program d? run o?a5~: How many integers? d? prompt GoT (\)')o?oo~1~ 12 d?~a5co~Go:q8 OCOg omf: (12) a?:d? random generate C\(8~: CoS0e~:d2a5 OO:l)S§f~Go: aY.l:0Y.ld? G06.qo1c{3~goSll ~ (09· '2) d?§~o111

_Quincy 99


Hou integers? 12 II
many •
llns o r-t e d ---
41 18467 (.334 2(.5J<1J<1
1 'J 1 f.. oJ 15724 114?N :-9]~H
2£,</(,2 :!4464 5?14~ ~H145
!''Jl'tt:rI
·11 L..?145 h 1].1 114'/R
15'124 1 ~4f, 7 1,/1(, '/ 24·1(.4
2(.51414 '2.(.'/(,2 ~H145 ?·n~.H
An I, kt;y to r-e t ur-n t .. 1~1I inc y ... Sequences

09.\> The deque Class Template

:)11 deque class template ox: vector OJS:r~ ~~~olol1 deque sequence q,~Q)~~~:G~q:>'f-'

I t - o~ c c ~ ceo C t co~c '1 Cit 0 d

e emen GOJo(t::'l~~().) I t::'llOJ~().)~qc vec or com«l:l~OIOJ()')1I array e emen GOJO( ran om

C 0 c" C 0 '1 C to" . 0 d . II . C 0 C '1 C

access C\(OGO:~CO?~~~:~OIOJ()')1I vec or C\(O array size 0( vnarruca y resize C\(OGO:~COIOJ()')II

Ex1408.cpp program <:fY)~q8 deque object OJS:rd? create C\(8[9: content GOJd? screen 'f-' display (\)8~~8:aJ program OJS~oll1 0 (:)9' ~) if.) program ciS run ~CO'):olOJoSll

L til 0 L l J L. t1

II Listing 14.8: Creating a simple deque #include <Iostrearn>

#include <deque>

int main() {

deque<int> intDeq(5, 1234); int kount = 0;

deque-clnt>: :iterator iter; cout < < endl;

for (iter = intDeq.begin( ); iter != intDeq.end( ); iter++) cout « "\tElement #" « kount++ « ": II

« *iter « endl;

return 0;

}

Ell Quincy 99

Sequences

Adding Elements to a Deque

811 GG'n~'PG~T§CO'):o? Ex1409.cpp program ()7) empty deque object ooSy~. sequence In new element GoodS push front( ) member function nd~:r,:.,rR: nd0~::D8:o) data dS last

J 0 L - L tflL::f L 0 0 L

I t 'r;;:c c· rt c, c r;;:c '1 C ~ C '1 • ( )

e emen ndGi'<f.lj0GG'nC mse O(0Go:O? program OO0Ylj00lOOOO I GO?C\Y)e:f~OIIl « 89' ~ 'P

Ex1409.cpp program d2 run §CO'):oloooSll

II Listing 14.9: Adding elements to a deque #include <iostream>

#include <deque>

int main() {

deque<char> charDeq; int kount= 0;

for (int i=O; i<5; ++i) charDeq.push_front(65 + i);

deque<char>:: iterator iter; cout « endl;

for (iter= charDeq.begin( );i ter != charDeq.end( ); iter++) cout « n\tElement #n « kount++ « ": n

« *iter « endl;

return 0;

}

Sequences

Inserting Elements anywhere in a Deque

011 8'd~O)S~lO)Ehlf.)mGoy) insert( ) member function ciS8'd:D:hl~: deque object O)S~~

L r:1J Q L Lt1t1 L-I.o

II Listing 14.10: Inserting elements anywhere within a deque #include <iostream>

#include <deque>

int main() {

deque<char> charDeq;

for (int x=D; x-c 10; ++x) charDeq.push_front(65 + x):

cout « "\n\tOriginal deque : "; deque-cchar>: :iterator iter;

for (iter= charDeq.begin( ); iter != charDeq.end( ); iter++) cout < < *iter;

cout < < endl;

deque-cchar>: :iterator start = charDeq.beginO; charDeq.insert(start, 5, '$');

cout « "\n\tResultant deque: ";

for (iter= charDeq.begin( ); iter != charDeq.end( ); iter++) cout < < *iter;

cout < < endl; return 0;

}

Ex1410.cpp program ciS run c3d)(doS~QE 0 (09' 00) If.)h(XY):cn8'ddSE: hEQlf.)()ll1

L L L -1 L J t1 0 l L:1 -lJ

Sequences

:)11 GG'nd)':PGtDT]9cm:0 Ex1409.cpp program <JY) empty deque object ooSyq. sequence g) new element GoodS push front( ) member function G'd::D:~l~: G'd0:;o:::n8:m data dS la~

J 0 L - L t1l:1 L 0 0 L

Adding Elements to a Deque

I t 'r,::c c· rt c, C r,::c '"l C h=: C '"l • ( )

e em en G'dGff.lj'0GG'nC inse O(OGO:O: program 000Ylj'00100()') I GO;>C\Y)~2:t0'" Y. :)9' e r.p

Ex1409.cpp program d? run Bcm:oloooSll

II Listing 14.9: Adding elements to a deque #indude <iostream>

#indude <deque>

int main() {

deque<char> charDeq; int kount= 0;

for (int i=O; i<5; ++i) charDeq.push_front(65 + i);

deque<char>:: iterator iter; cout « endl;

for (iter= charDeq.begin( );i ter != charDeq.end( ); iter++) cout « "\tElement #" « kount++ « ": II

« *iter « endl;

return 0;

}

Sequences

Inserting Elements anywhere in a Deque

::>1 8'daO)Sal0)8r:~mGO)') insert( ) member function d58'do):r:l~: deque object O)SaQ

L r:1J • L ltfr:1 L-I.o

sequence "p element GOJa?E3lci3o?G1'9?"P insert o.c8G():o?1'~:a? 0)8§"P()1~uSll Ex1410.cpp

,0 § cn program ~GQ:CO'):0)8Q)')m GC\)C\)') ~()III

J "I • C G) l a Ci.

II Listing 14.10: Inserting elements anywhere within a deque #include <iostream>

#include <deque>

int main() {

deque<char> charDeq;

for (int x=O; x-c 10; ++x) charDeq.push_front(65 + x);

cout « "\n\tOriginal deque : "; deque<char>:: iterator iter;

for (iter= charDeq.begin( ); iter != charDeq.end( ); iter++) cout < < *iter;

cout « endl;

deque<char>::iterator start = charDeq.beginO; charDeq.insert(start, 5, '$');

cout « "\n\tResultant deque: ";

for (iter= charDeq.begin( ); iter != charDeq.end( ); iter++) cout < < *iter;

cout < < endl; return 0;

}

Sequences

> ,~- \~"V

rIIQuincy99 ...

Removing Elements from a Deque

011 Gon05'PG(J)T§cxn:a? Ex1411.cpp program <.JY)~E>[8 ONMLKJIHG ~a? sequence q, element GOJo? push_front( ) function o?8'd~:§l[9: create or8[9:GOO1 G,yo05~:mG'l' element mSy~J8:o? §laS~Go:~:a? program §SolmoSll pop_back( ) function 8'd~:§l~O? G0?C\Y.)§~oll1

/ / Listing 14.11: Removing elements from a deque #include <iostream>

#include <deque>

int main() {

deque<char> charDeq;

for (int x=O: x< 10; ++x) charDeq.push_front(70 + x);

int size = charDeq.sizeO; cout < < endl;

for (int x=O: x<size; ++x) {

charDeq.pop_back( );

Sequences

cout « '\t'; deque-cchar>: :iterator iter;

for (iter= charDeq.beginO; iter != charpeq.endt): iter++) cout « *iter;

cout « endl;

}

return 0;

}

Ex1411.cpp program d? ~ (09· 00) '<fJ run BCO'):ola:>oS I GCI?(\Y.)6~oll1

rIt.Quincy99

Removing Elements Anywhere within a Deque

.

push_front( ) ~. erase( ) member function G06d? G'd~:Bll9: deque object d? create

C\(8~oS I element G06d?B~~oS~oSa?q8 Ex1412.cpp program G'do?8:Gq:a?,qola:>oSll ~ (09' oj) '<fJ program d? run BCO'):ola:>oS I G~(\Y.)§~oll1

Sequences

II Listing 14.12: Removing elements anywhere within a deque #include <iostream>

#include <deque>

deque<char> charDeq;

int main() {

for (int x=D; x<5; ++x) charDeq.push_front(65 + x);

int size = charDeq.size( ); cout < < endl;

for (int x=O; x-csize: ++x) {

deque<char>::iterator start = charDeq.beginO; charDeq.erase(start);

cout < < '\t'; deque-cchar>: :iterator iter;

for (iter= charDeq.begin( ); iter != charDeq.end( ); iter++) cout < < *iter;

cout « endl;

}

return 0;

}

Sequences

@J

Comparing Deques

G8d')d),?G(J)T§(X)'):o? Ex1413.cpp program,? <char> vector object (2) yo? XloSq(_OO ?::ro;£OY.) g8:0)2c~(X)'):olO)oSll 6 (:::leo :::l8) If.) program d5 run ~(X)'):olO)oS I G(\)(\)')r;::;::{;oll1

-.; L jL J L:f L 7 "\ J L Cj 0 t..::.j C.i..

II Listing 14.13: Comparing deques #include <iostream>

#include <deque>

int main() {

deque-cchar> charDeq1;

for (int x=O: x<10; ++x) charDeq1.push_front(70 + x);

deque<char> charDeq2;

for (int x=O: x<10; ++x) charDeq2.push_front(65 + x):

cout « "\n\tDeque 1: "; deque-cchar>: :iterator iter;

for (iter= charDeq1.begin( ); iter != charDeq1.end( ); iter++)

cout < < *iter; cout « endl;

cout « "\n\tDeque 2: ";

for (iter = charDeq2.begin( ); iter! = charDeq2.end( ); iter++) cout < < *iter;

cout « endl;

if (charDeq1 == charDeq2)

cout « "\n\tdeque1 == deque2"; else if (charDeq1 < charDeq2)

cout < < "\n\tdeque1 < deque2"; else if (charDeq1 > charDeq2)

cout « "\n\tdeque1 > deque2"; cout « endl;

return 0;

}

Sequences

c,' • • • •
Deque 1: OHMLKJIHGF II,
-
J'lP.que 2: JI HGFEJoCRA
d"'jut:l > dt;quc2
"In II ke " t .. I'" t ur-n t .. IJuincy ..• 0<;.<; The list Class Template

G8'ir)(r5'PG~T§CXY.):o? Ex1414.cpp program <:fY) rand( ) function 8<l~:§l~: generate (\)0CXY.):OO <int> list sequence mom~:Gmd5 co5<D5~:cSaS sort (\)0';;0:00 program mSe>G;:Sol

L • T 0 L c~ l L· Llj

mo5lI sort( ) function 8<l~:§l~O? GO?C\)')§~oll1 ~ (09' 09) 'P program o? run §CXY.):olmo5lI

II Listing 14.14: Creating a single list #include <iostream>

#include <list>

int main() {

list-clnt> intList(S, 123); int kount = 0; list<int>::iterator iter; cout < < endl;

for (iter= intList.beginO; iter != intList.endO; iter++) cout « "\tElement #" « kount++ « ": " « *iter « endl;

return 0;

}

Sequences

@9

Adding Elements to a List

G8'n05':PG(J)Ti3c:m:o? Ex1415.cpp program c.:rY) empty list object cnSyq. sequence fJ new element Go;sq push_front( ) member function 8d~:Bl~: insert Clj?OGo:o? program cnSy§So1cnoS I GC9(\)')§~o1n ~ (09. oJ) ':P program q run Bc:m:01cnoSn

II Listing 14.15: Adding elements to a list #include <iostream>

#include <list>

int main() {

list<char> charList; int kount = 0;

for (int i=O: i<7; ++i) list<char>: : ite ra tor iter; cout < < endl;

for (iter = charList.begin( ); iter! = charList.end( ); iter++)

cout « n\tElement #n « kount++ « ": n « *iter « endl; return 0;

charList.push_front(65 + 0;

}

Sequences

Inserting Elements anywhere in a List

011 8tldmSdlm8~bl'x1)GO')') insert( ) member function d58tl::D:~l~: list object mSdQ

L l:jJ • L ltftf Lt-

sequence 'fJ blank element GOJo?[gla5o?G,,~'fJ insert C\(8G():o?,,~:o?m8§()lbloSll Ex1416.cpp

program o?GC\~)(\)')§~()ll1

II Listing 14.16: Inserting elements anywhere within a list #include <iostream>

#include <list>

int main() {

list<char> charList;

for (int x=O; x<10; ++x) charList.push_front(65 + x);

cout « "\n\tOriginallist : "; list<char>:: iterator iter;

for (iter= charList.begin( ); iter! = charList.end( ); iter++) cout < < *iter;

Sequences

cout < < endl;

list<char>::iterator start = charList.beginO; charListinsert( ++start, 5, ' ');

cout « "\n\tResultant list: ";

for (iter= charList.begin( ); iter! = charList.end( ); iter++) cout < < *iter;

cout « endl;

return 0;

}

JII ~ (09' 0(5) !fJ Ex1416.cpp program o? run §ro:>wlmoSll

rIIQuincy99

Removing Elements from a List

011 Ex1417cpp program ()Y.)~98 ABCDEFG ~o? sequence rom elements 'E' ~ 'B' o?,O? §l05;;lJGO:o.p:o? program §SolmoSll push_back( ) function ~ remove( ) function G068<lo.?:Bl~o? GC\?(\)')6~oll1

Sequences

II Listing 14.17: Removing elements from a list #include <iostream>

#include <list>

int main() {

list<char> charList;

for (int x=O; x<7; ++x) charList.push_back(65 + x):

cout « "\n\tOriginallist : "; list<char>::iterator iter;

for (iter= charList.begin( ); iter != charList.end( ); iter++) cout < < *iter;

cout « endl;

charList. remove('E'); charList.remove(,B');

cout « "\n\tResultant list: ";

for (iter= charList.begin( ); iter! = charList.end( ); iter++) cout < < *iter;

cout « endl;

return 0;

}

JII ~ (09' O?) IcfJ Ex1417.cpp program d2 run BCXY.l:ola:>J)1I

III Quincy 99

Sequences

Removing Elements Anywhere within a List

:>1 GG'"nch'PGlOT§cxn:0 Ex1418.cpp program 'P JIHGFEDCBA ~0 sequence q.mGf

element 'I' o?~chGo:0 program §SolmoSll erase( ) function 8'd~:§l~O? GO?C\YJ6~oll1

II Listing 14.18: Removing elements anywhere within a list #include <iostream>

#include <list>

int main() {

list<char> charList;

for (int x=D; x-c 10; ++x) charList.push_front(65 + x):

list-cchar>': iterator iter; cout « '\t';

for (iter= charList.begin( ); iter! = charList.end( ); iter++) cout < < *iter;

cout < < endl;

list<char>::iterator start = charList.beginO; charList.erase( ++start);

cout « '\t';

for (iter= charList.begin( ); iter! = charList.end( ); iter++) cout < < *iter;

cout < < endl; return 0;

}

II Ex1418.cpp program dS run c8chldoS~Q8 0 (::)C";. 80) ld')~cxn:m8'dd58: ~8Qld')oll1

L l L. "I L 7 J L:1 0 L 1.::1 "I J

Sequences

Comparing Lists

011 G8'd')d)g)G(9~CO'):m Ex1419.cpp program g) <char> list object (2) ;;l ~uS:::Dm~:cD

J YI L:1 0 J L IL ~

o 0 0 C c§ '1 C § C '1

cocxx» IlIc:w2 CO'):OI(),)W I GCI)C\Y.) ~JOIII

L l JL J 0 Ci.

Sequences

000

II Listing 14.19: Comparing lists #include <iostream>

#include <list>

int main() {

list<char> charList1;

for (int x=O; x< 10; ++x) charList1.push_front(65 + x);

list <char> charList2;

for (int x=O; x<10; ++x) charList2.push_front(66 + x):

cout « "\n\tlist 1: "; list-cchar>: :iterator iter;