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

Pao

21

S a m s T e a c h Y o u rs e lf

C++

in One Hour a Day

SEVENTH EDITION

Siddhartha Rao

SAMS
800 East 96th Street, Indianapolis, Indiana 46240

C++

21

C++

21

2013

I.

19
23

1.

25

2. C++

35

3. ,

47

4.

71

5. ,

89

113

7.

145

8.

167

. -
C++

201

9.

203

247

11.

277

12.

301

13.

339

14.

351

ill. (STL)

15.

16. STL

375

377
389

17. STL

405

18. STL

423

19. STL

443

20. STL

461

iv. STL

483

21.

485

22. - ++11

499

23. STL

513

24. :

545

25. STL

561

V. C++

571

26.

573

27.

587

28.

607

29.

621

VI.

C++

831

633
639
641

643

. ASCII

681

685

19
19
20
21
21

I.

23

1.
C++

C++
C++
, C++?
C++



C++
C++

C++11

25
26
26
26
26
27
27
27
28
28
29
30
31
31
32
32
33
33
33

2. C++
Hello World
#in c lu d e
m ain ()


C++
C++
s t d :: c i n s t d :: c o u t

35
36
36
37
38
38
40
40
43
45
45
45
45
46

. ,



47
48
48
48
50



, C++
bool
char

short, int, long long long
unsigned short, unsigned int,
unsigned long unsigned long long
float double
sizeof
typedef


const

#def ine

,

4.




,






C++: std::string

5. ,

,

(=)
1- -
(+), (-), (*), (/) (%)
(++) ( )

50
52
54
54
55
55
56
56
57
57
61
61
62
62
64
66
66
67
68
68
70
70
70
71
72
72
73
74
75
76
78
79
79
81
82
85
86
87
87
88
88
89
90
91
91
91
91
91
93
93


(==) (! =)

NOT, AND, OR XOR
C++ NOT (!), AND (&&) OR ( I I)
NOT (-), AND (&), OR ( | ) XOR ( A)
( ) ( )

s i z e o f ,

9
96
96
98
99
102
104
105
107
108
110
110
111
111
111

6.
i f . . . e l s e
i f . . . e l s e

i f
s w itc h - c a s e
(? :)

g o to
w h ile
do. . .w h ile
f o r
c o n tin u e b r e a k
, , ..



113
114
115
117
118
122
124
126
126
128
129
131
134
135
135
138
139
141
142
142
143
143
143

7.







,
r e t u r n



145
146
147
148
148
148
150
151
152
154
155
155
157
158

10

160
161
163
164
164
165
165
165

8.


(&)

(*)
s i z e o f () ?

new d e l e t e

(++ -)
c o n s t





( )

new


c o n s t

167
168
168
169
170
172
174
175
176
179
182
183
184
186
187
187
188
189
190
193
194
195
195
197
197
198
198
199

II. -
C++

201

9.



( .)
(->)
p u b l i c p r i v a t e
p r i v a t e

203
204
204
205
205
206
208
209
211
211
212

11








,
,
,
t h i s


214
216
217
219
220
220
221
223
223
226
230
232
232
233
235
237
238
240
241
243
243
244
- 244
245

.


C++
p r o t e c t e d

,

.

,





247
248
248
250
252
254
256
258
259
261
263
263
265
267
270
271
273
274
274
274
275

11.


,

.

277
278
278
279
281
285
288

12

291
295
298
298
299
299
300

12.
301
C++
302

303

303

303

306
(*)
(->)
308

312

312
( + ) ( - )
313
(+=) (-=) 315
(==) (! =)
317
<, >, <= >=
320
(=)
322
([ ])
325
()
328
,
335

336

336

337

337

337

13.

C++
C++
s t a t i c c a s t
d y n a m ic _ c a st

r e i n t e r p r e t c a s t
c o n s t _ c a s t
C++

339
340
340
341
341

14.

# d e f in e

# d e f in e
?

351
352
352
354
355
357

342
345
346
347
349
349
349
349
350


a s s e r t










I d s P a i r

C++

13
358
359
360
361
361
362
364
364
365
366
366
367
368
371
371
372
372
372
373

ill. (STL)

375

15.
STL



STL
STL

STL

377
378
378
379
380
382
383
384
386
386
387
387
387

16. STL

STL
STL
s t d : : s t r i n g


STL


STL

389
390
391
391
393
395
396
398
400
401
402
. 403
403
403
403
404

14

17. STL
s t d : : v e c t o r


p u sh _ b a ck ()
i n s e r t ()




deque STL

405
406
406
406
408
409
412
413
414
416
418
420
421
421
421
422

18. STL
s t d : : 1 i s t

s t d : : 1 i s t




l i s t : : r e v e r s e ()

,

423
424
424
424
426
428
430
431
432
433
435
440
441
441
441
442

19. STL
, STL
s e t m u l t i s e t STL
s t d : : s e t



20. STL
STL
s t d : :map s t d : : m u ltim ap STL
s t d : :map s t d : : m u ltim a p
STL
STL

443
444
444
444
447
449
450
455
458
459
459
459
460
461
462
463
463
465
467

15

STL
STL

-
- ++11: u n ordered _ m ap u n o rd e re d _ m u ltim a p

470
470
472
476
477
480
481
481
482
482

IV. STL

483

21.





485
486
486
486
490
492
495
497
497
497
498
498

22. - ++11
-
-
-
-
- [. . . ]
-
-
-

499
500
500
501
502
504
505
507
508
511
511
512
512
512

23. STL
STL
STL


STL




s t d : : g e n e r a te ()
,

513
514
514
514
515
517
517
519
521
523

525

16

for each ()

526

std::transform()

528
531
534
535
538
540
542
542
543
543
544

24. :

stack STL

- stack
push () pop ()
queue STL

- queue

push () pop ()
priority_queue STL

- priority_queue

push () pop ()

25. STL
bitset
std::bitset
std::bitset
, std: :bitset
std: : bitset
vector<bool>
vector<bool>
vector<bool>

545
546
546
546
547
547
548
549
550
550
552
552
554
554
555
556
558
558
558
559
559
561
562
562
563
563
564
566
567
567
569
569
569
569
570

17

V. C++

571

26.

()








573
574
574
574
575
576
577
578
579
580
580
584
584
584
585
585
585

27.

C++
s t d : : c o u t


s t d : : c o u t
s t d : : c i n
s t d : : c i n
s t d : : c i n : : g e t ( )
s t d : : c i n s t d : : s t r i n g
s t d : : f s tr e a m
open () c l o s e ()
open ()

open ()

s t d : : s t r i n g s t r e a m

587
588
588
590
590

28.


t r y c a tc h
c a tc h ( . . . )

th ro w

s t d : : e x c e p tio n
, s t d : : e x c e p tio n

592
593
593
594
595
597
597
598
599
600
602
604
604
604
605
605
607
608
608
608
609
610
612
613
615
616

18

29.






,
C++
C++

621
622
623
623
624
625
626
626
627
628
628
629
629
629
630
630

VI.

631

633
634
634
635
635
635
635
636
636
636
637
637

618
618
619
619
619

. C++

639

641

643

. ASCII
ASCII

681
682

685


2011 C++. ++11
,
. ++11
. ,
-
. ++11, .

, Microsoft Visual C++ 2010
C++ C++ GNU 4.6,
++11.


C++.
, , .
C++ , .
, C++,
, ++11. ,
, C++11.



. .
I, , C++.
,
C++, , .
II, -
C++, . , C++
- ,
, , . 9,
, ++11, ,
12, ,
.
, . 14,
,
C++.

20

III, (ST L ),
C++, STL string . ,
std::string
.
STL, .

IV, STL, . , ,
, , .
, + + 11 auto
. 22, - C + + ,
,
STL.

V, C + + , ,
,
C++,
.
++11.

,
, .

.
, .
, , , U R L -
.

, ,
.

.
,
, : BINDSIZE= (
) * ( ).

: Menu

Option ( ).

.
. .
. ,
,
.

. ,
,
.

,
.

21

++11____________________________________________
C++11. ,
.
!


, .

C++.


, , - Sams.


, , .
, ,
. ,
.
.
-, . ,
, ,
, .
, ,
e-mail.
.
:
E-mail:
info0williamspublishing.com
WWW:

http: //www.williamspublishing.com

:
: 127055, , . , . 43, 1
: 03150, , / 152

1.
2. C++
3. ,
4.
5. ,
6.
7.
8.



C++ 21 \ ,

C++.
.

C++
.

,
C++.

++11.

26

1.

C++
,
. C++ ,
. C++,
ISO Standards Committee 2011 ++11.


1979 , C++
. ,
. C++, , -,
, , ,
. C++
. ( .)
, .
C++ .
,
, ,
, .

C++
C++ , ..
, ,
. C++
, ,
,

.
* , Java,
.NET, C++ .
,
, ,
. ,
,
C++. , - C++,
HTML, Java .NET,
.

C++
C++ ,
- ,
.
. ,
.

C++

27

1998 C++
ISO Committee ISO/IEC 14882:1998.
, 2003 , ISO/IEC 14882:200).
C++ 2011 . ++11
(ISO/IEC 14882:2011)
, - .

++0.
, 2008 2009 ,
. , 2011
++11.
, ++11 C++ .

, C++?
, ,
,
C++. , ,
, -, ( ),
, ,
, C++.

C++
(Notepad) v i ,
.
(executable) ,
, .


C++ ,
.
C++ .
1. ( ) C++, .
2. , C++,
(object file).
3. , ,
( . Windows, ).
, ,
, , , . (compilation)
, C++,
. , , .
(compiler) ,

28

1.

. . obj ,
.
(linker).
,
, .


,
, .
, ( C++),
, .
, .
, ( , ),
(debugging),
,
, .



(Integrated D evelopm ent E nvironm ent IDE),
, ,
,
.


C++. - Microsoft Visual C++ Express
Windows GNU C++ Compiler ( g++) Linux.
Linux,
Eclipse C++
g++.


C++ ,
.


,
gedit,

. ,

, C++

C++

29

C++
, ,
C++, Hello
world! (, !).
Windows
IDE Microsoft Visual C++ Express, , .
1. , File1^ New1^ Project (11^
1^ ).
2. Win32 Console Application ( Win32)
Use Precompiled Header (
).
3. Hello
Hello. , 1.1.
Linux, . ,
1.1, ( Ubuntu gedit).

1:
2:
3:
4:
5:
6:
7:

Hello World ( Hello.)________________________

#include <iostream>
int main()
{
std::cout << "Hello World!"
return 0;
}

std::endl;

,
std::cout. std::endi cout ,
return

0.

, ,
. , #inciude
hash-include ( ), sharp-include ( ),
pound-include ( ), .
std::cout standard-c-out (-).

, - , , ,
. .
:, ;, ,
, !

30

1.

C++
IDE M icrosoft Visual C ++ Express,
<Ctrl+5>.
,
. .
1.
Build, .
2. ,
( Debug ).
3. , .
M icrosoft V isual C ++
, . 1.1.
i. l Hello World - Microsoft Visual C++ 20 Express
file

y ie w ' foject

>ebug

!J3

|dit

J S

\ %

A* l T *2

J oe ls
:

W indow

1 - *

jhjeip

D eb ug
:

Solution Explorer

(Global Scope)

^ 9 X

Solution '11 Hello World' (1 project}

:|include <iostream>

1.1 HeBo W orld

-iint main()

std::cout
return 0;

Hello World

External Dependencies
C M

Header Files

C M

Resource Files

std::endl;

C M

Source Files
0

11 Hello World.cpp

: ReadMe.txt

Build started: Project: 1.1 Hello World, C *


=* Build: 1 succeeded, 8 failed, 0 up-to-dafl

Solution Explorer

__
. 1.1. C++ Hello World

Microsoft Visual C++ 2010 Express


Linux g++ ,
:
++ - hello Hello.epp
g++ hello
C++ Hello . . . \ hello Linux
Hello. W indows :
Hello World!

!
!

+ + 1 1

31

* C++ ISO
,
1.1
C++. ,
,
Windows, Linux, ,
( ,
)

. , , ,
.


, , ,
, .
1.1, ,
, (
5):
hello.(6): error 2143: syntax error : missing

before 'return'

Visual C ++ :
, , ( 6),
, ,
( 2143).
, ,
, return ,
return.
,
!

,
, VBScript.
C++ .

++11
C++, , , ,
C++ 1.1 . + + 11
C++,
, .
, auto, ,
, (,

32

1.

) . - .
,
. C + +
,
C++. , ,

, ,
.
+ + 1 1, .

, , ,
C++. C++
,

.


?
.
,
. , , ,
.

,
.
. ,
, .

?
, W indows Script.
. ,
() . ,
, ; ,
,
, .


?
, ,
(runtim e error). , A ccess
V iolation W indow s,
.
;
.

33


, ,
. ,
, .
,
.


1.
2.
3.
4.

?
?
?
++11 ?

1. , ,
:
1: #include <iostream>
2: int main()
3: {
4:
int x = 8;
5:
int = 6;
6:
std::cout << std::endl;
7:
std::cout x - "
8:
std::cout std::endl;
9:
return 0;
1 0 :}

x *

x + y;

2. 1, .
? , ?
3. :
1: include <iostream>
2: int main ()
3: {
4:
std::cout << "Hello
5:
return 0;

Buggy World \n";

6: }

4. 3, ,
. ?

2 . 3626

C++
C++ , ,
.
,
, .
.

C++.

36

2. C++

Hello World
C++ ( 1, )
H e l l o W o rld .
C++.
2.1 ,
C++.
2.1. HelloWorldAnalysis.: C++__________________
1: // , iostream
2: #include <iostream>

3:
4: / / : main()
5: int main()
6:

7:
8:
9:
10:
11:
12: }

/* */
std::cout "Hello World" << std::endl;
//
return 0;

C++ : ,
#, , i n t
m a in ().
1,4, 7 10, / / /*,
. .

.

#include
, (preprocessor) ,
. (preprocessor
directive) , (#).
2 2.1 # i n c l u d e <>
( i o s t r e a m ) ,
, i o s t r e a m , ,
c o u t , 8
H e l l o W o rld . , 8,
s t d : : c o u t , ,
c o u t 2.

Hello World

37

C++
. , , ,
. , ,
FileA, FileB,
. FileA
#include:

#include "...relative path to FileB\FileB"



, . ( ) , ,
.

main()
() ,
m a in (). C++ .
, m a in () i n t . i n t
m a in ().

C++ main (),


:

int main (int argc, char* argv[])


,
main () int, -
(argument), . , ,
, , ,

program.exe /DoSomethingSpecific
/DoSomethingSpecific - ,

main ().

8, !
std::cout << "Hello World" << std::endl;

c o u t (console-out ( ) see-out (-)),


, H e l l o W o rld , c o u t ,
( s t d : : c o u t) , , ,
H e l l o W o r ld e ,
. s t d : : e n d l ,
. : (stream
insertion operator)
.
C++ ,
. ,
, , , . ,
,

38

2. C++

( c o u t, ),
( f stream , ).
27,
.

, "Hello World",
(string literal).


C++ ,
, main () , .
(OS) ,
, ,

. ,
( ) ,
. main ()
.
0 -1
. int ( )
, ,
.

C++ . ,
int int, void void s t d : :Cout

std: :cout.


s t d : :c o u t,
c o u t, , (c o u t)
(std ).
(namespaces)?
,
c o u t, .
? ,
. . ,
, .
s t d : : c o u t
co u t, s td .

39

std ( standard ())


, ,
ISO Standards Committee, , .


s t d c o u t ,
. u s in g nam espace, 2.2,
.
22 using namespace_________________________________________
1: //
2: #include <iostream>

3:
4: //
5: int main()

6: {
7:
8:
9:
10:
11:
12:
13:
14:
15: }

//
using namespace std;
/* std::cout */
cout "Hello World"
endl;
//
return 0;

8. ,
s t d , 11
t d : : c o u t s t d : : e n d l .
2.3 2.2.
, ,
.
2.3. using____________________________
1: //
2: #include <iostream>

3:
4: //
5: int main()

6: {
7:
8:
9:
10:
11:
12:
13:
14:
15: }

using std::cout;
using std::endl;
/* cout */
cout "Hello World" endl;
//
return 0;

40

2. C++

2.3 8 2.2 7 8.
u s in g nam espace s t d u s in g s t d : : c o u t ,
s td ,
s t d : :. ,
s t d : : c o u t
s td ::e n d l.

C++
1,4, 10 13 2.3 ,
. .
(comment).
. ,
( ).
/ / , . :
//

, /* * /, ,
:
/* ,
*/

,
,
, ,
.
, .

C++
C++ , . (function) ,
,
.
. , , main ().

C++

41

C++
i n t (.. ).
, , ,
. 2.4 ,
, s t d : : c o u t
.
2.4. , ,
std: :cout_______________________
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
I I
int DemoConsoleOutput();
int main()

8: {

9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:

//
DemoConsoleOutput();
return 0;
}
//
int DemoConsoleOutput()
{
cout "This is a simple string literal endl;
cout "Writing number five: " 5 << endl ;
cout "Performing division 10 / 5 = " 1 0 / 5 : endl;
cout "Pi when approximated is 22 / 7 = " 22 / 7 endl;
cout "Pi more accurately is 22 / 7 = " 22.0 / 7 endl;
return 0;
}

This is a simple string literal


Writing number five: 5
Performing division 10 / 5 = 2
Pi when approximated is 22 / 7 = 3
Pi more accurately is 22 / 7 = 3.14286

5, 10 15-25. 5
(function declaration), ,
D e m o C o n s o le O u tp u t (), i n t
( ). -
10, , ( 15-25) (function
definition), .. .

42

2. C++

c o u t .
: , Hello World
, . , 21 22,
(22 / 7), ,
22.0 7
( f l o a t C++), .
,
0. ,
.
m a in () 0. m a in ()
D e m o C o n so le O u tp u t (),
m a in ( ) , 2.5.
2.5.
1: #include <iostream>
2 : using namespace std;
3:
4: //
5: int DemoConsoleOutput()

6: {
7:
8:

9:
10:
11:

cout
cout
cout
cout
cout

"This is a simple string literal" endl;


"Writing number five: " 5 endl;
"Performing division 10 / 5 = " 10 / 5 endl;
"Pi when approximated, is 22 / 7 = " 22 / 7 endl;
"Pi more accurately is 22 / 7 = " 22.0 / 7 endl;

12:
13:
return 0;
14: }
15:
16: int main()
17: {
18:
//
return DemoConsoleOutput();
i9:
20: }

, .
. (.. )
m a in () 5, .
C++ .
m a in () . 19 DemoCon
s o l e O u t p u t ()
.

std::cin std::cout

43

, ,
,
vo id :

v o id D em oC onsoleO utput()
,
.

, ,
, , ..
, 7, .


std: :c in std: :cout

,
. ,
.
,
.
C++
.
s t d : : c o u t
( standard see-out ( -)) s t d : : c i n (
standard see-in ( -)) ( ,
). H e l l o W o rld 2.1
c o u t :
8:

std::cout << "Hello World" << std::endl;

c o u t (
), " H e llo W o rld "
s t d : : e n d l ( standard end
line ( -)).
c i n , ,
:
std::cin

, c i n
( ) ,
. , ,
, :
std::cin

2;

, c i n ,
, 2.6.

44

2. C++

2.6. c i n c o u t

________________________
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <iostream>
#include <string>
using namespace std;
int main()
{

//
int InputNumber;
cout

"Enter an integer:

";

11:

12:
13:
14:
15:
16:
17:
18:
19:
20:

//
cin >> InputNumber;
//
cout "Enter your name: ";
string InputName;
cin
InputName;
cout

InputName

return

0;

" entered "

InputNumber

endl;

21:

22:
23: }

Enter an integer: 2011


Enter your name: Siddhartha
Siddhartha entered 2011

8 InputNumber
in t . 10 , co u t,
c in
13. , ,
, .
s t r i n g , 17 18. ,
s t r i n g main (), 2 t in c lu d e
< s tr in g > . , 20 c o u t
, S id d h a rth a e n
t e r e d 2011.
C++. ,
, .

45

C++.
, m a in (),
.
, .


#in clu d e?
, .
,
, ,
.

/ / /*?
( / / ) .
(/* ) ,
(* /).
,
. ,
; ,
.

?
. ,
I s Linux d i r Windows
. , ,
, I s / d i r \.


, ,
. ,
, .
,
.


1. I n t m a in () ?
2. ?

46

2. C++

1. : .
? ?
1: #include <iostream>
2: void main()
3: {
4:
std::Cout Is there a bug here?";

5: }

2. 1 , ,
.
3. 2.4 ,
( -) ( *).

,

(variable) ,
. (constant) ,
,
.
.

++11 auto constexpr.

48

3. ,



, ,
.


,
,
(R andom A ccess M em ory RA M ). ,
, .

, , ,
.
, ,
, , .. .
, 578-,
.



, . ,
, .
, ,
. ,
,
.
( 578), ,
,
, .
, C++,
. :
_ _;

_ _ = _ ;

,
, .

, .
, ,
. , ,
. 3.1
, , ,
.

49

3.1.
#include <iostream>
2 : using namespace std;

3:
4: int main ()

5: {
6:

cout

"This program will help you multiply two numbers"


endl;

cout "Enter the first number: ";


int FirstNumber = 0;
cin FirstNumber;

12
13

cout "Enter the second number: ";


int SecondNumber = 0;
cin SecondNumber;

14
15
16
17
18

// ,
int MultiplicationResult = FirstNumber * SecondNumber;

19

//
cout FirstNumber " x " SecondNumber;
cout " = " MultiplicationResult endl;

20

21
22

23
24

return 0;

This program will help you multiply two numbers


Enter the first number: 51
Enter the second number: 24
51 x 24 = 1224

,
. ,
. F ir s tN u m b e r S eco n d N u m b er,
9 13,
. s t d : : c i n 10 14
.
c o u t 21 .
:
9:

int FirstNumber = 0;

i n t , ,
F ir s tN u m b e r . .
, ,
, 578, C ++

50

3. ,

,
, F ir s tN u m b e r .

.
, ,

.

,
.
,
, ( +, ..). .

. , return
.



F ir s tN u m b e r , S eco n d N u m b er M u l t i p l i c a t i o n R e s u l t 3.1
( ), .
,
:
int FirstNumber = 0, SecondNumber = 0, MultiplicationResult = 0;

, C++
.

,
.

, , .
,
,
.

27, ".


(scope),
.
,

51

. ,
.
,
3.1 M ultiplyN um bers (),
( 3.2).
3.2. __________________________
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

#include <iostream>
using namespace std;
void MultiplyNumbers ()
{
cout "Enter the first number: ";
int FirstNumber = 0;
cin FirstNumber;
cout "Enter the second number: ";
int SecondNumber = 0;
cin SecondNumber;
// ,
int MultiplicationResult = FirstNumber * SecondNumber;
//
cout FirstNumber " x " SecondNumber;
cout " = " MultiplicationResult endl;
}

int main ()
{

24:
25:
26:
27:
28:
29:
30:
31:
32: }

cout

"This program will help you multiply two numbers"


endl;

// ,
MultiplyNumbers();
// cout
// cout

FirstNumber " " SecondNumber;


" = " MultiplicationResult endl;

return 0;

This program will help you multiply two numbers


Enter the f^.rst number: 51
Enter the second number: 24
51 x 24 = 1224

3.2 , 3.1, .
, M u l
t i p l y N u m b e r s ( ) , m a in (). ,
F i r s t N u m b e r S eco n d N u m b e r

52

3. ,

M u ltip ly N u m b e r s (). 28 29 m a in (),


u n d e c l a r e d i d e n t i f i e r

( ).
, F ir s tN u m b e r S eco n d N u m b er
, ,
M u ltip ly N u m b e rs (). (local variable)
. (}),
, .
, ,
.
M u ltip ly N u m b e r s ()
, m a in (),
, .
main ()
, , , , ,
MultiplyNumbers ().
main ()
, ,
,
.


, M u lt ip ly N u m b e r s () 3.2,
, ,
m a in (), M u ltip ly N u m b e r s (). 3.3
(global variable), .
3.3. _______________________________
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
//
int FirstNumber = 0;
int SecondNumber = 0;
int MultiplicationResult = 0;

8:

9: void MultiplyNumbers ()
10: {

11:
12:
13:
14:
15:
16:
17:
18:

cout "Enter the first number:


cin >> FirstNumber;
cout "Enter the second
cin >> SecondNumber;

number: ";

// ,
MultiplicationResult =FirstNumber * SecondNumber;

53

19:

20:
21:
22:
23:
24: }
25: int
26: {
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39: }

//
cout "Displaying from MultiplyNumbers(): ";
cout FirstNumber " x " SecondNumber;
cout " = " MultiplicationResult endl;
main ()
cout

"This program will help you multiply two numbers"


endl;

// ,
MultiplyNumbers();
cout

"Displayingfrom

main(): ";

// !
cout FirstNumber " " SecondNumber;
cout " = " MultiplicationResult endl;
return 0;

This program will help you multiply two numbers


Enter the first number: 51
Enter the second number: 19
Displaying from MultiplyNumbers(): 51 x 19 = 969
Displaying from main(): 51 x 19 = 969

3.3 ,
F ir s tN u m b e r , S eco n d N u m b er M u l t i p l i c a t i o n R e s u l t .
(global), 5-7,
. 22 35,
. ,
M u l t i p l i c a t i o n R e s u l t M u lt ip ly N u m b e r s (),
m a in ().


.
,
,
.
m a in ()
3.3

MultiplyNumbers().

54

3. ,

,
C++
i n t ..
. C++
, .
, !
,
!
, , . 3.1.
C++.
3.1.

Bool

true () false ()

Char

256

unsigned short in t

0 65 535
- 3 2 768 32 767
0 4 294 967 295
- 2 147 483 648 2 147 483 647
0 18 4 46 744 073 709 5 5 1 6 1 5
- 9 223 372 036 8 5 4 775 808 9 223 372 036 854 775 807
- 3 2 768 32 767
- 2 147 483 648 2 147 483 647
0 65 535
0 4 294 967 295
1 .2 -3 8 3.438
2 .2 -3 0 8 1.8308

short int
unsigned long int
long int
unsigned long long
long long
int (16 )
int (32 )
unsigned int (16 )
unsigned int (32 )
float
double

bool

C++ , t r u e f a l s e ,
C++. ,
, ,
.

:
bool AlwaysOnTop = false;

, , :

, C++

55

bool DeleteFile = (UserSelection == "yes");


// , UserSelection "yes",
//

char

c h a r .
.
char Userlnput = 1Y '; // 'Y'

, .
0 1, , .
, , ,
,
. A -Z, a-z, 0-9,
(, <DEL>) (,
)
(American Standard Code for Information Interchange), ASCII.
, ASCII, ,
Y , U s e r l n p u t , 89,
ASCII. , 89 ,
U s e r l n p u t .


(sign) . ,
, , .
1 8 . 0 I (..
). ,
1 2 8 , .. 256 .
16 2 16 ,
.. 65 536 .
,
, 0
255, 0 65 535 .
. 3.1 , u n s i g n e d s h o r t i n t ,
, 16 . ,
(. 3.1).
15

......................

11111111111111

= 65535

v----------------------v--------------------- '
16 ,

. 3.1. 16-

56

3. ,

?
, ,
(. 3.2).
(Most-Significant-Bit MSB),
(Least-Significant-Bit LSB) . MSB
, , 0
, 1 . .
15

......................

1 1 1 1 1 1 1 1 1 1 1 1 1 1

15


0
1

. 3.2. 16-

, 8
-128 127, 16 -3 2 768 32 767.
. 3.1 , s h o r t i n t (
) 16- .

short, in t, long long long


, , ,
. i n t , ,
32 .
,
.
:
short int SmallNumber = 100;
int LargerNumber = -70000;
long PossiblyLargerThanlnt = -70000;
// long c int
long long LargerThanlnt = -70000000000;

unsigned short,
unsigned in t, unsigned long unsigned long long
,
, ,
.

sizeof

57

:
unsigned short int SmallNumber = 255;
unsigned int LargerNumber = 70000;
// long c int
unsigned long PossiblyLargerThanlnt = 70000;
unsigned long long LargerThanlnt = 70000000000;

,
. , ,
int, unsigned int.
, .


, .

flo a t double
, , .
.
. , C ++
(22/7, 3,14), .
, i n t
3.1. , f l o a t , ,
:
float Pi = 3.14;

( d o u b le )
:
double MorePrecisePi = 22 / 7;


(Plain Old Data - POD).
(, , ).


s iz e o f
(size) ,
.
, C ++ s i z e o f ,
.
s i z e o f . ,
s i z e o f i n t (), 3.4.
cout << "Size of an int: " << sizeof

(int);

58

3. ,

3.4. C++
1: #include <iostream>
2:

3: int main()
4: {
5:
6:

using namespace std;


cout "Computing the size of some C++ inbuilt variable types"
endl;

7:
8:

9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

22:
23:
24: }

cout
cout
cout

cout
cout

cout
cout
cout

cout
cout
cout
cout

"Size of bool: " sizeof(bool) endl;


"Size of char: " sizeof(char) endl;
"Size of unsigned short int: " sizeof(unsigned short)
endl;
"Size of short int: " sizeof(short) endl;
"Size of unsigned long int: " sizeof(unsigned long)
endl;
"Size of long: " sizeof(long) endl;
"Size of int: " sizeof(int) endl;
"Size of unsigned long long: "
sizeof(unsigned long long) endl;
"Size of long long: " sizeof(long long) endl;
"Size of unsigned int: " sizeof(unsigned int) endl;
"Size of float: " sizeof(float) endl;
"Size of double: " sizeof(double) endl;

cout

"The output changes with compiler, hardware and OS"


endl;

return 0;

Computing the size of some C++ inbuilt variable types


Size of bool: 1
Size of char: 1
Size of unsigned short int: 2
Size of short int: 2
Size of unsigned long int: 4
Size of long: 4
Size of int: 4
Size of unsigned long long: 8
Size of long long: 8
Size of unsigned int: 4
Size of float: 4
Size of double: 8

,
.

sizeof

59

3.4
: , .
32-
(32- ) 64- . ,
64- , , , 32-
, 32-
, 64- . s i z e o f ,
;
MSB .

. -
,
.

++11
a u to
,
, . ,
true, bool. ++11
, auto:
auto Flag = true;

Flag .
,
, , .
true bool.
, bool Flag
bool, 3.5.
3.5. auto
1: #include <iostream>
2 : using namespace std;
3:
4: int main()
5: {
6:
auto Flag = true;
7:
auto Number = 2500000000000;
8:

9:
10:

11:
12:

13:
14:
15: }

cout
cout
cout
cout

"Flag = " Flag;


" , sizeof(Flag) = " sizeof(Flag) << endl;
"Number = " Number;
" , sizeof(Number) =" sizeof(Number) endl;

return 0;

60

3. ,

Flag = 1 , sizeof(Flag) = 1
Number = 2500000000000 , sizeof(Number) = 8

, b o o l F l a g
lo n g l o n g N um ber 6 7, ,
a u t o . ,
. ,
, s i z e o f ,
3.4, .

auto ,
,
.
,

auto .

a u t o ,
, .
, , , MyNumbers
s t d : : v e c t o r :
std::vector<int> MyNumbers;

( )
, :
for ( vector<int>::const_iterator Iterator = MyNumbers.begin ();
Iterator < MyNumbers.e n d ();
++Iterator )
cout * Iterator << " ";

s t d : . - v e c t o r , f o r ,
, . ,
, c o u t .
, I t e r a t o r
, b e g i n (). I t e r a t o r
v e c t o r < i n t > : : c o n s t _ i t e r a t o r ,
. ,
b e g i n () f o r :
for( auto Iterator = MyNumbers.begin();
Iterator < MyNumbers.e n d ();
++Iterator )
cout * Iterator "

, .
I t e r a t o r ,

typedef

61

b e g i n ( ) , .
C++, .


typedef
C ++ ,
. t y p e d e f . ,
u n s i g n e d i n t STRICTLY_POSITIVE_INTEGER.
typedef unsigned int STRICTLY_POSITIVE_INTEGER;
STRICTLY_POSITIVE_INTEGER PosNumber = 4532;

, STR IC LY _PO SITIV E_IN TEGER u n s i g n e d i n t . ,


STRICLY_POSITIVE_INTEGER,
u n s i g n e d i n t .


, . ,
.


, .
:
= Pi * * ;
= 2 * Pi *

P i 2 2 /7 1. ,
P i - .
P i , ,
. C++ P i ,
. ,
, .
C++ .
, C++ , ,
. ,
.
. C ++
.

1 Pi
. 3,14159265. . .

62

3. ,

, c o n s t .

, c o n s t e x p r (
++11).

, enum.

, .


3.1 , .
F ir s tN u m b e r :
9: int FirstNumber = 0;

F ir s tN u m b e r .
, ,
(literal constant).
: b o o l , i n t e g e r , s t r i n g .. C ++ (.
1.1) " H e l l o W o rld " :
std::cout << "Hello World" << std::endl;

" H e l l o W o rld " (string literal).


const
C++, ,
c o n s t , .
:
const _ _;

,
P i ( 3.6).
3.6. Pi____________________________________
1: #include <iostream>
2:
3: int main()
4: {
5:
using namespace std;
6:
7:
const double Pi = 22.0 / 7;
8:
cout "The value ofconstant Pi is: " Pi endl;
9:
10:
//
11:
// Pi = 345;
12:

13:
14: }

return 0;

63

The value of constant Pi is: 3.14286

P i 7. c o n s t
, P i d o u b le .
11, ,
,
: You c a n n o t a s s i g n t o a v a r i a b l e t h a t i s c o n s t (
, ). ,
.

,
, .
const ,

.
, .

,
. 4.2, 4, ,
, c o n s t i n t
.

--11________________________________________________
c o n s t e x p r
(constant expression)
C++, ++11,
. 3.5,
2 2 .0 / 7 2011 .
,
. + + 1 1 :
constexpr double GetPiO

{return 22.0 / 7;}

G e t P i ( ) , ,
, , :
constexpr double TwicePiO

{return 2 * GetPiO;}


;
. ( c o n s t e x p r )
, ,

64

3. ,

++11, ,
.

constexpr
Microsoft Visual C++ Express Compiler.
g++.


.
, ,
.
, .
(enum erated constant) ,
, enum.
, :
enum RainbowColors

{
Violet = ,
Indigo,
Blue,
Green,
Yellow,
Orange,
Red

:
enum CardinalDirections

{
North,
South,
East,
West

};
,
, ,
. , , ,
:
RainbowColors MyWorldsColor = Blue; //

M yW orld
s C o l o r R a in b o w C o lo r s .
, .

65


, violet , .
.
, ,
0. , North 0.

.

3.7
.

3.7.
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <iostream>
using namespace std;
enum CardinalDirections
{
North = 25,
South,
East,
West

1 0 : };

11:
12: int main()
13: {
14:
cout
"Displaying directions and their symbolic values"
endl;
15
cout "North: " << North << endl;
16
cout "South: " South endl;
17
cout "East: " East << endl;
18
cout "West: " West endl;
19
20
CardinalDirections WindDirection = South;
21
cout "Variable WindDirection = " WindDirection endl;
22
23
return 0;
24: }

Displaying directions and their symbolic values


North: 25
South: 26
East: 27
West: 28
Variable WindDirection = 26

3 3ak. 3626

66

3. ,

,
, 25 , N o r t h (. 6).
,
26, 27 28, . 20 C a r d i n a l D i r e c t i o n s , S o u th .
21 , S o u th ,
26.

6.4 6.5 6,
. ,
.


#define
, .
# d e f i n e
, ,
:
#define Pi 3.14286

,
P i 3 .1 4 2 8 6 . : (:
), .
.

#def ine
.


.

, . :
bool blsLampOn = false;

b , ,
b o o l . ;
M icrosoft. C ++
, ,
, , b o o l . ,
.
, . ,

, ...

67


, :
bool IsHeadLampOn = false;
, , :
bool b = false;
.

,

,
, ,


,
,

,

C++,

,


C++,
.
C++. , i f , w h i l e , f o r m a in .
C ++ . 3.2, ,
C + + . ,
.
3.2. C++
asm
auto
bool
break
case
catch
char
class
const
const cast

else
enum
explicit
export
extern
false
float
for
friend
goto

New
Operator
Private
Protected
Public
Register
reinterpret_cast
Return
Short
Signed

this
throw
true
try
typedef
typeid
typename
union
unsigned
using

continue

if

Sizeof

virtual

68

3. ,
. 3.2

default
delete
do
double
dynamic_cast

inline
int
long
mutable
namespace

Static
static cast
Struct
Switch
Template

void
volatile
wchar_t
while

, :
and
and_eq
bitand

bitor
compl
not

not_eq
Or
or_eq

xor
xor_eq


. ,
s i z e o f .
, b o o l, i n t .., ,
.
; ,
.
C++11 a u to ,
.
,
( c o n s t enum).


,
?
, , c o n s t,
,
. ,
, , ,
, , ,
. , ,
,
, .

?
, ,
. ,
. ,
int MyFavoriteNumber = 0;,

69

, M y F a v o rite N u m b e r,
, 0. ,

( , ).
, ,
, .. , .
C++ : s h o r t

in t , i n t lo n g in t? ,
?
C++ ,

.
, .
,
, .

,
, .

?
, ,
?
.
, . ,
.
.
,
. , , .
,
, .

C++ ,
, ,
.
u n sign ed in t?
(wrapping). 0
1 ,
! . 3.1 , u n s i g n e d s h o r t
0 65535. , u n s ig n e d
s h o r t , :
unsigned short MyShortlnt =0;
//
MyShortlnt = MyShortlnt - 1;
// 1
std::cout << MyShortlnt std::endl; // : 65535!

: u n s i g n e d s h o r t ,
. ( )
, .
M y S h o r t ln t

70

3. ,
, , ,
64 ! , M yShortlnt
, , ,
!


, ,
. ,
, .
,
.


1. ?
2. # d e f in e ?
3. ?
4. . QUEEN?
enum Y0URCARDS {, JACK, QUEEN, KING};

5. ?
i n t I n t e g e r = 0;

1. YOURCARDS 4 , <
QUEEN 45.
2. , ,
,
.
3. ,
.
4. 3
, ?
5. : :
a u to I n t e g e r ;



int, char string,
.
, , 20 .
.

, .

std::string.

72

4.


(array) ,
. , ,
, .
.
.
.
.
C++
.


, ,
.
.
:
int
int
int
int
int

FirstNumber = 0;
SecondNumber = 0;
ThirdNumber = 0;
FourthNumber = 0;
FifthNumber = 0;

500
, 500 ,
.
. , 500 000
5?
,
:
int MyNumbers

[5] = {0};

, 500 000 ,
:
int ManyNumbers

[500000] = {0};

:
char MyCharacters

[5];

(static array),
,
.

73


MyNumbers,
i n t (.. ), 0.
, C++ :
_ _ [_] = { }

.
,
:
int MyNumbers

[5] = {34, 56, -21, 5002, 365};

:
int MyNumbers

[5] = {100}; //
// 100

:
int MyNumbers

[5] = {34, 56}; //

(.. )
:
const int ARRAY_LENGTH = 5;
int MyNumbers [ARRAY_LENGTH] = {34, 56, -21, 5002, 365};

,
. ,

c o n s t in t .


0.

, :
int MyNumbers

[] = {2011, 2052, -525};


2011, 2052 -5 2 5 .

, ,
(static array),

. ,
. ,
.

74

4.


, . ,
,
. , ,
(. 4.1).

. 4.1. :
, . ,
, C++ 0, 1. ,
MyNumbers, , . 4.2.

. 4.2. MyNumbers
,
, ,

75

i n t . ,
3, , . ,
M yNumbers, s i z e o f ( i n t ) * 5.
, , :
= sizeof( ) * _

(index). ,
0. , ,
M yN um bers, M yN um bers [ 0 ] , M yN um bers [1 ] ..
M yN um bers [ 4 ] . ,
.
N,
( ) ,
N , , N * s i z e o f (_
) , , N+1- . C++
,
. 1001 ,
10 , .

.

. ,
. .

4.1 ,
.
4.1.
0: #include <iostream>
1:
2 : using namespace std;

3:
4: int main ()
5: {
6:
int MyNumbers [5] = {34, 56, -21, 5002,
7:
8:
cout "First element at index 0: "
9:
cout "Second element at index 1: "
10:
cout "Third element at index 2: "
11:
cout "Fourth element at index 3: "
12:
cout "Fifth element at index 4: "
13:
14:
return 0;
15: }

365};
MyNumbers
MyNumbers
MyNumbers
MyNumbers
MyNumbers

[0] endl;
[1] endl;
[2] endl;
[3] endl;
[4] endl;

76

4.

First element at index 0: 34


Second element at index 1: 56
Third element at index 2: -21
Fourth element at index 3: 5002
Fifth element at index 4: 365

6 ,
. ,
c o u t MyNumbers
.

,
, 4.1
, .


.

.
, 2011 :
int AnlntegerValue;
AnlntegerValue = 2011;

2011 :
MyNumbers

[3] = 2011; // 2011

4.2 ,
.

4.2. ____________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:.
15:
16:

#include <iostream>
using namespace std;
int main()
{
const int ARRAY_LENGTH = 5;
// 5 ,
int MyNumbers [ARRAY_LENGTH] = {0};
cout "Enter index of the element to be changed: ";
int nElementlndex = 0;
cin nElementlndex;
cout "Enter new value: ";
cin MyNumbers [nElementlndex];


17:
18:
19:
20:
21:
22:
23:
24: }

cout
cout
cout
cout
cout

77

"First element at index 0: " MyNumbers [0] endl;


"Second element at index 1: " MyNumbers [1] endl;
"Third element at index 2: " MyNumbers [2] << endl;
"Fourth element at index 3: " MyNumbers [3] endl;
"Fifth element at index 4: " MyNumbers [4] endl;

return 0;

Enter index of the element to be changed: 2


Enter new value: 2011
First element at index 0: 0
Second element at index 1: 0
Third element at index 2: 2011
Fourth element at index 3: 0
Fifth element at index 4: 0

8 c o n s t i n t e g e r
ARRAY LENGTH, .
, .
ARRAY LENGTH 5 , ,
, . 10-12
, ,
E le m e n tl n d e x . 14
. ,
2, ,
. .

C++
.
: ,
, .
(fence-post error).
,
, .

4.2 :
.
,
nElementindex 0 4, .

.
, .
6, "
.

78

4.


(
) .
, fo r, 6.10 6, "
".

N,
N, N

,
0


, , .
. ,
, , ,
.
, . 4.3? , ,
: .
0

. 4.3.
. 4.3,
: .
,
, , . C ++
, .

.

79


C++ , ,
. ,
, . 4.3, :
int SolarPanellDs

[2][3];

, . 4.3
0 5.
, :
int SolarPanellDs

[2][3] = {{0, 1, 2},

{3, 4, 5}};

,
. : ,
, . ,
:
int ThreeRowsThreeColumns
{303, 456, 596}};

[3][3] = {{-501, 206, 2011},

{989, 101, 206},

, C++
, .
,
.
SolarPanellDs ,
:

int SolarPanellDs [2] [3] = {0, 1, 2, 3, 4, 5};


,
, - .


.
, ,
, ,
, .
, ,
, ,
.
:
int ThreeRowsThreeColumns
{303, 456, 596}};

[3][3] = {{-501, 206, 2011},

{989, 101, 206},

, ,
.
206 [0][1], 456 [2][2].

80

4.

4.3 ,
.
4,3.
0
1
2
3

5
6
1
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

____________________________

#include <iostream>
using namespace std;
int main()
i
int ThreeRowsThreeColumns [3][3] = \
{{501, 206, 2011},
(989, 101, 206}, {303, 456 , 596}};
"Row 0: "

ThreeRowsThreeColumns [0] [0]


ThreeRowsThreeColumns [0] [1]
ThreeRowsThreeColumns [0] [2]

ft " \
vv " \
endl;

cout << "Row 1: "

ThreeRowsThreeColumns [1] [0]


ThreeRowsThreeColumns [1] [1]
ThreeRowsThreeColumns [1] [2]

VI " \
If " \
endl;

"Row 2: "

ThreeRowsThreeColumns [2] [0]


ThreeRowsThreeColumns [2] [1]
ThreeRowsThreeColumns [2] [2]

IV "\
VI " \
endl;

cout

cout

return 0;
}

Row 0: -501 206 2011


Row 1: 989 101 206
Row 2: 303 456 596

,
Row 0 ( 0)
Row 2 ( 2). ,
, 10.

4.3
.
.

6.14 6,
.
for. for
, ,
.

81


, .
,
.
, .

.
,
, ,

. C++
s t d : : v e c t o r , 4.4.
4,4.
0: #include <iostream>
1: #include <vector>
2:

3: using namespace std;


4:
5: int main()
6: {
7:
vector<int> DynArrNums (3);
8:

9:
10:
11:

DynArrNums[0] = 365;
DynArrNums[1] = -421;
DynArrNums[2]= 789;

12:

13:

cout

14:
15:
16:
17:
18:
19:
20:

"Number of integers in array: "


endl;

DynArrNums.size()

cout "Enter another number for the array"


int AnotherNum = 0;
cin AnotherNum;
DynArrNums.push_back(AnotherNum);

21:
22:
23:
24:
25: }

cout

cout
cout

endl;

"Number of integers in array: " DynArrNums.size()


endl;
"Last element in array: ";
DynArrNums[DynArrNums.size() - 1] endl;

return 0;

Number of integers in array: 3


Enter another number for the array
2011

Number of integers in array: 4


Last element in array: 2011

82

4.

4.4,
. .
, ,
7. , 15
, , 18 ,
p u s h b a c k ( ) . ,
.
4.
. 22
( ,
) ,
- 1, s i z e ()
.

std::vector
vector, 1 4.4.

#include <vector>
17,
STL".


(C -style string) .
,
:
std::cout << "Hello World";

:
char SayHello[] = {'', '', '1*, '1', '', '
std::cout << SayHello << std::endl;

'W', 'o', '', '1*, 'd', '\0'};

: ' \ 0 '.
(string-term inating character),
, .
, ' \ 0 *.
,
' \ 0 '.
' \ 0 ' , ;
, , .
4.5.

83

' \ 0 ' , , ,
.
- ,
\0 , ..
.
, ' 0 '
ASCII 48, 0.
ASCII,
, ASCII.

4.5.
0: #include <iostream>
1: using namespace std;
2:

3: int main()
4: {
5:

6
7
8
9
10

cout "Replacing space with null" endl;


SayHello[5] = '\0';
cout SayHello endl;
cout "Size of array: " sizeof(SayHello)

11
12

13
14
15

char SayHello[] = {'H', 'e', *1', '1', 'o', ' ',


'W', 'o', 'r', 11 1, 'd',
cout SayHello endl;
cout "Size of array: " sizeof(SayHello) endl;

endl;

return 0;

Hello World
Size of array: 12
Replacing space with null
Hello
Size of array: 12

10 H e l l o W o rld .
, ,
. ,
H e llo . s i z e o f () 7 12 ,
, .

84

4.

5
4.5 ' \ 0 ', H e llo W orld
. ,
s t d : :c o u t , ,
,
.
,
.

. 4.6 ,
.
4,6. ____________
0:
1:
2:
3:
4:
5:

#include <iostream>
using namespace std;
int main()
{
cout

"Enter a word NOT longer than 20 characters:"

endl;

6:

7:
8:
9:
10:

char Userlnput [21]


cin >> Userlnput;
cout

= {'\0 '};

"Length of your input was: "


endl;

strlen (Userlnput)

11:

12:
13: }

return 0;

Enter a word NOT longer than 20 characters:

Don'tUseThisProgram
Length of your input was: 19

.
. , 7 ,
,
21 . ' \ 0 ',
, , .
s t r l e n 10
. ,
, .
c i n .
s t r l e n ,
, . ,

C++: std::string

85

, , ,
6.2 6, .

C++:
s t d : : s t r in g
C ++ ,
, , .
, ( C++
),
, strcpy, , street,
, strlen.
,
,
.

C ++
s t d : : s t r i n g , 4.7. s t d : : s t r i n g
c h a r ,
, , .

4-7- std::string
, ,
0
1

#include <iostream>
#include <string>

3
4
5
6
7
8
9
10
11
12

13
14
15
16
17
18
19
20

using namespace std;


int main()

{
string Greetings ("Hello std::string!");
cout Greetings endl;
cout "Enter a line of text: "
string FirstLine;
getline(cin, FirstLine);
cout "Enter another: "
string SecLine;
getline(cin, SecLine);

endl;

endl;

cout "Result of concatenation: " endl;


string Concat = FirstLine + " " + SecLine;
cout Concat endl;

21

22
23
24

cout "Copy of concatenated string: "


string Copy;
Copy = Concat;

endl;

4.

86
25:
26:
27:
28:
29:
30: }

cout

cout

endl;

"Length of concat string: "

Concat.length()

endl;

return 0;

Hello std::string!
Enter a line of text:

I love
Enter another:

C++ strings
Result of concatenation:
I love C++ strings
Copy of concatenated string:
I love C++ strings
Length of concat string: 18

.
.
7 H e l l o s t d : : s t r i n g !. , 12
16, ,
F i r s t L i n e S e c L in e .
19, .
24.
l e n g t h () 27.

C++ string:

#include <string>
1 4.7.

s t d : : s t r i n g ,
16, STL.
, .

.
,
. ,
. (buffer overflow),

.

87


,
, .
, ,
1\ 0 . ,
, C++ s t d : : s t r i n g ,

, .


?
, ,
,
.
,
.

,
?
. .
,
, ,
.

,
?
- . C ++
s t d : : s t r i n g ,
.

?
, . H e ll o W o rld 11 , ,
.

,
, . ?
.
,
- .
. H e ll o W o rld ,
, 11 + 1 , .. 12 .


, ,
. ,

88

4.

, .
,
.


1. MyNumbers 4.1.
?
2. ,
?
3. , ' \ 0 ' ?
4. .
?
5. 4.4
, c h a r .

1. , ;
, .
2. : ?
int MyNumbers[5] = {0};
MyNumbers[5] = 450; // 450

3. : ?
int MyNumbers[5];
cout MyNumbers[3];

,


.
.
.

, .

90

5. ,

, , (statem ent),
. ,
:
cout << "Hello World" << endl;

c o u t (.. ).
C ++ ( ; ) ,
. ( .) ,
.
,
. , , :
cout << "Hello World" << endl; cout << "Another hello" << endl;
// ,

. ,
, ..
.

:
cout << "Hello
World" << endl;
//

, ,
(")
( ;) . -
, ( \) :
cout << "Hello \
World" << endl; //


:
cout << "Hello "
"World" << endl; //

,
.
,
,
, ,
.

91

,
{ . . . } ,
(com pound statem ent), (block).
{
int Number = 365;
cout << "This block contains an integer and a cout statement"
<< endl;

}
, .
i f , 6,
' .


(operator) ,
C++ , ,
.

(-)
(assignm ent operator) ,
:
int Mylnteger = 101;


101. ,
( 1- (1-value)),
( r- (r-value)).

I- -
1- . , M y ln t e g e r ,
()
1-, r-, ,
.
1- r-, r- 1-.
, ,
, :
101 = Mylnteger;

(+), (-),
(*), (/) (%)

+ , - , * ,
/ % :

92

5. ,
int
int
int
int
int
int
int

Numl = 22;
Num2 = 5;
addition = Numl + Num2;
subtraction = Numl - Num2;
multiplication = Numl * Num2;
division = Numl / Num2;
modulo = Numl % Num2;

//
//
//
//
//

27
17
110
4
2

( / ) .
,
. (%)
. 5.1
,
.

5.1.
_________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:,
15
16
17

#include <iostream>
using namespace std;
int main()
{
cout "Enter two integers:"
int Numl = 0,Num2
= 0;
cin Numl;
cin Num2;
cout
cout
cout
cout
cout

Numl
Numl
Numl
Numl
Numl

it

+
-
ii
/
% ii

Num2
Num2
Num2
Num2
Num2

endl;

I.

=
=
=
=
=

Numl
Numl
Numl
Numl
Numl

+ Num2
- Num2
Num2
/ Num2
% Num2

endl ;
endl ;
endl;
endl ;
endl;

return 0;

Enter
365
25
365 +
365 365 *
365 /
365 %

two integers:

25
25
25
25
25

=
=
=
=
=

390
340
9125
14
15

. , , ,
%.
Numl (365) Num2 (25).

93

(++) ( )
(increm ent), , .
, ,
.
C ++ ++ ( )
().
:
int
int
int
int
int

Numl
Num2
Num2
Num2
Num2

=
=
=
=
=

101;
Numl++;
++Numl;
Numl--;
--Numl;

//
//
//
//


: . , ,
(prefix) , ,
, (postfix) .


,
, .
, 1- r- , -
. ,
Num2 Numl
(.. , ).
:
-, 1-. Num2
Numl . 5.2
.

5.2. ______________
0: #include <iostream>
1: using namespace std;

2:
3: int main()

4: {
5:
6:
7
8
9
10
11
12

13
14
15

int Mylnt = 101;


cout "Start value of integer being operated: " << Mylnt
endl;
int PostFixInc = Mylnt++;
cout "Result of Postfix Increment = " << PostFixInc << endl;
cout "After Postfix Increment, Mylnt = " Mylnt endl;
Mylnt = 101; //
int PreFixInc = ++Mylnt;
cout "Result of Prefix Increment = " << PreFixInc << endl;
cout << "After Prefix Increment, Mylnt = " << Mylnt << endl;

94

5. ,

16:
17:
18:
19:
20:

Mylnt = 101;
int PostFixDec = Mylnt ;
cout "Result of Postfix Decrement = " PostFixDec endl;
cout "After Postfix Decrement, Mylnt = " Mylnt endl;

21:

22:
23:
24:
25:
26:
27:
28: }

Mylnt = 101;
int PreFixDec = Mylnt;
cout "Result of Prefix Decrement = " PreFixDec endl;
cout "After Prefix Decrement, Mylnt = " Mylnt endl;
return 0;

Start value of integer being operated: 101


Result of Postfix Increment = 101
After Postfix Increment, Mylnt = 102
Result of Prefix Increment = 102
After Prefix Increment, Mylnt = 102
Result of Postfix Decrement = 101
After Postfix Decrement, Mylnt = 100
Result of Prefix Decrement = 100
After Prefix Decrement, Mylnt = 100

, ,
8 1 8 .1- , ,
.
13 23, , .
, , .

:
Mylnt++; // , ...
++Mylnt;

,
.
,

, .. ++Myint , Myint++.
, , ,

.
, .

95

,
, short, int, long, unsigned short, unsigned int, unsigned
long .., .
,
(overflow).
, , unsigned short. short 16 ,
, 0 65535. 1
65535, unsigned short,
0. :
, ,
99 999 .
unsigned short
. 65 535 unsigned int.
signed short -32768 32767.
1 32767 signed integer
, .

5.3 ,
.
5.3.
0:
1:
2:
3:
4:
5:
6:

#include <iostream>
using namespace std;

int main ()
{
unsigned short UShortValue = 65535;
cout "Incrementing unsigned short "
" gives: ";
7:
cout ++UShortValue endl;

UShortValue

8:

9:
10:
11:

short SignedShort = 32767;


cout "Incrementing signed short "
cout ++SignedShort endl;

SignedShort " gives: ";

12:

13:
14: }

return 0;

Incrementing unsigned short 65535 gives: 0


Incrementing signed short 32767 gives: -32768

,
.

96

5. ,

u n s i g n e d
0.

s h o r t , 65 536,

(=) (!=)

, . == ( )
! = ( ) .
b o o l , .. t r u e ( )
f a l s e ().
int MyNum = 20;
bool CheckEquality = (MyNum == 20);
bool Checklnequality = (MyNum != 100);

// true
// true

bool CheckEqualityAgain = (MyNum == 200);


bool ChecklnequalityAgain = (MyNum != 20);

// false
// false


,
, , . C ++
, . 5.1.
5.1.

(<)

true,
(1 <2), false

(>)

true,
(Opl > 2), false

(<=)

true,
, false
true,
, false

(>=)

. 5.1,
t r u e f a l s e , , b o o l.
, . 5.1:
int MyNum = 2 0 ;
//
bool CheckLessThan = (MyNum < 100);
bool CheckGreaterThan = (MyNum > 100);
bool CheckLessThanEqualTo = (MyNum <= 20);
bool CheckGreaterThanEqualTo = (MyNum >= 20);
bool CheckGreaterThanEqualToAgain = (MyNum >= 100);

// true
// false
// true
// true
// false

5.4
.


S.4.
0
1

#include <iostream>
using namespace std;

int main()

4
5
6
7

{
cout "Enter two integers:"
int Numl = 0, Num2 = 0;
cin Numl;
cin Num2;

9
10

endl;

bool Equality = (Numl == Num2);


cout "Result of equality test: "

11
12

Equality

13
14
15
16
17
18
19
20

bool Inequality = (Numl != Num2);


cout "Result of inequality test: "

21

" < "

22
23
24
25
26
27
28
29
30
31
32

endl;

Inequality

endl;

bool GreaterThan = (Numl > Num2);


cout "Result of " Numl " > " Num2;
cout " test: " GreaterThan endl;
bool LessThan = (Numl < Num2);
cout "Result of " Numl
LessThan endl;

bool GreaterThanEquals = (Numl >= Num2);


cout "Result of " Numl " >= "
cout " test: " GreaterThanEquals

Num2

Num2;
endl;

bool LessThanEquals = (Numl <= Num2);


cout
"Result of " Numl " <= "
Num2;
cout " test: " LessThanEquals endl;
return 0;

Enter two
365
-24
Result of
Result of
Result of
Result of
Result of
Result of

integers:

equality test: 0
inequality test: 1
365 > -24 test: 1
365 < -24 test: 0
365 >= -24 test: 1
365 <= -24 test: 0

:
Enter two integers:
101
101
Result of equality test: 1
Result of inequality test: 0

4 3ak. 3626

" test: "

97

98

5. ,
Result
Result
Result
Result

of
of
of
of

101
101
101
101

> 101 test: 0


< 101 test: 0
>= 101 test:
:1
<= 101 test:
:1

.
, . ==,
>= <= .
, ,

, , .
6,
.

NOT, AND, OR XOR


N O T !
. NOT,
, . 5.2.
5.2. NOT

NOT ()

False
True

True
False

, A N D , O R X O R, .
A N D t r u e ,
t r u e . A N D . 5.3.
5.3. AND
1

1 AND 2

F a ls e
T ru e
F a ls e
T ru e

F a ls e
F a ls e
T ru e
T ru e

F a ls e
F a ls e
F a ls e
T ru e

A N D &&.
O R t r u e ,
t r u e . O R
. 5.4.
O R | | .
X O R (exclusive OR, )
O R t r u e ,
t r u e , . X O R
. 5.5.

99

5.4. OR
1

1 OR 2

raise
True
False
True

False
False
True
True

False
True
True
True

5.5. XOR
1

1 XOR 2

False
True
False
True

False
False
True
True

False
True
True
False

O R C ++ .
X O R .


C++ NOT (!), AND (&&) OR ( ||)
.
, .
,
.
,

. C ++
AND O R, , ,
.
5.5 A N D OR.

5.5. C++ && | |____________________________________


0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

#include <iostream>
using namespace std;
int main()
{
cout "Enter true(l) or false(0) for two operands:"
bool Opl = false, Op2 = false;
cin Opl;
cin Op2;
cout
cout

Opl
Opl

" AND " Op2 " = "


" OR " Op2 " = "

(Opl && Op2)


(Opl || Op2)

endl;

endl;
endl;

100
12:
13:
14: }

5. ,

return 0;

Enter true(l) or false(0) for two operands:

1
0
1 AND 0 = 0
1 OR 0 = 1

:
Enter true(l) or false(0) for two operands:

1
1
1 AND 1 = 1
1 OR 1 = 1

, AND
OR. , .
5.6 , ,
, ,
.
5.6. NOT (!)

AND (&&) ____________________


0: #include <iostream>
1: using namespace std;
2:
3: int main()

4: {
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

cout "Use boolean values(0 / 1) to answer the questions"


endl;
cout "Is it raining? ";
bool Raining = false;
cin Raining;
cout "Do you have buses on the streets? ";
bool Buses = false;
cin Buses;
// AND NOT
if (Raining && IBuses)
cout "You cannot go to work" endl;
else
cout "You can go to work" endl;
if

(Raining && Buses)


cout << "Take an umbrella"

endl;

101

22:

23:
24:
25:
26:
27: }

if ((!Raining) && Buses)


cout "Enjoy the sun and have a nice day"

eridl;

return 0;

Use boolean values(0 / 1) to answer the questions


Is it raining? 1
Do you have buses on the streets? 1
You can go to work
Take an umbrella

:
Use boolean values (0 / 1) to answer the questions
Is it raining? 1
Do you have buses on the streets? 0
You cannot go to work

:
Use boolean values(0 / 1) to answer the questions
Is it raining? 0
Do you have buses on the streets? 1
You can go to work
Enjoy the sun and have a nice day

5.6 i f ,
.
, . 15 ( R a i n in g &&
!B u s e s ) , .
AND (
NOT ) .

i f 6,
.

5.7 NOT ( !) OR ( | | )
.
5.7. NOT OR

, __________________________
0: #include <iostream>
1: using namespace std;
2:

3: int main()
4: {

102
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20: }

5. ,
cout "Answer questions with 0 or 1" endl;
cout "Is there a deep discount on your favorite car? ";
bool Discount = false;
cin Discount;
cout "Did you get a fantastic bonus? ";
bool FantasticBonus = false;
cin FantasticBonus;
if (Discount || FantasticBonus)
cout "Congratulations, you can buy that car!" endl;
else
cout "Sorry, waiting a while is a good idea" endl;
return 0;

Answer questions with 0 or 1


Is there a deep discount on your favorite car? 0
Did you get a fantastic bonus? 1
Congratulations, you can buy that car!

:
Answer questions with 0 or 1
Is there a deep discount on your favorite car? 0
Did you get a fantastic bonus? 0
Sorry, waiting a while is a good idea

:
Answer questions with 0 or 1
Is there a deep discount on your favorite car? 1
Congratulations, you can buy that car!

14 i f e l s e 16.
i f 15, ( D i s c o u n t
I | F a n t a s t i c B o n u s ) t r u e .
OR t r u e ,
. f a l s e ,
17 e l s e .

NOT (~), AND (&), OR ( |) XOR ()


,
, ,
. C++
, NOT, OR, AND OR (XOR), ,
,

103

OR | , AND
& XOR .
).
, ,
, , . ,
32 32- .
5.8.
5.8.

NOT, AND, OR XOR


#include <iostream>
#include <bitset>
using namespace std;
int main()

{
cout "Enter a number (0 - 255): ";
unsigned short InputNum = 0;
cin InputNum;
bitset<8> InputBits (InputNum);
cout InputNum " in binary is "
bitset<8> BitwiseNOT = (-InputNum);
cout "Logical NOT |" endl;
cout "-" InputBits " = "

19:
10:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30: }

InputBits

BitwiseNOT

endl;

endl;

cout "Logical AND, & with 00001111" endl;


bitset<8> BitwiseAND = (OxOF & InputNum);
// OxOF 0001111
cout "0001111 & " InputBits " = " BitwiseAND endl;
cout "Logical OR, | with 00001111" endl;
bitset<8> BitwiseOR = (OxOF | InputNum);
cout "00001111 | " InputBits " = " BitwiseOR
cout "Logical XOR, with 00001111" endl;
bitset<8> BitwiseXOR = (OxOF A InputNum);
cout "00001111 " InputBits " = " BitwiseXOR
endl;
return 0;

Enter a number (0 - 255): 181


181 in binary is 10110101
Logical NOT |
-10110101

01001010

Logical AND, & with 00001111

endl;

104

5. ,

0001111 S 10110101 = 00000101


Logical OR, | with 00001111
00001111 | 10110101 = 10111111
Logical XOR, A with 00001111
00001111 A 10110101 = 10111010

( b i t s e t ) ,
, . s t d : : b i t s e t
, .
10, 13, 17 22 ,
.
. ,
181 ,

&, | .
, NOT, 13,
. &, | ,
.
, .
C++,
25,
STL", std::bitset .

( ) ( )
,
, .
:
int DoubledValue = Num << 1; //
//

:
int HalvedValue = Num >> 2; //
//


5.9.
5-9- ()
,
() ___________________________
0:
1:
2:
3:
4:

#include <iostream>
using namespace std;
int main()
{

105

cout "Enter a number: ";


int Input = 0;
cin Input;
int
int
int
int

Half = Input 1;
Quarter = Input 2;
Double = Input 1;
Quadruple = Input 2;

cout
cout
cout
cout

"Quarter: " Quarter endl;


"Half: " Half endl;
"Double: " Double endl;
"Quadruple: " Quadruple endl;

return 0;

Enter a number: 16
Quarter: 4
Half: 8
Double: 32
Quadruple: 64

16, 1000.
9 , 0100,
8 . 10
, 1000 00100, 4.
11 12 .
10000 32, 100000
64, !

. ,
.

; .


(com pound assignm ent operator)
, .
:
int Numl = 22;
int Num2 = 5;
Numl += Num2; // Numl 27

106

5. ,

:
Numl = Numl + Num2;

, += ,
(Numl).
. 5.6.
5..








AND
OR
X0R

Numl += Num2 ;

Numl = Numl + Num2;


Numl = Numl - Num2 ;
Numl = Numl Num2 ;

Numl -= Num2 ;
Numl *= Num2;
Numl /= Num2 ;
Numl %= Num2 ;

Numl = Numl / Num2;


Numl = Numl % Num2 ;

Numl = = Num2;

Numl = Num *

Num2 ;

Numl = = Num2;

Numl = Num :

Num2 ;

Numl &= Num2;

Numl = Numl & Num2;

Numl 1= Num2 ;
Numl A= Num2;

Numl = Numl 1 Num2;


Numl = Numl
Num2;

5.10.
5.10. ,

, , , OR, AND X0R


0
1
2
3

#include <iostream>
using namespace std;

/
i

5
6
7
O

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

int main()
cout
"Enter a number:
int Value = 0;
cin ValuedValue + =
cout
Value - =
cout
Value / =
cout
Value * =
cout
Value % =
cout

8;
"After
2;
"After
4;
"After
4;
"After
1000;
"After

";

+ =

8, Value

"

Value

endl ;

-=

2, Value

"

Value

endl ;

/=

4, Value

"

Value

endl ;

*=

4, Value

"

Value

endl ;

%=

1000, Value _ ii

Value

endl;

//
: cout
(Value = 1) endl;
cout
"After = 1, value = "
cout
"After = 2 , value = " (Value = 2) endl;

cout

"After |= 0x55, value _

(Value |= 0x55)

endl


15:
16:

cout
cout

"After = 0x55, value = "


"After &= OxOF, value = "

13:
19:}

return 0;

(Value A= 0x55)
(Value &= OxOF)

107

endl;
endl;

Enter
After
After
After
After
After
After
After
After
After
After

a number: 440
+= 8, Value = 448
-= 2, Value = 446
/= 4, Value = 111
*= 4, Value = 444
%= 1000, Value = 444
= 1, value = 888
= 2, value = 222
|= 0x55, value = 223
A= 0x55, value = 138
&= OxOF, value = 10

, V a lu e
.
V a lu e ,
V a lu e . , 9 440
8, , 448, V a lu e .
11 448 2, 446,
V a lu e , ..

size o f
,
,
. s i z e o f :
sizeof( );

sizeof();

sizeof (...) , ,
. ,
, .

12, .

5.11 s i z e o f
, . , 3.4

108

5. ,

s i z e o f ,
.
5.11. sizeof

, 100 __________________
0:
1:
2:
3:
4:
5:

#include <iostream>
using namespace std;

int main ()
{
cout "Use sizeof of determine memory occupied by arrays"
endl;
6:
int MyNumbers [100] = {0};
7:
8:
cout "Bytes occupied by an int: " sizeof(int) endl;
9:
cout "Bytes occupied by arrayMyNumbers:
"
sizeof(MyNumbers) endl;
10:
cout "Bytes occupied by each element: "
sizeof(MyNumbers[0]) endl;
11:

12:
13: }

return 0;

Use sizeof of determine memory occupied by arrays


Bytes occupied by an int: 4
Bytes occupied by array MyNumbers: 400
Bytes occupied by each element: 4

, s i z e o f
100 , 400 ,
4 .
s i z e o f ,
N , .
s i z e o f ,
, ,
new.

8, .


, ,
, .
C++ :
int MyNumber = 10 * 30 + 2 0

- 5 * 5<<2;

109

: MyNumber?
.
C++. , . 5.7.
5.7.

8
9
10
11
12
13
14
15
16


,
,
,
" ", ,
new, new [ ] ,delete, delete [ ] ,casting, sizeof ()

, ,
,
,
, , ,
,
AND
or
or
a n d
OR

17

4
5
6
7

. -> () ++
++ ! - + & * ()

^* _>*
* / %
+

II

== !=
&
1
&&
11
?:
II

V
V

II
* II

II

, :
int MyNumber = 10 * 30 + 20 - 5 * 5 << 2;


, . 5.7, , .
, , ,
, , .
:
int MyNumber = 300 + 2 0 - 2 5

<< 2;

,
:
int MyNumber = 295 << 2;

, . ,
, 4, ,
2 95 * 4, 1180.

110

5. ,

, .
.
, .
, :

int MyNumber = ((10 * 30) - (5*5) +20) 2 ; //


//

,
;



, i- (,
) r-,
r- (, "Hello World")
{-

,
++ ++
.

, , C++.
, ,
, .
, NOT, A N D , O R X O R. !, && | | ,
, , ~, &, | ,
.
, ,
,
.
.


u nsign ed in t , u nsign ed
s h o r t ?
u n s i g n e d s h o r t 65535,
, . ,
, u n s i g n e d i n t , ,
.

. :
i n t r e s u l t = Number / 3 1;?
! ,
.
.

111

5 2:
int Numl = 5, Num2 = 2;
int result = Numl / Num2;

2. ?
. .
2, 2.5. 2.5,
f l o a t d o u b le ,
.


, ,
. ,
, .
,
.


1. . :
i n t f l o a t ?
2. 32 / 7?
3. 3 2 . 0/7?
4. s i z e o f ( . . . ) ?
5. , 5, .
?
int Result = number

1+5

1;

6. XOR, t r u e ?

1. 5,
.
2. R e s u l t :
int Result = number

1 + 5

1;

3. ,
.

-
.
-,
, .
.

-
.

6.


i f . . .else
[, ,
. ,
, ,
, , ,
. 6.1, <>, , ,
, .
.

. 6 .1 .

if...else

115


i f . . .e lse
C + + i f
e l s e , :

...

if ( )
, true;
else //
, false;

, i f . . . e l s e , ,
<>, ,
:
if (UserSelection == 'm')
Result = Numl * Num2; //
else
Result = Numl + Num2; //

C++ true ,
false, . ,
, ,
, true,
.

6.1,
, .

6.1.
__________________________________________
0: #include <iostream>
1: using namespace std;
2:

3: int main()
4: {
5:
cout "Enter two integers: " endl;
6:
int Numl = 0, Num2 = 0;
7:
cin Numl;
8:
cin Num2;
9:
10:
cout "Enter V m V to multiply, anything else to add: ";
11:
char UserSelection = *\0;
12:
cin UserSelection;
13:
14:
int Result = 0;
15:
if (UserSelection == 'm')
16:
Result = Numl * Num2;
17:
else
18
Result = Numl + Num2;
19

116
20:

6.
cout

"Result is: "

Result

endl;

21:

22:
23: }

return 0;

Enter two integers:


25
56
Enter 'm' to multiply, anything else to add: m
Result is: 1400

:
Enter two integers:
25
56
Enter 'm' to multiply, anything else to add: a
Result is: 81

i f 15 e l s e
17. 15 ,
i f ( U s e r S e l e c t i o n == ' m ' ) (
t r u e ) , , (
f a l s e ) . ( U s e r S e l e c t i o n == 'm ') t r u e ,
' ( ), f a l s e
. , -
. 6.1 , -
.
else if...else
,
.

15 6.1 :

15:

if (UserSelection == 'm');

if ,
( ).
,
, if else.

empty control statement (
).

if...else

117


,
. , ( { . . . } ) ,
, . :
if ( )

{
//
1;
2;

}
else

{
//
3 ;
4;

(com pound statem ent).


4, ,
.
.
, , . 6.2
, .

6.2.
0
1
2

#include <iostream>
#include <string>
using namespace std;

3
4
5
6
7

int main()

{
char Buffer[20] = {\0*};

cout "Enter a line of text: "


string LineEntered;
getline (cin, LineEntered);

10
11
12

if (LineEntered.length() < 20)

13
14
15
16
17
18
19

endl;

strcpy(Buffer, LineEntered.c_str());
cout "Buffer contains: " Buffer

}
return 0;

Enter a line of text:

This fits buffer!


Buffer contains: This fits buffer!

endl;

118

6.

, 12
.
13-16 ( ).

if ( ) .
, if
.
:

if ( ) ;
;
, if

, .

i f
, ,
. C++
i f .
i f :
if ( 1)

{
1 ;
if (2)
2;
else
2 ;

}
else
1;

, 6.1, ,
< d> < >, ,
. , ,
.
, , .
6.3 i f .

..

3
if
_________________________________________________

0:
1:
2:
3:
4:
5:

#include <iostream>
using namespace std;
int main()
{
cout

"Enter two numbers: "

endl;

if...else
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

float Numl = 0, Num2 = 0;


cin Numl;
cin Num2;
cout "Enter 'd' to divide, anything else to multiply: ";
char UserSelection = '\0';
cin UserSelection;
if (UserSelection == 'd')
{
cout "You want division!" endl;
if (Num2 != 0)
{
cout "No div-by-zero, proceeding to calculate"
endl;
cout Numl " / " Num2 " = " Numl / Num2
endl;

21:

22:
23:
24:
25:
26:
27:
28:

else
cout

"Division by zero is not allowed"

endl;

}
else
{
cout "You want multiplication!" endl;
cout Numl " x " Num2 " = " Numl * Num2
endl;

29:
30:
31:
32: }

}
return 0;

Enter two numbers:


45
9
Enter 'd ' to divide, anything else to multiply: m
You want multiplication!
45 x 9 = 405

:
Enter two numbers:
22
7
Enter 'd' to divide, anything else to multiply: d
You want division!
No div-by-zero, proceeding to calculate
22 / 7 = 3.14286

:
Enter two numbers:
365

119

120

6.

Enter ' to divide, anything else to multiply: d


You want division!
Division by zero is not allowed


. ,
. 6.1
.

f l o a t , ,
.

i f 6.1.
, <>; ( U s e r S e l e c t i o n ==
' d ' ) 14 t r u e , d.
, .

,
, , .
17 i f .

, , i f
,
.

, , ,
if.

: i f . . . e l s e .
6.4 , ,
i f . . . e l s e , , .

6.4. ,
0
1

#include <iostream>
using namespace std;

int main()

5
6
7
8
9

10
11
12

13
14
15

enum DaysOfWeek
{
Sunday = 0,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday

};

if...else
16:
17:
18:
19:
20:

cout
cout

"Find what days of the week arenamedafter!"


"Enter a number for aday(Sunday
= 0): ";

121

endl;

int Day = Sunday; // Sunday


cin Day;

21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
21:
32:
33:
34:
35:
36:
37:
38:
39:
40: }

if (Day == Sunday)
cout "Sunday was named after the Sun" endl;
else if (Day == Monday)
cout "Monday was named after the Moon" endl;
else if (Day == Tuesday)
cout "Tuesday was named after Mars" endl;
else if (Day == Wednesday)
cout "Wednesday was named after Mercury" endl;
else if (Day == Thursday)
cout "Thursday was named after Jupiter" << endl;
else if (Day == Friday)
cout "Friday was named after Venus" endl;
else if (Day == Saturday)
cout "Saturday was named after Saturn" endl;
else
cout "Wrong input, execute again" endl;
return 0;

Find what days of the week are named after!


Enter a number for a day (Sunday = 0): 5
Friday was named after Venus

:
Find what days of the week are named after!
Enter a number for a day (Sunday = 0): 9
Wrong input, execute again

i f . . . e l s e . . . i f , 2 2 -3 7 ,
. ,
, 0 -6 ,
, .
, ,
.. ,
. ,
, D aysO fW eek,
5 i f .
; , , 0
.. S u n d a y
.

122

6.


switch-case
s w i t c h - c a s e ,
,
. C++,
, s w i t c h , c a s e , d e f a u l t b r e a k .
s w i t c h - c a s e :
switch()

{
case :
;
break;
case :
;
break;
/ / ...
default:
;
break;

}

c a s e , ,
. ,
. , .
, b r e a k .
b r e a k . . b r e a k
; ,
. , , . d e f a u l t
, ,
s w i t c h - c a s e .

switch-case
. 3, "
, .

6.5 6.4,
s w i t c h - c a s e .

6.5. , ,
switch-case_______________________________________________
0:
1:
2:
3:
4:
5

#include <iostream>
using namespace std;
int main()
{
enum DaysOfWeek

if...else

Sunday = ,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday

cout
cout

"Find what days of the week are named after!"


"Enter a number for a day (Sunday = 0): ";

int Day = Sunday; // Sunday


cin Day;
switch(Day)

{
case Sunday:
cout "Sunday was named after the Sun"
break;

endl;

case Monday:
cout "Monday was named after the Moon"
break;
case Tuesday:
cout "Tuesday was named after Mars"
break;

endl;

endl;

case Wednesday:
cout "Wednesday was named after Mercury"
break;
case Thursday:
cout "Thursday was named after Jupiter"
break;
case Friday:
cout "Friday was named after Venus"
break;

}
return 0;

"Wrong input, execute again"

endl;

endl;

case Saturday:
cout "Saturday was named after Saturn"
break;
default:
cout
break;

endl;

endl;

endl;

endl;

123

124

6.

Find what days of the week are named after!


Enter a number for a day (Sunday = 0): 5
Friday was named after Venus

:
Find what days of the week are named after!
Enter a number for a day (Sunday = 0): 9
Wrong input, execute again

2 2 -5 5 s w i t c h - c a s e ,
, ,
Day. 5,
Day s w i t c h , 5, ,
S u n d a y ( 0) T h u r s d a y ( 4),
, 5.
F r i d a y , 5 Day s w i t c h ,
, b r e a k ,
s w i t c h . , ,
d e f a u l t
.
s w i t c h - c a s e
, i f . . . e l s e . . . i f 6.4.
s w i t c h - c a s e , ,
, ,
( ,
).

(?:)
C + + ,
(conditional operator), i f . . .
e lse .
,
, :
( ) ? 1 tr u e : 2 f a l s e ;

, .
int = (Numl > Num2)? Numl : Num2;
// Max Numl Num2

6.6 : ?.

6.6. (?:)
0: #include <iostream>
1: using namespace std;

if...else

125

2: int main()

4: {
::
6:

5:
1:
_:
11:

cout "Enter two numbers"


int Numl = 0, Num2 = 0;
cin
Numl;
cin
Num2;

endl;

int Max = (Numl > Num2)? Numl : Num2;


cout "The greater of " Numl " and " \
Num2 " is: " Max endl;

_4:

return

0;

Enter two numbers

365
-1
The greater of 365 and -1 is: 365

10. ,
, .
i f . . . e l s e , :
int = 0;
if (Numl > Num2)
Max = Numl;
else
Max = Num2;

, !
.
, . ,
.


s w it c h ,

c a s e
-

d e f a u l t
s w itc h ,

ca s e ,
b r e a k
,
c a s e

,
b r e a k c a s e

: ?

126

6.


, -,
. , 6.2 ,
< > , .
, ?
, ?
.
.

goto
g o to ,
.
.
g o t o :
SomeFunction()

{
JumpToPoint: //
CodeThatRepeats;
goto JumpToPoint;

}
J u m p T o P o in t g o t o
, 6.7.
g o t o , f a l s e
, r e t u r n ,
, g o t o
.
6 .7 . ,
, goto_______________________________________________

0: #include <iostream>
1: using namespace std;
2:

3: int main()
4: {
5:
JumpToPoint:
6:
int Numl = 0, Num2 = 0;
7:
8:
cout "Enter two integers: "
9:
cin >> Numl;
10:
cin Num2;

endl;

11:

12:
13:
14:
15:
16:

cout
cout

Numl
Numl

" x"
" +"

Num2 " = "


Num2 " = "

Numl * Num2 endl;


Numl + Num2 << endl;

cout "Do you wish to perform another operation (y/n)?"


endl;
char Repeat = 'y';


cin

127

Repeat;

1:
19:
12:

if (Repeat == '')
goto JumpToPoint;

12:

cout

24:

return 0;

"Goodbye!"

endl;

Enter two integers:


56
25
56 x 25 = 1400
56 + 25 = 81
Do you wish to perform another operation (y/n)?

Enter two integers:


95
-47
95 x -47 = -4465
95 + -47 = 48
Do you wish to perform another operation (y/n)?

n
Goodbye!

6.7 6.1:
,
. 6.7
, ,
. , , 20,
g o t o , ' '.
g o t o 20 J u m p T o P o in t,
5, .

goto ,

,
,
.
, goto,
(spaghetti code).
while, do...while for
goto.
goto ,
, .

128

while
w h i l e C ++ , g o t o
6.7, . :
while()

{
I I = true
;

}
,
t r u e . , ,
f a l s e , w h i l e .
6.8 6.7,
, w h i l e g o to .

..

6 8 while
______________________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
int main()
{
char UserSelection = 'm'; //

8:

while (UserSelection != 'x')


{

9:
10:
11:
12:
13:
14:

cout "Enter the two integers: "


int Numl = 0, Num2 = 0;
cin Numl;
cin Num2;
cout

cout

15:
16:
17:
18:
19:
20:
21:
22:
23:
24: }

Numl
endl;
Numl
endl;

endl;

" x "

Num2

" = "

Numl * Num2

" + "

Num2

" = "

Numl + Num2

cout "Press x to exit(x) or any other key to recalculate"


endl;
cin UserSelection;
}
cout

"Goodbye!"

return 0;

Enter the two integers:


56

endl;

129

25
56 25 = 1400
56 + 25 = 81
Press to exit() or any other key to recalculate
r
Enter the two integers:
365
-5
365 x -5 = -1825
365 + -5 = 360
Press x to exit(x) or any other key to recalculate
x
Goodbye!

w h i l e 7 -1 9 . , w h i l e ( U s e r S e l e c t i o n ! = ' 1)
, t r u e .
U s e r S e l e c t i o n 5
' i '. , * 1 (
,
).
17 , . 18
; ,
w h ile , .

w h ile 7 , , ' '.
<>, 7 f a l s e
w h i l e . ,
.

(iteration). ,
while, do...while f_or,
.

do...while
( 6.8), ,
, .
d o . . . w h ile .
:
do

{
; //
} while( );
// ,

5 . 3626

130

6.

, , w h i l e ( ),
. w h ile ,
, .

6.9. do...while
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

#include <iostream>
using namespace std;
int main()
{
char UserSelection = 'x ; //
do
{
cout "Enter the two integers: " endl;
int Numl = 0,Num2
= 0;
cin Numl;
cin Num2;

12:
13:

cout

cout

14:
15:
16:

Numl
endl;
Numl
endl;

" x "

Num2

" = "

Numl * Num2

" + "

Num2

" = "

Numl + Num2

cout "Press x to exit(x) or any other key to recalculate"


endl;
cin UserSelection;
} while (UserSelection != 'x');

17:
18:
19:
20:

cout

"Goodbye!"

endl;

21:

22:
23: }

return 0;

Enter the two integers:


654
-25
654 x -25 = -16350
654 + -25 = 629
Press x to exit(x) or any other key to recalculate

m
Enter the two integers:
909
101

909 x 101 = 91809


909 + 101 = 1010
Press x to exit(x) or any other key to recalculate

x
Goodbye!

131

. ,
do 6 w h i l e
18. , ,
18 w h i l e , ( U s e r S e l e c t i o n
= ' ' ) . t r u e (.. <>
), . f a l s e (..
<>),
, .
.>

fo r
f o r ,
( ), ( ,
) ( ).
f o r :
I
for ( , ;
, ;
, )

{
;

}
f o r ,
,
.
6.10
f o r .
6.10. for
* _____________________________________________

I: #include <iostream>
1: using namespace std;
3: int main()

4: {
5:
3:
3:

const int ARRAY_LENGTH = 5;


int Mylnts[ARRAY_LENGTH] = {0};
cout

II:
II:

12:
13:

"Populate array of "


endl;

ARRAY_LENGTH

" integers"

for (int Arraylndex = 0; Arraylndex < ARRAY_LENGTH; ++Arraylndex)


{

cout "Enter an integer for element "


cin Mylnts[Arraylndex];

Arraylndex

": ";

132

6.

16:
17:
18:
19:
20:
21:
22:

cout

"Displaying contents of the array: "

endl;

for (int Arraylndex = 0; Arraylndex < ARRAY_LENGTH; ++Arraylndex)


cout "Element " Arraylndex " = "
Mylnts[Arraylndex] endl;
return 0;
}

Populate array of 5 integers


Enter an integer for element 0: 365
Enter an integer for element 1: 31
Enter an integer for element 2: 24
Enter an integer for element 3: -5 9
Enter an integer for element 4: 65536
Displaying contents of the array:
Element 0 = 365
Element 1 = 31
Element 2 = 24
Element 3 = -59
Element 4 = 65536

6.10 f o r 10 18.
, . f o r
. A r r a y l n d e x
. ;
.
f o r . ,
A r r a y l n d e x , ,
( ARRAY LENGTH). , f o r
.

, Arraylndex, 6.10,
(, ),
(iterator).
, for,
. , for
6.10 , ,
.

, ,
, . f o r
, 6.11.

133

6.11. f o r

^ _________
#include <iostream>
using namespace std;
5: int main()

4: {
::
6:

// ( )
for(char UserSelection = 'm'; (UserSelection != 'x'); )

{
::
9:
:
1:

cout "Enter the two integers: "


int Numl = 0,Num2
=0;
cin Numl;
cin Num2;
cout

cout

I d:
16:

Numl
endl;
Numl
endl;

endl;

" x "

Num2

" = "

Numl * Num2

" + "

Num2

" = "

Numl + Num2

cout "Press x to exit or any other key to recalculate"


endl;
cin UserSelection;

19
1j

cout

12:

return 0;

"Goodbye!"

endl;

13: }

Enter the two integers:


56
25
56 x 25 = 1400
56 + 25 = 81
Press x to exit or any other key to recalculate

m
Enter
789
-3 6
789 x
789 +
Press

the two integers:

-36 = -28404
-36 = 753
x to exit or any other key to recalculate

x
Goodbye!

6.8, w h ile ;
f o r 8. f o r ,
,
.

134

6.

for
. for 6.11
:

for (int Index = 0, AnotherInt = 5; Index < ARRAY_LENGTH;


++Index, Anotherlnt)
Anotherlnt,
5.
, ,
.



continue break
(
) ,
.
c o n t i n u e b r e a k .
c o n t i n u e .
, . ,
c o n t i n u e w h ile , d o . . . w h i l e f o r
, .
continue for
(
for, ).

b r e a k , ,
.

, ,
. continue break
.
continue break ,
,
, .

6.12 c o n t i n u e
b r e a k
.

continue break

135

,
, ..
, w h i l e , d o . . . w h i l e f o r , f a l s e
. ,
t r u e , .
w h i l e :
while(true) // while true

{
;

}
d o . . . w h i l e :
do

{
;
} while(true); // do...while false

f o r :
for (;;) // , , for

{
;

}
, .
, , U SB
U SB. ,
. .


( ,
) b r e a k ( ,
i f ( ) ).
b r e a k w h ile :
while(true) // while true
{
;
if()
break; // , true

}
b r e a k d o . . w h ile :
do

{
;
if()
break; // , true
} while(true); // do...while false

136

6.

b r e a k f o r :
for (;;) // , , for

{
;
if ()
break; // , true

}
6.12 c o n t i n u e b r e a k
.
6.12. continue

break for______________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;

int main ()
{
for(;;) //
{
cout "Enter two integers: " endl;
int Numl = 0, Num2 = 0;
8:
cin Numl;
9:
cin Num2;
10:
11:
12:
cout "Do you wish to correct the numbers? (y/n): ";
13:
char ChangeNumbers = '\0 *;
14:
cin ChangeNumbers;
15:
16:
if (ChangeNumbers == 'y )
17:
continue; // !
18:
19:
cout Numl " x " Num2 " = " Numl * Num2
endl;
20:
cout Numl " + " Num2 " = " Numl + Num2
endl;

21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33: }

cout "Press x to exit or any other key to recalculate"


endl;
char UserSelection = *\0';
cin UserSelection;
if (UserSelection == x')
break; //
}
cout

"Goodbye!"

return 0;

endl;

continue break

137

Enter two integers:


560
25
Do you wish to correct the numbers? (y/n):
Enter two integers:
56
25
Do you wish to correct the numbers? (y/n): n
56 x 25 = 1400
56 + 25 = 81
Press x to exit or any other key to recalculate

r
Enter two integers:
95

-1
Do you wish to correct the numbers? (y/n): n
95 x -1 = -95
95 + -1 = 94
Press x to exit or any other key to recalculate

x
Goodbye!

f o r 5 6.11 , ,
, . ,
b r e a k ( , )
. ,
, ,
. 16 17
c o n t i n u e , .
<> , ,
16 t r u e , , c o n
t i n u e . c o n t i n u e ,
, . ,
' ',
26 b _ r e a k ,
.
6.12
for (;;). while (true) d o ...
while (true); ,
.

138

6.

d o . . . w h ile ,

c o n t in u e b re a k

w h ile , d o . . . w h i l e
f o r


b re a k ,

g o t o

,
,


, i f
. , .
A r r a y l 2
, .
A r r a y l , , , 2 .
6.13 , .

6.13.
__________________________
0: #include <iostream>
1: using namespace std;
2:

3: int main ()
4: {
5:
const int ARRAY1_LEN = 3;
6:
const int ARRAY2_LEN = 2;
7:
8:
int Mylntsl[ARRAY1_LEN]
= {35, -3, 0};
9:
int Mylnts2 [ARRAY2_LEN]
= {20, -lb10:
11:
cout "Multiplying each int in Mylntsl by each in Mylnts2:"
endl;
12:
13:
for(int Arrayllndex = 0; Arrayllndex < ARRAY1_LEN; ++Arrayllndex)
14:
for(int Array2lndex = 0;
Array2lndex < ARRAY2_LEN; ++Array2lndex)
15:
cout Mylntsl[Arrayllndex] " x "
Mylnts2[Array2Index] \
16:
" = " Mylntsl[Arrayllndex] * Mylnts2[Array2Index]
endl;
17:
18:
return 0;
19: }

139

Multiplying each int in Mylntsl by each in Mylnts2:


35 x
20=
700
35 x
-1=
-35
-3 x
20=
-60
-3 x
-1=
3
0 x 20 = 0
0 x -1 = 0

f o r 13 14.
f o r M y l n t s l , M y ln ts 2 . f o r
. f o r
M y ln ts 2 , ,
A r r a y 1 I n d e x , , . ,
M y l n t s l I n t s 2 , M y l n t s l ( 0)
M y ln ts 2 . M y l n t s l
M y ln ts 2 . , M y l n t s l
M y ln ts 2 .
( )
6.13 . ,
6.10, ,
.



4 . 4.3
.
,
. ,
.
, 6.14.

6.14.
___________________________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
int main()
{
const int MAX_ROWS = 3;
const int MAX_COLS = 4;

140

6.

8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

//
int Mylnts[MAX_R0WS][MAX_COLS] = { {34, -1, 879, 22},
{24, 365, -101, -1},
{-20, 40, 90, 97} };
//
for (int Row = 0; Row < MAX_ROWS; ++Row)
{
// ()
for (int Column = 0; Column < MAX_COLS; ++Column)
{
cout "Integer[" Row "][" Column \
"] = " Mylnts[Row][Column] endl;

21:

22:
23:
24:
25: }

return 0;

Integer[0][0]
Integer[0][1]
lnteger[0][2]
Integer[0][3]
Integer[1][0]
Integer[1][1]
Integer[l][2]
Integer[1][3]
Integer[2][0]
Integer[2][1]
Integer[2][2]
Integer[2][3]

=
=
=
=
=
=
=
=
=
=
=
=

34
-1
879
22
24
365
-101
-1
-20
40
90
97

14-22 f o r ,
.
. , f o r
( ),
, .. .

6.14 for
.
, - ,
, .

141



, 0 1,
. ,
:
, 1, 1, 2, 3, 5, 8, ...
6.15 ,
, ,
.
6 .1 5 .
_____________
2 : #include <iostream>
1: using namespace std;

2
3: int main()
const int NumsToCal = 5;
cout "This program will calculate "
" Fibonacci Numbers at a time"

NumsToCal \
endl;

9
13

13
14

int Numl = 0, Num2 = 1;


char WantMore = *\0';
cout Numl " " Num2

" ";

do

15

for (int Index = 0; Index < NumsToCal; ++Index)

16

17

cout

13
19

:i
12

26
27
28
29
30
31

" ";

int Num2Temp = Num2;


Num2 = Numl + Num2;
Numl = Num2Temp;

10

13
34
25

Numl + Num2

cout endl "Do you want more numbers (y/n)? ";


cin WantMore;
}while (WantMore == 'y');
cout

"Goodbye!"

endl;

return 0;

This program will calculate 5 Fibonacci Numbers at a time


0 1 1 2 3 5 8
Do you want more numbers (y/n)?

142

6.

13 21 34 55 89
Do you want more numbers (y/n)?
144 233 377 610 987
Do you want more numbers (y/n)?
1597 2584 4181 6765 10946
Do you want more numbers (y/n)? n
Goodbye!

d o . . . w h i l e 13 ,
, . f o r 15
* .
19 Num2 ,
21. ,
, Numl , 20,
.
Numl Num2, <>.

, ,
;
. ,
i f . . . e l s e s w i t c h - c a s e , ,
.
g o to ,

. C++, w h ile , d o . . . w h ile
f,o r, , ,
, c o n t i n u e b r e a k .


, break sw itc h -c a se ?
b r e a k s w i t c h .
c a s e .

?
b r e a k . r e t u r n
.

w h i l e w h ile (I n te g e r ). ,
In te g e r -1, ?
w h i l e
t r u e f a l s e , f a l s e 0.
t r u e . -1 ,
w h i l e t r u e , .
, ,

143

w h i l e ( l n t e g e r > 0 ) .
.

w h ile fo r ( ; ; ) ?
, w h i l e .

d o. . .w h ile (exp) ; w h ile (exp) ; .


- ?
, ! w h i l e ( e x p ) ; , w h i l e ,
,
.
. .


, ,
. ,
, .
,
.


1. ,
i f , ?
2. , g o to .
?
3. f o r , ?
?
4. ?
for (int Counter=0; Counter==10; ++Counter)
cout Counter "

1. f o r .
2. , 6.13,
.
3. , , 6.15,
, , .
4. s w i t c h - c a s e , ,
. .
5. : ?
for (int Counter=0; Counter=10; ++Counter)
cout Counter " ;

144

6.

6. : ?
int LoopCounter = 0;
while(LoopCounter <5);

{
cout LoopCounter
LoopCounter++;

" ";

7. : ?
cout "Enter a number between 0 and 4"
int Input = 0;
cin Input;
switch (Input)

{
case
case
case
case
case

0:
1:
2:
3:
4:
cout
default:
cout

"Valid input"

endl;

"Invalid input"

endl;

endl;



,
main ().
.
,
main (),
.

.
, .
(function) ,
. ,
.
.

- ++11.

7.

146


, ,
. , , m a in (),
, :
, , ( 7.1).

7,1. , ,
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
const double Pi = 3.14159;
// ()
double Area(double InputRadius);
double Circumference(double InputRadius);

8:

9: int main()
10:

11:
12:
13:
14:
15:
16:
17:
18:
19:

cout "Enter radius: ";


double Radius = 0;
cin Radius;
// "Area"
cout "Area is: " Area(Radius)

// "Circumference"
cout "Circumference is: " Circumference(Radius)

20:

21:

return

0;

22: }
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

endl;

// ()
double Area(double InputRadius)
{
return Pi * InputRadius * InputRadius;
}
double Circumference(double InputRadius)
{
return 2 * Pi * InputRadius;
}

Enter radius: 6 .5
Area is: 132.732
Circumference is: 40.8407

endl;

147

, .
,
,
, . m a in () ,
A re a () C i r c u m f e r e n c e ( ),
16 19 .
, .
(declare) 6 7.
, A r e a C i r c u m f e r e n c e ,
m a in ().
A re a () C i r c u m f e r e n c e () (invoke) m a in ()
16 19.
A r e a () (define) 2 5 -3 8 , C i r c u m f e r
e n c e () 30-33.


6 7 7.1:
double Area(double InputRadius);
double Circumference(double InputRadius);

. 7.1.

double Area(double InputRadius);

(),
,

(),

. 7.1.
( A re a),
( d o u b le I n p u
t R a d iu s ) ( d o u b le ) .
16 19 m a in ()
, A re a C i r c u m f e r e n c e .
, A r e a C i r c u m f e r e n c e ,
d o u b le d o u b le .
,
,
.

148

7.

,
, .
, ,
void ().


(im plem entation),
(definition). A re a :
25: double Area(double InputRadius)
26: {
27:
return Pi * InputRadius * InputRadius;
28: }

. r e t u r n
, v o id .
A re a r e t u r n ,
v o id . (statem ent
block) ( { . . . ) ) ,
. A re a () I n p u t R a d i u s ,
, .


(function call).
, , (param eter),
(argum ent), ,
. A re a () 7.1:
16:

cout

"Area is: " << Area(Radius) << endl;

A re a ( R a d iu s ) ; R a d iu s ,
A re a (). A re a ( ) ,
. ,
d o u b le , c o u t .


, , ,
. 7.2.

. 7.2.

149

:
= + +
+
= Pi * RadiusA2 + Pi * Radius A2 + 2 * Pi * Radius * Height
= 2 * Pi * RadiusA2 + 2 * Pi * Radius * Height

,
.
.
, 7.2.

7.2. ,
* ______________________________________
I: #include <iostream>
1: using namespace std;
2: const double Pi = 3.14159;
5: //
2: double SurfaceArea(double Radius, double Height);
5: int main ()

?: (
II:
11:
11:
12:
14:
15:

cout
double
cin
cout
double
cin

"Enter the radius of the cylinder: ";


InRadius = 0;
InRadius;
"Enter the height of the cylinder: ";
InHeight = 0;
InHeight;

1~:

cout

12:

return 0;

"Surface Area: "


endl;

SurfaceArea(InRadius, InHeight)

22: }
12: double SurfaceArea(double Radius, double Height)

23: {
14:
15:

double Area = 2 * Pi * Radius * Radius + 2 * Pi * Radius \


* Height;
return Area;

Enter the radius of the cylinder: 3


Enter the height of the cylinder: 6.5
Surface Area: 179.071

6 S u r f a c e A r e a () : R a
d i u s H e i g h t , d o u b l e . 2 2 -2 6

7.

150

, .. S u r f a c e A r e a ( ) . ,
R a d iu s H e i g h t A re a ,
.

.
. , Radius Height Surface
Area () 7.2
SurfaceArea (), .



" H e l l o W o rld " ,
, (
, " H e l l o W o rld " ),
( ).
7.3.

7.3. _____________________
0:
1:
2:
3:
4:
5:
6:

#include <iostream>
using namespace std;
void SayHelloO;
int main()

7:
8:
9: }

SayHelloO;
return 0;

10:

11: void SayHelloO


12: {

13:
14: }

cout

"Hello World"

endl;

Hello World

3 S a y H e ll o
v o id , .. . ,
( 11-14) . 7
m a in ()
, .

151



.
. ,
,
, ?
A re a ()

; default value). A re a () 7.1 :
double Area(double InputRadius, double Pi = 3.14);

P i
3,14. (optional
param eter) . ,
A re a ( ), :
Area(Radius);

,
3,14.
, , A re a () :
Area(Radius, Pi); // Pi

7.4 ,
,
.

7.4. ,
3 ,1 4 ______

#include <iostream>
using namespace std;
// ()
double Area(double InputRadius, double Pi = 3.14); // Pi
//
int main ()
3:
9:
13:

cout "Enter radius:


double Radius = 0;
cin Radius;

";

12:
13:
14:

cout "Pi is 3.14, do you wish to change this (y / n)? ";


char ChangePi = 'n';
cin ChangePi;

15:
16:
17;
18:
19:
13:

double CircleArea = 0;
if (ChangePi == 'y')
{
cout "Enter new Pi: ";
double NewPi = 3.14;

152
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

7.
cin NewPi;
CircleArea = Area (Radius, NewPi);
}
else
CircleArea = Area(Radius); // 2- ,
// ,
// "Area"
cout "Area is: " << CircleArea endl;
return 0;
}
//
double Area(double InputRadius, double Pi)
{
return Pi *InputRadius * InputRadius;
}

Enter radius: 1
Pi is 3.14, do you wish to change this (y / n)? n
Area is: 3.14

:
Enter radius: 1
Pi is 3.14, do you wish to change this ( / )?
Enter new Pi: 3 .1 4 1 6
Area is: 3.1416


, 1. ,
, . ,
22 25 . 25
, P i,
3,14.

;

.

,
.
(recursive function). ,
,
.

153


,
,
.


, 7.5. , 0 1:
F

( 0 )

F (1) = 1


. , ( >1)
() :
Fibonacci(n) = Fibonacci( - 1) + Fibonacci( - 2)


F (2)
F (3)
F (4)
F (5)
F (6)

=
=
=
=
=

1
2
3
5
8 .

7.5.
___________________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:

#include <iostream>
using namespace std;
int GetFibNumber(int Fiblndex)
{
if (Fiblndex < 2)
return Fiblndex;
else // , Fiblndex >= 2
return GetFibNumber(Fiblndex - 1) \
+ GetFibNumber(Fiblndex - 2);

9: }
10:
11: int main()
12: {
13:
cout "Enter 0-based index of desired Fibonacci Number: ";
14:
int Index = 0;
15:
cin Index;
16:
17:
cout "Fibonacci number is: " GetFibNumber(Index) endl;
18:
return 0;
19: }

Enter 0-based index of desired Fibonacci Number: 6


Fibonacci number is: 8

154

7.

G e tF ib N u m b e r ( ) , 3 -9 , ,
8. ,
5 6; ,
. , ,
F ib ln d e x , ,
.

return
r e t u r n .

, 7.6.
, .
7 .6 . rturn _______________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <iostream>
using namespace std;
const double Pi = 3.14159;
void QueryAndCalculate()
{
cout "Enter radius: ";
double Radius = 0;
cin Radius;
cout

"Area: "

Pi * Radius * Radius

endl;

11:

12:
13:
14: t
15:
16:
17:
18:
19:
20:
21: }

cout "Do you wish to calculate circumference (y/n)? ";


char CalcCircum = n';
cin CalcCircum;
if (CalcCircum ==
return;
cout
return;

n')

"Circumference: "

2 * Pi * Radius

22:
23 : int main ()
24: {
25:
QueryAndCalculate
26:
27:
return 0;
28: }

();

Enter radius: 1
Area: 3.14159
Do you wish to calculate circumference (/n)?
Circumference: 6.28319

endl;

155

:
Enter radius: 1
Area: 3.14159
Do you wish to calculate circumference (y/n)? n

Q u e r y A n d C a l c u l a t e () r e t u r n :
17, 20. ,
. ' ',
, r e t u r n .
,
r e t u r n .

.
,
, , .
7.6,
i f ' ':

if (CalcCircum == '')
cout "Circumference: "

2 * Pi * Radius

endl;



;
.
, . ,
;
, ,

. ,
.


,
(overloaded
function). ,
,
. ,
, . ,
, . ,
,
. .

156

7.

C ++ , A re a , ,
d o u b le , ,
, 7.7.

7.7.
________________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:

#include <iostream>
using namespace std;
const double Pi = 3.14159;
double Area(double Radius); //
double Area(double Radius, double Height); //
//
int main ()
{
cout "Enter z for Cylinder, c for Circle: ";
char Choice =
'z';
cin Choice;
cout "Enter radius: ";
double Radius = 0;
cin Radius;
if (Choice ==
'z')
{
cout "Enter height:
double Height = 0;
cin Height;

";

// Area
cout "Area of cylinder is: " Area (Radius, Height)
endl;
}
else
cout

"Area of cylinder is: "

Area (Radius)

return 0;
}
//
double Area(double Radius)
{
return Pi *Radius * Radius;
}
//
double Area(double Radius, double Height)
{
//

return 2 * Area(Radius) + 2 * Pi * Radius * Height;
}

endl;

157

Enter z for Cylinder, for Circle: z


Enter radius: 2
Enter height: 5
Area of cylinder is: 87.9646

:
Enter z for Cylinder, c for Circle: c
Enter radius: 1
Area of cylinder is: 3.14159

5 6 A re a ( ),
( ), (
). (A re a )
\ d o u b le ), . , .
3 4 -4 4 ,
: .
, , (
, ) ,
A re a () , 43.


, , :
void Displaylnteger(int Number);

, , :
void Displaylntegers(int[] Numbers, int Length);

, ,
1, , ,
( 7.8).
7 .8 . , ___________________________________

0: #include <iostream>
1: using namespace std;
2:

3: void DisplayArray(int Numbers[], int Length)


4: {
5:
for (int Index = 0; Index < Length; ++Index)
6:
cout Numbers[Index] << " ";

He .
,
,
. s i z e o f ()
. . .

158
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

7.

cout

endl;

}
void DisplayArray(char Characters[], int Length)
{
for (int Index = 0; Index < Length; ++Index)
cout Characters[Index] i t ;
cout

endl;

}
int main()
{
int MyNumbers[4] = {24, 58, -1, 245} r
DisplayArray(MyNumbers, 4);
char MyStatement[7] = {'H ', 'e',
DisplayArray(MyStatement, 7);

11' r

1L1 /
-

10

return 0;
}

24 58 -1 245

Hello!

D i s p l a y A r r a y ():
, . 22 25
,
. ,
( 24) . ,
, c o u t
( c o u t M y S ta te m e n t;) , .


7.1:
24:
25:
26:
27:
28:

// ()
double Area(double InputRadius)
{
return Pi * InputRadius * InputRadius;
}

I n p u t R a d i u s ,
m a in ():
15:
16:

// "Area"
cout "Area is: " << Area(Radius)

endl;

159

, A re a () R a
d iu s m a in ( ) , R a d iu s ,
I n p u t R a d i u s . ,
, ,
, .
(by reference). A re a ( ) ,
, :
// Result
void Area(double Radius, doubles Result)

{
Result = Pi * Radius * Radius;

: A re a () .
(&) R e s u l t .
, ,
. v o id ,
,
.
7.9, .

7.9. ,
#include <iostream>
using namespace std;
const double Pi = 3.1416;
// Result
void Area(double Radius, doubles Result)

{
Result = Pi * Radius * Radius;

}
int main()

{
cout "Enter radius: ";
double Radius = 0;
cin Radius;
double AreaFetched = 0;
Area(Radius, AreaFetched);

13
:

cout "The area is: "


return 0;

id

12

Enter radius: 2
The area is: 12.5664

AreaFetched

endl;

160

7.

17 18, A re a ()
; , .
A re a () , R e s u l t ,
8 A re a ( ) , ,
d o u b le A r e a F e tc h e d , 17 ( m a in ()).
, A re a () ( 8)
m a in () 20.

return, .
, ,
,
,
.



,
, . ,
C ++ ,
.
, , ,
, ,
.
, .
CALL,
, .
r e t u r n
RET.
CALL,
, , ,
CALL.
, .
, RET (
r e t u r n ). RET
, CALL.
, . ,
, ,
.

16J


(stack) , ,
(Last-In-First-Out LIFO), ,
, .
(push),
(pop).
, (. 7.3).

3
2


( ,


)

. 7.3. ,

.
, ..
. ,
, .


CALL,
..
, ,
, ?
double GetPiO

{
return 3.14159;

}

,
G e t P i ( ) . C ++
(inline). i n l i n e <
.
inline double GetPiO

{
return 3.14159;

}
,
, .
7.10.

6 . 3626

162

7.

7.10. ,
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
//
inline long DoubleNum (int InputNum)
{
return InputNum * 2;
}

8:

9: int main()

10:

11:
12:
13:
14:
15:
16:
17:
18:
19: }

cout "Enter an integer: ";


int InputNum = 0;
cin InputNum;
//
cout "Double is: " DoubleNum(InputNum)

endl;

return 0;

Enter an integer: 35
Double is: 70

, i n l i n e , 4. ,
,
D oubleN um () ( 16),
.
,

. i n l i n e
, ,
, .
C++
. ,
Microsoft C++ Compiler,
.
, , ,
.
, .

(, ) ,
.

163

++11
-
.
, , .
- 22, - ++1 \
- , STL
, , , STL,
s t d : : v e c t o r ( ). ,
, ,
. , ++11,
- , 7.11.

7.11. -
________________________________________________
0:
1:
2:
3:
4:
5:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void DisplayNums(vector<int>& DynArray)

6:

7:
8:
9:
10:

for_each (DynArray.begin(), DynArray.end(), \


[](int Element) {cout Element " ";} );//
cout

endl;

11: }
12:

13: int main()


14: {
15:
vector<int> MyNumbers;
16:
MyNumbers.push_back(501);
17:
MyNumbers.push_back(-1);
18:
MyNumbers.push_back(25);
19:
MyNumbers.push_back(-35);

20:

21:

DisplayNums(MyNumbers);

23:
24:
25:
26:
27:
28:
29:
30:
31: }

cout

22:

"Sorting them in descending order"

endl;

sort (MyNumbers.begin(), MyNumbers.end(), \


[](int Numl, int Num2) {return (Num2 < Numl); } );
DisplayNums(MyNumbers);
return 0;

164

7.

501 -1 25 -35
Sorting them in descending order
501 25 -1 -35

,
C++ s t d : : v e c t o r ( 5 -19). D i s p l a y Nums () STL
. 8 -.
25 ( 26)
-, t r u e , ,
.
- :
[ ] ( ) { ; }

, ,
,
. ,
, ,
, ,
. , ,
,
.
, - . + + 11 ,
C++, STL.


, ?
. ,
, w h ile ( t r u e ) f o r ( ; ; ) ;
,
.

?
, ?
.
,
. ,
, .

165

?
, , .
, A r e a . ,
. , f l o a t , d o u b le .

?

. ,
.


, ,
. ,
, .
,
.


1. , ?
2. , ?
int Func(int &SomeNumber);

3. , . ?
4. ,
. ?
5. , ?

1. , .
:
= (4 * Pi * * * ) / 3
= Pi * * *

2. , d o u b le .
3. : ?
#include <iostream>
using namespace std;
const double Pi = 3.1416;
void Area(double Radius, double Result)

{
Result = Pi * Radius * Radius;

7.

166

int main()

{
cout "Enter radius:
double Radius = 0;
cin Radius;
double AreaFetched = 0;
Area(Radius, AreaFetched);
cout "The area is: "
return 0;

AreaFetched

endl;

}
4. : ?
double Area(double Pi = 3.14, double Radius);

5. v o id ,

.


C++ ,
,
, , ,
. , C++

.
,
.
.

new delete
.

,
.

, .

168

8.


, , (pointer) ,
. i n t
,
(. 8.1).


0x101
0x558


0x558
0x558

0x101

. 8.1.
, , , ,
( . 8.1 0x101).
, ( 0x558)
. , ,
.

, .
, (, i n t ) .
, ,
. (
(void pointer)).
, :
* ;

, ,
.
, NULL. NULL ,
:
* = NULL; //

, :
int *plnteger = NULL; //

,
, .
,
.
,
.

169


(&)
, .
> 3, ,
. , ,
.
V arN am e , &VarName ,
\? .
, ,
::
int Age = 30;

& , (3 0 ).
8.1 ,
.

8.1. int double_____________________


1 : #include <iostream>
1: using namespace std;
3: int main()
4: {
3:
int Age = 30;
6:
const double Pi =3.1416;
3:
9:
ID:

// &
cout "Integer Age is at: Ox" hex &Age endl;
cout "Double Pi is located at: Ox" hex &Pi endl;

12:
33: }

return 0;

Integer Age is at: 0x0045FE00


Double Pi is located at: 0x0045FDF8

, (&) 9 10
P i.
, .

, , ,
. sizeof () 3.4 ,
4 (
). ,
,
0x0045FE08, , sizeof (int) 4 ,
, , 0x0045FE000x0045FE04, .

170

8.

(referencing operator) (&)


(address-of operator).


, , ,
, .
,
(&).
:
//
= ;

,
, (&):
//
* = &;

, i n t :
int = 30;

i n t ,
, :
int* plnteger = &; //

8.2 ,
(&).
8.2. _______________________________
0: #include <iostream>
1: using namespace std;
2:

3: int main()
4: {
5:
int Age = 30;
6:
int* plnteger = &Age; // int,
7;
// &Age
8:
//

9:
cout "Integer Age is at: Ox" hex plnteger endl;
10:
11:
return 0;
12: }

Integer Age is at: 0x0045FE00

171

, , ,
, . , ( 6),
2 ( 9) () c o u t .

, , .
.

, , ,
,
, 8.3.
8.3. ________________________________
D: #include <iostream>
1: using namespace std;
2:

3: int main()

4: {
5:

int Age = 30;

6:
7:
8:
9:
10:
11:

int* plnteger = &Age;


cout "plnteger points to Age now"

13:
14:
15:
16:
17:
18:
19:

int DogsAge = 9;
plnteger = &DogsAge;
cout "plnteger points to DogsAge now"

//
cout "plnteger = Ox" hex plnteger

12:

20:

endl;

cout

"plnteger = Ox"

hex

endl;

endl;

plnteger

endl;

return 0;

plnteger
plnteger
plnteger
plnteger

points to Age now


= 0x002EFB34
points to DogsAge now
= 0x002EFBlC

, p l n t e g e r
. 7
&. ,
. 14 &DogsAge,

172

8.

, DogsAge.
, , ,
, D ogsA ge.
, , , 0x002E FB 34 0 x 0 0 2 E F B lC
.


(*)
, , .
,
? (de-referencing operator) (*).
, p D a ta , * p D a ta
, ,
. (*) 8.4.
8 .4 .
(*) ______________________

0
1

#include <iostream>
using namespace std;

int main()

4
5
6
7

{
int Age = 30;
int DogsAge = 9;

cout
cout

9
10
11
12
13
14
15
16
17
18
19
20

int* plnteger = &Age;


cout "plnteger points to Age"

endl;

endl;

//
cout "plnteger = Ox" hex << plnteger

endl;

//
cout "*plnteger = " dec *plnteger

endl;

plnteger = &DogsAge;
cout "plnteger points to DogsAge now"

21

22
23
24
25
26
27

"Integer Age = " Age endl;


"Integer DogsAge = " DogsAge

cout
cout

endl;

"plnteger = Ox" hex plnteger << endl;


"*plnteger = " dec *plnteger endl;

return 0;

Integer Age = 30
Integer DogsAge = 9
plnteger points to Age

173

plnteger = 0x0025F788
*plnteger = 30
plnteger points to DogsAge now
plnteger = 0x0025F77C
*plnteger = 9

, , (.
8.3), (*)
p l n t e g e r . 18 24.
,
p l n t e g e r , (*).
, p l n t e g e r , 20,
D ogsA ge 9.
(*),
4 ,
( i n t s i z e o f ( i n t )
4). , , ,
. &
11 , .
, ,
.
A c c e s s V i o l a t i o n (
), ,
.
(*)
(indirection operator).

()
, . 8.5 ,
, * p l n t e g e r 1-, ..
, .

8.5.
(*)_____
0
1

#include <iostream>
using namespace std;

int main()

4
5

int DogsAge = 30;


cout "Initialized DogsAge = "

DogsAge

int* pAge = &DogsAge;


cout << "pAge points to Dog'sAge"

endl;

7
8

10
11

cout

"Enter an age for your dog: ";

endl;

174

8.

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22: }

// ,
cin *;
// ,

cout "Input storedusing


pAge at Ox" hex
cout

"Integer DogsAge = "

dec

DogsAge

pAge

endl;

endl;

return 0;

Initialized DogsAge = 30
pAge points to DogsAge
Enter an age for your dog: 10
Input stored using pAge at 0x0025FA18
Integer DogsAge = 10

14,
, pA ge. , ,
pA ge, 19
D ogsA ge. ,
D ogsA ge, 8.
, D ogsA ge,
, .


size o f () ?
, ,
. , , ,
. ,
; . ,
s i z e o f ()
, , ,
, 8.6.

8.6. _________________
0:
1:
2:
3:
4:
5:
6:
7:
8:

#include <iostream>
using namespace std;
int main()
{
int Age = 30;
double Pi = 3.1416;
char SayYes = ' ';

175

//
int* pint = &Age;
double* pDouble = &Pi;
char* pChar = &SayYes;
cout
cout
cout
cout

"sizeof fundamental types


endl;
"sizeof(int) = " sizeof(int) endl;
"sizeof(double) = " sizeof(double) endl;
"sizeof(char) = " sizeof(char) endl;

cout
cout
cout
cout

"sizeof pointers to fundamental types -" endl;


"sizeof(pint) = " sizeof(pint) endl;
"sizeof(pDouble) = " sizeof(pDouble) endl;
"sizeof(pChar) = " sizeof(pChar) endl;

return 0;

sizeof fundamental types sizeof (int) = 4


sizeof(double) = 8
sizeof(char) = 1
sizeof pointers to fundamental types sizeof(pint) = 4
sizeof(pDouble) = 4
sizeof(pChar) = 4

, , s i z e o f ( c h a r ) 1
5, a s i z e o f ( d o u b le ) 8 ,
- . , , ,
, , 1 8 .
8.6 , 4 ,
.
32- . 64-
64- ,
64 , .. 8 .


, ,
int Numbers[100]; // 100
.

1. ,
100 .

176

8.

2. ,
1 , 100 .
,
, .
,
,
. ,
. C ++ , new
d e l e t e ,
. , , ,
.

n e w d e l e t e


new () .
new,
, .
new ,
:
* = new ; //

,
( ):
* = new []; //

, ,
:
int* pNumber = new int;
int* pNumbers = new int[10];

//
// 10
//

, new
. , ,
.

, new,
( ) d e l e t e :
* = new ;
delete ; // ,
//

:
* = new [];
delete[] ; //

177

delete []
new [.. . ] delete
new.

,

. , , ,
, ,
. , .
8.7 .

8-7. (*) ,
new, delete
3: #include <iostream>
using namespace std;
2:

3: int main()
4: {
5:
// int
6:
int* pAge = new int;

7:
3:
:
13:

//
cout "Enter your dog's age: ";
cin *pAge;

11:

12 :
13:
14:
15:
16:
17:

// *
//
cout "Age " *pAge " is stored at Ox" hex
endl;

pAge

delete pAge; //
return 0;

13: }

Enter your dog's age: 9


Age 9 is stored at 0x00338120

6 new
, .
, new ,
.
, c i n 10, *.
13 , (*),
, .
pAge 13 , new
6, .

178

8.

delete ,
, , ,
new delete.
, 8.6
, delete,
new.

----------------------------------------------------------------------- ---------------------------- ,
n e w .
, d e l e t e [ ],
8.8.

8.8. new [... ]


delete []_____________
0: #include <iostream>
1: #include <string>
2 : using namespace std;

3:
4: int main()
5: {
cout "Enter your name: ";
6:
7:
string Name;
cin Name;
8:
9:
10:
// 1
//
int CharsToAllocate = Name.length() + 1;
11:
12:
//
13:
char* CopyOfName = new char [CharsToAllocate];
14:
15:
// strcpy
16:
17:
strcpy(CopyOfName, Name.c_str());
18:
//
19:
cout "Dynamically allocated buffer contains: " CopyOfName
20:
endl;
21:
// ?
22:
delete[] CopyOfName;
23:
24:
return 0;
25:
26: }

Enter your name: Siddhartha


Dynamically allocated buffer contains: Siddhartha

179

23, new d e _ e t e [ ] . 8.7,


, .

d e l e t e [ ] , .
11 ,
, ,
N U LL , .
NULL 4, .
17 s t r c p y , c _ s t r ()
::, s t d : : s t r i n g ,
IcpyOfName.

new delete .
(free store) - ,

(allocate) (..
(reserve) ) (de-allocate) (.. (release)).


(++ -)
. ,
8.3 0 x 0 0 2 E F B 3 4 ,
. 4 , ,
0 x 0 0 2 E F B 3 4 0 x 0 0 2 E F B 3 7 .
(++) 0 x 0 0 2 E F B 3 5 ,
, .
( )

, , , (
1 , , c h a r ) .
, , p l n t e g e r 8.3,
. 4 , i n t .
++ ,
. ,
0 x 0 0 2 E F B 3 8 . 2
2 , 8 .
, ,
, .
( - )
, , ,
.

8.

180

?

{ ). , ,
,
, .
:
* * ;

++ , ( )
+ s i z e o f {).

8.9 .

8.9. ,
++_____________
0
1

#include <iostream>
using namespace std;

3
4
5
6

int main()
cout "How many integers you wish to enter? ";
int InputNums = 0;
cin InputNums;

10

int* pNumbers = new int [InputNums]; //


//
int* = pNumbers;

11
12

13
14
15
16
17
18
19
20

21

cout"Successfully allocated memory for "<<InputNums


" integers" endl;
for(int Index = 0; Index < InputNums; ++Index)

{
cout "Enter number " Index
cin * (pNumbers + Index);

": " ;

}
cout "Displaying all numbers input: "
for(int Index = 0, int* pCopy = pNumbers;
Index < InputNums; ++Index)
cout * (pCopy++) " ";

endl;

22

23
24
25
26
27
28
29

cout

endl;

// ?
delete[] pNumbers;
return 0;

181

How many integers you wish to enter? 2


Successfully allocated memory for 2 integers
Enter number 0: 789
Enter number 1: 575
Displaying all numbers input:
789 575

:
How many integers you wish to enter? 5
Successfully allocated memory for 5 integers
Enter number 0: 789
Enter number 1: 12
Enter number 2: -6 5
Enter number 3: 285
Enter number 4: -101
Displaying all numbers input:
789 12 -65 285 -101

,
, 9.
, 10,
d e l e t e 26.

.
, ; ,
, .
,
. 13-17
f o r , , , 16,
, .
( I n d e x ) ,
,
. , (pN um ber + I n d e x )
(.. 1
), , * (pN um ber +
In d e x ) , c i n
. f o r 20 21
, .
21, , f o r
.
10 , ,
(++). , new,
d e l e t e [ ] ( 26),
, new,
.

182

8.

const
3, , , ,
c o n s t ,
.
, 1-.
, , c o n s t
. ,

. , ,
.
, ,
, , , (..
):
int HoursInDay = 24;
const int* plnteger = &HoursInDay; //
//
int MonthsInYear = 12;
plnteger = &MonthsInYear;
*plnteger =13;

plnteger
HoursInDay

// OK!
// :
//
int* pAnotherPointerToInt = plnteger; // :
//

,
, , :
int DaysInMonth = 30;
// plnteger
int* const pDaysInMonth = &DaysInMonth;
*pDaysInMonth = 31;
// OK!
int DaysInLunarMonth = 28;
pDaysInMonth = &DaysInLunarMonth; // :
// !

, , ,
( ):
int HoursInDay = 24;
// HoursInDay
const int* const pHoursInDay = SHoursInDay;
*pHoursInDay .= 25;
// :
// ,
int DaysInMonth = 30;
pHoursInDay = &DaysInMonth; // :
//


. ,
( ) ,
, , .
,
, .

183


,
. 1 ,
, , . , ,
, , .
, ,
, ( 8.10).

8.10. const
~ , ___________________________

I: #include <iostream>
1: using namespace std;
2: void CalcArea(const double* const pPi,
//
4:
const double* const pRadius, // ,
// ..
5:
double* const pArea) // ,

t:

{
// !
if (pPi && pRadius && pArea)
*pArea = (*pPi) * (*pRadius) * (*pRadius);

5:
2:

ii:

II: int main()

12: {
14:

const double Pi = 3.1416;

I.':
I:

cout "Enter radius of circle: ";


double Radius = 0;
cin Radius;

II:
II:

double Area = 0;
CalcArea (&Pi, &Radius, &Area);

12:

cout

15:

return 0;

"Area

is = " Area

endl;

I-': }

Enter radius of circle: 1 0 .5


Area is = 346.361

3 -5 , , p R a d iu s
p ? i , ,
>, , , . p A re a ,

184

8.

, , .
() , , , .
7
. , , , ,

, .


, 8.9,

, ?
:
int MyNumbers [5];


,
, . , MyNumbers
MyNumber [ 0 ]. 8.11 .
8 .1 1 . ,
_________

0
1

#include <iostream>
using namespace std;

int main()

4
5

{
// 5
int MyNumbers[5];

7
8

// int
int* pNumbers = MyNumbers;

9
10

// ,
cout "pNumbers = Ox" hex pNumbers endl;

11
12

13
14
15
16
17
18

//
cout "&MyNumbers[0] = Ox" hex
return 0;

pNumbers = 0x004BFE8C
&MyNumbers[0] = 0x004BFE8C

&MyNumbers[0]

endl;

185

,
(. 9), , ,
. 12 15 ,
,
( 0). ,
.
, M yN um bers [ 1 ] ,
p N u m b e rs * (p N u m b ers + 1 ) .
, M yNumbers [ 2 ] ,

* (pN um bers + 2 ).
, , ,
(*),
.
| ; ]) , 8.12.
8 .1 2 .
(*) ([ ]) ____________

: #include <iostream>
1: using namespace std;

2:
3: int main()
4 {
3:
const int ARRAY_LEN = 5;
":
3:

// 5
int MyNumbers[ARRAY_LEN] = {24, -1, 365, -999, 2011};

9.
13:

11:
13:
14:
15:

/ / ,
int* pNumbers = MyNumbers;

cout "Displaying array usingpointer


syntax,operator*"
endl;
for (int Index = 0; Index < ARRAY_LEN; ++Index)
cout << "Element " Index " = " * (MyNumbers + Index)
endl;

16:
1:

18:
19:

cout <<
"Displaying array using pointer with array syntax, operator[]"
endl;
for (int Index = 0; Index < ARRAY_LEN; ++Index)
cout "Element " Index " = " pNumbers[Index]
endl;
return 0;

186

8.

Displaying array using pointer syntax, operator*


Element 0 = 24
Element 1 = -1
Element 2 = 365
Element 3 = -999
Element 4 = 2011
Displaying array using pointer with array syntax, operator[]
Element 0 = 24
Element 1 = -1
Element 2 = 365
Element 3 = -999
Element 4 = 2011

,
8.
, :
(*) 15,
([ ]) 19.
, , M yNumbers,
p N u m b ers . ,

. , , 11,
, ,
, 1-.
, ,
new, delete,
, .
, , .



C++ ,
. ,
C# Java, , C ++
,
, . ,
.

187


, C++:
, . ,
, ,
, new,
d e l e t e .
, .. ,
. - :
int* pNumbers = new int [5]; //
// pNumbers
// delete[] pNumbers;
//
pNumbers = new int[10]; //



(*) ,
, 100% ,
, .
,
. ,
. ,
, 8.13.
8 .1 3 .
_________________________________________________

3: tinclude <iostream>
1: using namespace std;

2:
3: int main()
4: {
5:
// ()
6:
int* pTemperature;
7:
8:
cout "Is it sunny (y/n)?" endl;
9:
char UserInput = 'y';
10:
cin Userlnput;
11:
12:
if (Userlnput== ' ')
13:
{
14:
pTemperature = new int;
15:
*pTemperature = 30;
16:
}
17:
18:
// pTemperature ,
// ' '

188
19:
20:
21:

8.
cout

22:
23:
24:
25: }

"Temperature is: "

*pTemperature;

// delete
// new
delete pTemperature;
return 0;

Is it sunny (y/n)?
Temperature is: 30

:
Is it sunny (y/n)? n
<!>

, .
, 14
i f , , .. ,
, <>.
i f , p T e m p e r a tu r e . ,
<>,
, p T e m p e r a tu r e
19 .
d e l e t e 22 ,
new, .
, , , d e l e t e
( ).
( ) 8.13
,
.

( )
,
d e l e t e . , p T e m p e r a tu r e
22, , <>
, d e l e t e
.
,
N U L L , , ,

(*).

189



,
, .


,
.
,
.

,
new ,
NULL


,
delete
delete

,
delete

NULL
. ,
,
(
NULL),
( 8.13)
,
,

,
new,
delete,

_, 8.13
:, 8.14.
8.14. , 8.13________________
1: #include <iostream>
1: using namespace std;
:: int main()

4: {
::
:

cout << "Is it sunny (y/n)?


char Userlnput = ' 1;
cin >> Userlnput;
if (Userlnput == 'y')

190

8.

11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

// ()
int* pTemperature = new int;
*pTemperature = 30;
cout

"Temperature is: "

*pTemperature << endl;

// ?
delete pTemperature;

}
return 0;
}

Is it sunny (y/n)?
Temperature is: 30

:
Is it sunny (y/n)? n
( )

,
(.. <>)
(. 12). ,
( d e
l e t e ) , .


new
new ,
,
. ,
( , ), , ,
. C ++
.
.
s t d : : b a d _ a l l o c .
u n h a n d l e d e x c e p t i o n ( ),
(exception handler).
28,
. 8.15
.

191

8.15.
new______________________________________
0: #include <iostream>
1: using namespace std;
2:

3: int main()

4: {
5:

try

6:

:
3:

//
int* pAge = new int [536870911];

:
10:

//

12:

delete[] pAge;

13:

14:
'-5:
16:

catch (bad_alloc)
{
cout "Memory allocation failed. Ending program"

l*7:

13:

return 0;

endl;

1: }

Memory allocation failed. Ending program

-.
536870911 .
( c a t c h , 14-17)
. M icrosoft Visual Studio
, . 8.2.

. 8.2.
8.15 ( MSVC)

192

8.

,
, .
( W indow s) ,
. 8.3.
' 81 5 Po<nter$rftew_exceptionhandler.exe
8.15 Pointers_new_exceptionhandier.exe has
stopped w orking
A problem caused the program to stop working correctly.
Windows will close the program and notify you if a solution is
available.

lose program

. 8.3.

8.15 ( )
, ,
, .

,
.
new, new ( n o t h r o w ) ,
, N U L L ,
, ( 8.16).

8.16. new (nothrow),


NULL___________
0
1

#include <iostream>
using namespace std;

int main()

{
// nothrow
int* pAge = new(nothrow) int [Oxlfffffff];

6
7

11

if (pAge) // pAge != NULL


{
//
delete[] pAge;

13

else

10

12

}
cout

14
15

return 0;

16
17

"Memory allocation failed. Ending program"

endl;

193

Memory allocation failed. Ending program

, new ( n o th r o w ) ,
N U LL , s t d : :b a d _
=11, 8.15. , .


(reference) .
. ,
, .
(&), :
VarType Original = Value;
VarType& ReferenceVariable = Original;

, ,
8.17.

8-17, ,
" _____________________________________________________

: tinclude <iostream>
1: using namespace std;
5: int main()

4: {
5:
5:

int Original = 30;


cout << "Original = " Original endl;
cout "Original is at address: " hex

&Original

5:
'.I:

int& Ref = Original;


cout "Ref is at address: "

_i:
15:
14:

int& Ref2 = Ref;


cout "Ref2 is at address: " hex &Ref2 endl;
cout "Ref2 gets value, Ref2 = " dec Ref2 endl;

15:
1

":

return 0;
}

Original = 30
Original is at address: 0044FB5C
Ref is at address: 0044FB5C
Ref2 is at address: 0044FB5C
Ref2 gets value, Ref2 = 30

~ 3ak. 3626

hex

&Ref

endl;

endl;

194

8-

, , ,
, 9, ,
12, , .
, , .. O r i g
i n a l . R e f 2 14
, O r i g i n a l 6,
R e f 2 O r i g i n a l .


, .
.
7, , :
{ );

() :
= { ); //

,
().
, .
, () , .
, ,
.
.
:
{ ); // &

:
= { );

, ,
, R e f 8.17. , ,
, , .
8.18, ,
.

8.18.
0:
1:
2:
3:
4:
5:
6:
7:
8:

#include <iostream>
using namespace std;
void ReturnSquare(int& Number)
{
Number *= Number;

195

: int main ()

{
_:
1:
::

cout "Enter a number you wish to square: ";


int Number = 0 ;
cin Number;

::

ReturnSquare(Number);
cout "Square is: "

::

Number

endl;

return 0;

Enter a number you wish to square: 5


Square is: 25

, , 3 -6 .
= , 51 . N um ber (&),
m a in ( ), R e tu r n S q u a r e () N um ber,
. , R e tu r n S q u a r e ()
, N um ber m a in ( ).
, m a in () , R e u r n S q u a r e () .
, ,
. , ,
: , .

const
,
. c o n s t :
int Original = 30;
const int& ConstRef = Original;
ConstRef = 40;

//
//
int& Ref2 = ConstRef;
//
const int& ConstRef2 = ConstRef; //

: ConstRef
Original
: Ref2 const
OK


,
, ,
.
, ,

196

8.


. , c o n s t ,
, 8.19.
1-,
.

8.19.
, _______________________
0: #include <iostream>
1: using namespace std;
2:
3: void CalculateSquare(const int& Number, int& Result)
// , "const"
4: {
5:
Result = Number*Number;
6: }
7:
8: int main()
9: {
10:
cout "Enter a number you wish to square: ";
11:
int Number = 0;
12:
cin Number;
13:
14:
int Square = 0;
15:
CalculateSquare(Number, Square);
16:
cout Number "A2 = " Square endl;
17:
18:
return 0;
19: }

E n t e r a n u m b e r y ou w is h t o

sq u a re :

27

2 7 A2 = 7 2 9

,
, : ,
, .

c o n s t (. 3). N um ber
(input param eter), .
5 , ,
, 8.18:
N um ber *= N um ber;
, ,
. , ,
C++, ,
.

197

, ,
, , ,
.

.
, ,
. new
d e l e t e , ,
- ew . . . [ ] d e l e t e [ ], .

, ,
. ,
,
.
, ,
.


,
?
; ,
,
, .
.

:
int* pNumber = new int;
int* pCopy = pNumber;

, ,
?
. d e l e t e
, new. ,
, d e l e t e
.
.

new (n o th ro w ) ?
s t d : r b a d a l l o c ,
n o th r o w new, N U LL
.

,
:
void CalculateArea (const double* const pRadius, double* const pArea);
void CalculateArea (const doubles radius, doubles area);

198

8.

?
, ,
. , .

:
int Number = 30;
const int* pNumber = &Number;

, Number, ^Number,
. pNum
b er ,
, Number?
, :
int* pAnother = pNumber; //
//

?
, .
( ),
.
. c o n s t ,
.

:
int MyNumbers[100];
int* MyArrays[100];

MyNumbers , .. M yNumbers
, ( 0) 100 .
:
int* MyNumbers = new int [100]; //
// MyNumbers
delete MyNumbers;

MyAr r a y s , , 100 ,
.


, ,
. ,
, .
,
.


1. ?
2. new d e l e t e ?

199

3. , ?
4. , ?

1. :
0:
1:
2:
3:
4:
5:

int Number = 3;
int* pNuml = &Number;
_*pNuml =20;
int* pNum2 = pNuml;
Number *= 2;
cout *pNum2;

2 / :
int DoSomething(int Numl, int Num2);
int DoSomething(int& Numl, int& Num2);
int DoSomething(int* pNuml, int* pNum2);

3. pNuml 1 1,
3 ? (:
,
pNum l.)
4. : ?
#include <iostream>
using namespace std;
int main()

{
int *pNumber = new int;
pNumber = 9;
cout "The value at pNumber: "
delete pNumber;
return 0;

*pNumber;

}
5. : ?
#include <iostream>
using namespace std;
int main()

'
int pNumber = new int;
int* pNumberCopy = pNumber;
*pNumberCopy = 30;
cout *pNumber;
delete pNumberCopy;
delete pNumber;
return 0;

}
6. ?

II

C + +

9.
10.
11.
12.
13.
14.


,
main (),
, ,
,
. ,
3. . ,
, .
.

(
) .

, .

++11
.

-
.

this.

204

9.


, , , .
: , , .
,
. , ,
(. 9.1).

(Gender)
(Date of birth)
(Place of birth)
(Name)

() (lntroduceSelf())

. 9.1.
, ,
, (), , (
, ), .
(class).


c l a s s ,
{ . . . } ,
, .
.
. ,
, .
(
):
class Human

{
// :
string Name;
string DateOfBirth;
string PlaceOfBirth;
string Gender;

205

// :
void Talk(string TextToTalk);
void IntroduceSelf();

, I n t r o d u c e S e l f () T a l k ()
, c l a s s Human. , c l a s s C++
,
. , Name, D a t e O f B i r t h , P l a c e O f r i r t h G e n d e r, , T a l k () I n t r o d u c e S e l f ( ) ,
(m em bers o f class) Human.
(encapsulation) ,
; -
.
(method) - , , , .


,
. ,
, (object).
, .
Human ,
, , d o u b le :
double Pi = 3.1415; // double
Human Tom;
// Human

Human
, new, i n t :
int* pNumber = new int;

//
//
delete pNumber;
//
Human* pAnotherHuman = new Human(); //
// Human
delete pAnotherHuman;
// ,
// Human


(.)
, , 1970 .
Human, .. ,
:
Human Tom; // Human

206

9.

, , Dat e O f B i r t h , , (dot operator) (.):


Tom.DateOfBirth = "1970";

, D a te O f B i r t h Human
, .
, .. , . ( . )
, , I n t r o d u c e S e l f ():
Tom.IntroduceSelf();

Human,
(-> ), ,
(*)
.
Human* pTom = new Human();
(*pTom).IntroduceSelf() ;


(->)
new
,
(pointer operator) (-> ):
Human* pTom = new Human();
pTom->DateOfBirth = "1970";
pTom->IntroduceSelf();
delete pTom;

// :
Human Tom;
Human* pTom = &Tom; // , &
pTom->DateOfBirth = "1970"; // Tom.DateOfBirth = "1970";
pTom->IntroduceSelf();
// Tom.IntroduceSelf();

Human p r i v a t e p u b l i c
9.1.
9.1. Human___________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
string Name;
int Age;
public:


11:

void SetName (string HumansName)

12:

13:

207

Name = HumansName;

14:

16:

void SetAge(int HumansAge)

l7:

13:
19:

Age = HumansAge;

11:

void IntroduceSelf()

22:

13:
14:
15:
16: };

cout
cout

"I am " + Name " and am ";


Age " years old" endl;

13: int main()


2 9: {
1*0:
// Human "Adam"
// Name
21:
Human FirstMan;
32:
FirstMan.SetName("Adam");
23:
FirstMan.SetAge(30);
34:
25:
// Human "Eve"
// Name
26:
Human FirstWoman;
27:
FirstWoman.SetName("Eve");
33:
FirstWoman.SetAge (28);

39 :
40:
41:
42: }

FirstMan.IntroduceSelf() ;
FirstWoman.IntroduceSelf();

I am Adam and am 30 years old


I am Eve and am 28 years old

4 -2 6 C++.
, ,
, .
Human m a in ().
( p r i v a t e ) : s t r i n g
Name 7, i n t 8,
( p u b l i c ) ( (m ethod)): S etN am e ( ) , S e tA g e () I n t r o
d u c e S e l f () 11, 16 21, . 31
36 m a in () Human .
- F i r s t M a n F irs tW o m a n ,

208

9.

SetN am e () S etA g e (), (accessor


m ethod). , 40 41 I n t r o d u c e S e l f ()
, (m em ber variable), .
p r i v a t e p u b l i c 9.1?
, C++, ,
, .

pu blic private
,
, . .
, ,
. .
C++ (
) (
( )). C++ p u b l i c ( ) p r i v a t e
( ) ,
, , m a in (), .
?
Human, , - :
class Human

{
private:
// -:
int Age;
string Name;
public:
int GetAgeO
{
return Age;

}
void SetAge(int InputAge)

{
Age = InputAge;

}
// ...

};
, Human Eve:
Human Eve;


:
cout

Eve.Age; //

E r r o r : H um an: : Age - c a n n o t
a c c e s s p r i v a t e m em ber d e c l a r e d i n c l a s s Human ( : Human: : Age

public private

209

, Human).
G etA g e ( ),
Human
:
cout << Eve.GetAge(); // OK

Human , G etA g e () ,
, ! , , C++
,
. Human G etA g e ( ) ,
.
,
.
H um an: : Age
:
Eve. =22;

//

S e t ():
Eve.Set(22); // OK

. S e t ()
, - Human: :A ge.
S e t () ,
, , :
class Human

{
private:
int Age;
public:
void SetAge(int InputAge)

{
if (InputAge > 0)
Age = InputAge;

}
};
, C++
.

private
, ,
, C ++ p r i v a t e ,
(.. ).
, p u b l i c ,
, . ,
, , ,
( , m a in ( ) ) .

210

9.

- H um an: : Age, ,
,
. Human ,
, G e t ( ) ,
H um an: : , ,
9.2.

9.2. Human,
________________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
class Human
{
private:
// -:
int Age;

8:

9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:

public:
void SetAge(int InputAge)
{

Age = InputAge;
}
// ( 30)
int GetAgeO
{
if (Age > 30)
return (Age - 2);
else
return Age;
}

};
int main()
{
Human FirstMan;
FirstMan.SetAge(35);
Human FirstWoman;
FirstWoman.SetAge(22);
cout
cout

"Age of FirstMan " FirstMan.GetAge() endl;


"Age of FirstWoman " FirstWoman.GetAge() endl;

return 0;
}

Age of FirstMan 33
Age of FirstWoman 22

211

H um an: : G e t A ge () 16.
, -
Human: : Age, ,
Human G e t ().
, , - Human: :A ge,
.
(abstraction) -
13. ,
, (
").

(constructor) ( ),
. , .


,
. , Human ,
:
class Human
{
public:
Human(); //

};
.
) :
class Human
{
public:
Human()

{
//

};

:
class Human
{
public:
Human(); //

};
// ()
Human::Human()

{
//

212

9.

:: (scope resolution
operator). , Human:: DateOfBirth
DateOfBirth, Human. :: DateOf
Birth, , DateOfBirth,
.


.
- ,
, .. 9.2. :
S e t ( ), H um an: :
,
(, , 28 31).
Human, , 9.3
.
9.3. -
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16
17
18
19
20
21

22
23
24
25
26
27
28
29

#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
// -:
string Name;
int Age;
public:
//
Human ()
Age = 0 ;
cout

//
//
"Constructed an instance of class Human"

void SetName (string HumansName)


Name = HumansName;

void SetAge(int HumansAge)


Age = HumansAge;

void IntroduceSelf()

endl;

213

{
1:
2:

cout
cout

2:
4: };

"I am " + Name " and am ";


Age " years old" endl;

6: int main()

{
5:
2:
2:

Human FirstMan;
FirstMan.SetName("Adam");
FirstMan.SetAge(30);

2:
3:
4:

Human FirstWoman;
FirstWoman.SetName("Eve");
FirstWoman.SetAge (28);

6:
~:

FirstMan.IntroduceSelf();
FirstWoman.IntroduceSelf();

Constructed an instance of class Human


Constructed an instance of class Human
I am Adam and am 30 years old
I am Eve and am 28 years old


9.1. m a in ( ) ,
3 6 -4 8 . ,
F i r s t M a n F irs tW o m a n 38 42.
Human,
Human, 13-17. c o u t ,
. ,
. ,
,
( ), ,
H um an: : Age.

, ,
(default constructor).

.
, 9.1,
( - ,
, int).

9.

214


,
, Human,
, :
class Human

{
public:
Human()

{
//

Human(string HumansName)

{
//

}
};
9.4
Human .
9 .4 , Human ___________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10 :
11:
12:
13:
14:
15:

#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
// -:
string Name;
int Age;

public:
//
Human()
{
Age = 0 ; //
//
16:
cout "Default constructor creates an instance of Human"
endl;
17:
}
18:
19:
// , Name
20:
Human(string HumansName)
21:
{
22:
Name = HumansName;
23:
Age = 0 ; //
//
24:
cout "Overloaded constructor creates " Name endl;
25:
}

1:
12:

// , Name
Human(string HumansName, int HumansAge)

12:

2::
21:
21:
22:

Name = HumansName;
Age = HumansAge;
cout "Overloaded constructor creates ";
cout Name " of " Age " years"

34:

26:

void SetName (string HumansName)

endl;

{
22:
22:

Name = HumansName;

41:

void SetAge(int HumansAge)

61 :

42:

Age = HumansAge;

64:

46:

void IntroduceSelf()

4~:

42:
42:

:3 :

cout
cout

"I am " + Name " and am ";


Age " years old" endl;

53: int main ()


54: {
Human FirstMan; //
FirstMan.SetName ("Adam");
FirstMan.SetAge(30);

53
59
60
61
62
63
64
65
66

Human FirstWoman ("Eve"); //


//
FirstWoman.SetAge (28);
Human FirstChild ("Rose", 1);
FirstMan.IntroduceSelf() ;
FirstWoman.IntroduceSelf();
FirstChild.IntroduceSelf();

Default constructor creates an instance of Human


Overloaded constructor creates Eve
Overloaded constructor creates Rose of 1 years
I am Adam and am 30 years old
I am Eve and am 28 years old
I am Rose and am 1 years old

215

216

9.

;
, ,
- H um an: : Name,
,
, - H um an: : Age. ,
,
.

,

.


9.5 Human ,
, .
9 .5 . ,

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
// -:
string Name;
int Age;

10:

11: public:
12:
13:
// ( )
14:
Human(string HumansName, int HumansAge)
15:
{
16:
Name = HumansName;
17:
Age = HumansAge;
18:
cout << "Overloaded constructor creates " Name;
19:
cout " of age " Age endl;
20:
}
21:
22:
void IntroduceSelf()
23:
{
24:
cout << "I am " + Name " and am ";
25:
cout Age " years old" endl;
26:
}
27: };
28
29 int main()

I-1:

217

// ,
//
// Human FirstMan;

;1:
:4:

Human FirstMan("Adam", 30);


Human FirstWoman("Eve", 28);
FirstMan.IntroduceSelf();
FirstWoman.IntroduceSelf();

:::

Overloaded constructor creates Adam of age 30


Overloaded constructor creates Eve of age 28
I am Adam and am 30 years old
I am Eve and am 28 years old

32 m a in () . ,
F i r s t M a n , 9.3, ,
e r r o r : 'H u m a n ' : n o a p p r o p r i a t e d e f a u l t c o n
s t r u c t o r a v a i l a b l e ( : 'H u m a n ' : ).
, Human ,
s t r i n g i n t , 14.
, C++
.
, ,
, ,
Name . 9.5
Name Human
. , Human
s t r i n g Name,
m a in () , Human.
, Human
( ) ,
, ?
; , ( )
.


, ,
.
14 9.5,
25:

218

9.

class Human

{
private:
// -:
string Name;
int Age;
public:
// ( )
Human(string HumansName, int HumansAge = 25)

{
Name = HumansName;
Age = HumansAge;
cout "Overloaded constructor creates "
cout " of age " Age endl;

Name;

}
// ...

};

:
Human Adam("Adam"); // Adam.Age 25
Human Eve("Eve, 18); // Eve.Age 18

- ,
, , .
,
, .

class Human

{
private:
// -:
string Name;
int Age;
public:
//

Human(string HumansName = "Adam", int HumansAge = 25)

{
Name = HumansName;
Age = HumansAge;
cout "Overloaded constructor creates "
cout " of age " Age endl;

Name;

}
};
, Human
:

Human Adam; // Human Name "Adam", Age 25

219


,
.
initialization list). 9.5,
, :
class Human

{
private:
string Name;
int Age;
public:
//
// Name
Human(string InputName, int InputAge)
:Name(InputName), Age(InputAge)

{
cout
cout

"Constructed a Human called " Name;


", " Age " years old" endl;

}
// ...

};
, ( : ) , ( . . . ) ,
- .
, In p u tN a m e ,
.
, 10,
.
9.6 Human,
, , .

9.6. , ,
~ _____________________

I: #include <iostream>
1: #include <string>
1: using namespace std;
4: class Human
:: {
f: private:
int Age;
::
string Name;
.I: public:
LI:
Human(string InputName = "Adam", int InputAge = 25)
11:
:Name(InputName), Age(InputAge)
-3:
{
.4:
cout "Constructed a Human called " Name;
cout ", " Age " years old" endl;

220
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:

9.
}
};
int main()
{

Human
Human

FirstMan;
FirstWoman("Eve", 18);

return 0;
}

Constructed a Human called Adam, 25 years old


Constructed a Human called Eve, 18 years old

1 1 -16,
, "Adam"
- Name 25 - . ,
21 Human F ir s tM a n ,
. F irs tW o m a n , ,
Name , 22.

(destructor), , .
, .


, , ,
(~). , Human ,
:
class Human
{
~Human(); //

};
.
:
class Human
{
public:
~Human()

{
//

221

:
class Human
{
public:
~Human();//

// ()
Human::~Human()

{
//

}
,
, (-).
.



d e l e t e .
: ,
.
s t d : : s t r i n g ,
, ,
. s t d : : s t r i n g
,
, 12,
). M y S tr in g , 9.7,
.
9 .7 . ,
_____________________________________

1: #include <iostream>
1: using namespace std;
5: class MyString
4: {
5: private:
6:
char* Buffer;
-7 .

3: public:
9:
//
13:
MyString(const char* Initiallnput)
1

12:

if(Initiallnput != NULL)

-3:

14:
15:

Buffer = new char [strlen(Initiallnput) + 1];


strcpy(Buffer, Initiallnput);

16:

17:

else
Buffer = NULL;

222

9.

19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:

}
// : ,
//
-MyString()
{

cout "Invoking destructor, clearing up"


if (Buffer != NULL)
delete [] Buffer;

endl;

}
int GetLengthO
{
return strlen(Buffer);
}
const char* GetStringO
{
return Buffer;
}
}; // MyString
int main()
{
MyString SayHello("Hello from String Class");
cout "String buffer in MyString is " SayHello.GetLength();
cout " characters long" endl;
cout
cout

"Buffer contains: ";


"Buffer contains: "

SayHello.GetString()

endl;

String buffer in MyString is 23 characters long


Buffer contains: Hello from String Class
Invoking destructor, clearing up


M y S tr in g : : B u f f e r ,
.
M y S tr in g () 1 0-19 - M y S t r in g ()
21-2 6 . ,
, B u f f e r
14, s t r l e n
.
15 s t r c p y . ,
I n i t i a l l n p u t N U LL,
M y S t r i n g : : B u f f N U L L (
,
).
, ,

223

;. , M y S tr in g : : B u f f e r N U LL,
, d e l e t e [ ], new . , m a in ()
-ew d e l e t e . ,
~ .
- M y S trin g () m a in ( ) ,
, c o u t .
, ,
. 26, ,
,
.

.
. ,
, .. ,
.


7, , ,
A re a () (. 7.1):
double Area(double InputRadius);
, , I n p u t R a d i u s , ,
A re a (). ( ).


, M y S tr in g , , 9.7,
,
, new
d e l e t e [ ].
, , , , ,
. ,
. (shallow
:) , 9.8.

9.8. , , MyString, _____


:: #include <iostream>
1: using namespace std;
2: class MyString
{
5: private:
6:
char* Buffer;
public:

224

9.

9:
10:

//
MyString(const char* Initiallnput)

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:

if(Initiallnput != NULL)
{
Buffer = new char [strlen(Initiallnput) + 1];
strcpy(Buffer, Initiallnput);
}
else
Buffer = NULL;
}
//
~MyString()
{
cout "Invoking destructor, clearing up"
if (Buffer != NULL)
delete [] Buffer;
}

endl;

int GetLengthO
{
return strlen(Buffer);
}
const char* GetStringO
{
return Buffer;
}
};
void UseMyString(MyString Input)
{
cout "String buffer in MyString is "
cout " characters long"
endl;

Input.GetLength();

cout "Buffer contains: " Input.GetString()


return;
}
int main()
{
MyString SayHello("Hello from String Class");
// SayHello
UseMyString(SayHello);
return 0;
}

String buffer in MyString is 23 characters long


Buffer contains: Hello from String Class
Invoking destructor, clearing up
Invoking destructor, clearing up
<, . 9.2>

endl;

225

. 9.2. ,
9 .8 (
V isual Studio)

, 9.6,
9.7? 9.6 9.7 ,
S a y H e l l o M y S t r i n g , m a in (),
U s e M y S t r i n g (), 54.
, S a y H e l l o m a in ()
I n p u t , U s e M y S t r i n g ( ) .
, I n p u t
, . ,
, , . , ,
S a y H e l l o . B u f f e r , I n p u t , ..
, I n p u t . B u f f e r (. 9.3).

. 9.3. SayHello
Input UseMyString ()

(deep )
,
M y S t r i n g , . ,
U s e M y S t r i n g () I n p u t
. M y S t r i n g , 26

: . 3626

226

9.

9.8 d e l e t e ,
. , d e l e t e
, S a y H e ll o ,
m a in ( ) . m a in () , S a y H e l l o
. 26
d e l e t e , (
I n p u t ) .
. , ,
. 9.2, 52 ( 51 ,
), S a y H e llo ,
.

,
, - MyString::Buffer,
.



(copy constructor)
, .
, ,
.
M y S tr in g :
class MyString

{
MyString(const MyString& CopySource); //

MyString::MyString(const MyString& CopySource)

{
//

}
,
. ,
(
), 9.9.
9 .9 . ,
_______________________________

0:
1:
2:
3:
4:

#include <iostream>
using namespace std;
class MyString
{


private:
char* Buffer;
public:
//
MyString(const char* Initiallnput)

{
cout "Constructor: creating new MyString"
if(Initiallnput != NULL)

endl;

{
Buffer = new char [strlen(Initiallnput) + 1];
strcpy(Buffer, Initiallnput);
//
cout "Buffer points to: Ox" hex;
cout (unsigned int*)Buffer endl;

}
else
Buffer = NULL;

}
//
MyString(const MyString& CopySource)

{
cout

"Copy constructor: copying from MyString"

endl;

if(CopySource.Buffer != NULL)

{
// ,
//
Buffer = new char [strlen(CopySource.Buffer) + 1];
//
strcpy(Buffer, CopySource.Buffer);
//
cout "Buffer points to: Ox" hex;
cout (unsigned int*)Buffer endl;

}
else
Buffer = NULL;

}
//
~MyString()

{
cout "Invoking destructor, clearing up"
if (Buffer != NULL)
delete [] Buffer;

}
int GetLengthO

{
return strlen(Buffer);

endl;

227

228
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:

9.
}
const
char*GetStringO
{
return Buffer;
}
};
void UseMyString(MyString Input)
{
cout "String buffer in MyString is
cout " characters long" endl;
cout
return;

"Buffer contains: "

" Input.GetLength();

Input.GetString()

endl;

}
int main()
{
MyString SayHello("Hello from StringClass");
// SayHello ( )
UseMyString(SayHello);
return 0;
}

Constructor: creating new MyString


Buffer points to: 0x0040DA68
Copy constructor: copying from MyString
Buffer points to: 0x0040DAF8
String buffer in MyString is 17 characters long
Buffer contains: Hello from String Class
Invoking destructor, clearing up
Invoking destructor, clearing up

9.8, c o u t ,
, , 27-45.
m a in ( ) , ( )
S a y H e l l o 77. S a y H e l l o
, c o u t 12 M y S trin g .
,
B u f f e r . , 80, m a in () S a y H e ll o
U s e M y S trin g ( ) , ,
. .
,
( 34),

230

9.

const
, , .
, .
, - 1
, !
, .
|


,
(raw pointer) (,
char* ..)



,
std::string,
,

Mystring char* Buffer


.
,
, , std::string,
char*,
. , ,
,
, std::string.

++11

, ,
. :
class MyString
{
// 9.9

};
MyString Copy(MyString& Source)

{
MyString CopyForReturn(Source.GetString());
//
return CopyForReturn; //

231

//

int main()

{
MyString sayHello ("Hello World of C++");
MyString sayHelloAgain(Copy(sayHello)); //
//
return 0;

}
, s a y H e l l o A g a i n
, ,
- Copy ( s a y H e l l o ) ,
.-[-/S trin g .
. , , : C++, , ,
.
,
(m ove constructor).
:
//
MyString(MyString&& MoveSource)

{
if(MoveSource.Buffer != NULL)

{
Buffer = MoveSource.Buffer; // ,
// .. ''
MoveSource.Buffer = NULL; //
// NULL, ..

}
}
, C++11
, ,
.
:
MyString sayHelloAgain(Copy(sayHello)); // 1 ,
// 1


(m ove assig n m en t operator), 12,
. M y S tr in g ,
,
12.11.

232

9.



, ,
, ,
p u b l i c p r i v a t e . ,
, , .
,
.

,
, .
. P r e s i d e n t :
President OurPresident;
DoSomething(OurPresident); // ,
//
President clone;
clone = OurPresident;
//

, . ,
,
, .. ,
. , C++
.
. .
,
. , D o S o m e th in g ( O u r P r e s i d e n t )
. ,
.
, :
class President

{
private:
President(const Presidents);
//
Presidents operator= (const Presidents); //
//
// ...

};

. P r e s i d e n t
.

233

,

P r e s i d e n t , :
:
President One, Two, Three;

,
P r e s i d e n t ,
. (singleton),
,
4 (
:) .

static, - ,
.
static ,
,
.
static - (),
.

s t a t i c
singleton class), 9.10.
9.10. President,

,
!: #include <iostream>
1: #include <string>
2: using namespace std;
4: class President

5: {
i': private:
// ( )
:
President() {};
// ( )
President(const Presidents);

lz
13
14

15
16

// ( )
const Presidents operator=(const Presidents);
// -:
string Name;

13

:
:

public:
//
static Presidents Getlnstance()

234
22

9.

{
//
static President Onlylnstance;

23:
24:
25:

return Onlylnstance;

26:

27:
28:

32:

//
string GetNameO
{
return Name;

33:

29:
30:
31:

34:
35:

void SetName(string InputName)

36:

{
Name = InputName;

37:

38:
39:
40:
41:

int main()

42:

{
Presidents OnlyPresident = President::GetInstance();
OnlyPresident.SetName("Abraham Lincoln");

43:
44:
45:

//
//
//
//
//

,
,
President Second;
//
President* Third= new President ; //
President Fourth = OnlyPresident;
//
//
// OnlyPresident = President::GetInstance(); // =
//

46:

47:
48:
49:

50:

51:

cout
cout

52:
53:

"The name of the President is: ";


President::GetInstance().GetName()

endl;

54:

return 0;

55:
56:

The name of the President is: Abraham Lincoln

m a in ( ) :
,
P r e s i d e n t , .
:
47:
48:

// President Second;
//
// President* Third= new President(); //

235

47 48
, , ,
8 .
49:

// President Fourth = OnlyPresident;

//
//

49 ( ),
m a in ( ) , 11 .
50:

// OnlyPresident = President::GetInstance(); // =
//

50 , ,
14. ,
- a i n () P r e s i d e n t , : P r e s i d e n t
G e t l n s t a n c e ( ) , 43. G e t l n s t a n c e ()
, ,
5 . G e t l n s t a n c e ( ) , iax 2 1 -2 7 , O n l y l n s t a n c e
P r e s i d e n t . , 24
( ), , G e t
l n s t a n c e () P r e s i d e n t ,
, ( 43 53) m a in ().

(singleton pattern) ,
, .
,
,
.
,
,
192 192 , .

,
. ,
, , ,
.
:
class MonsterDB

{
private:
//
-MonsterDB();
// ... ,

236

9.

, M o n sterD B
:
int main()

{
MonsterDB myDatabase; //
// ...
return 0;

}
. ,
m y D a ta b a s e ,
, m a in ( ),
, ,
.

:
int main()
MonsterDB* myDatabase = new MonsterDB(); //
// ...
return 0;

, .
m a in ( ) , . , M onsterD B ,
-, (
). 9.11.

9.11. MonsterDB,
( new)_______________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

12
13
14
15
16
17
18
19
20

#include <iostream>
using namespace std;
class MonsterDB
{
private:
-MonsterDB() {}; //
public:
static void Destroylnstance(MonsterDB* plnstance)
sta

//
//
delete plnstance;

// ...

int main ()
MonsterDB* pMyDatabase = new MonsterDB();

this

237

// pMyDatabase -> member methods


// ,
//
// delete pMyDatabase; //
//
//
MonsterDB::Destroylnstance(pMyDatabase);
return 0;

}
.

, ,
, , 6,
D e s t r o y l n s t a n c e ( ) , 9 -1 3 ,
- a m () ( 28).

th is
t h i s C++; t h i s , .
, t h i s & o b je c t . ,
, t h i s
:
class Human

{
private:
// ...
void Talk (string Statement)

{
cout

Statement;

public:
void IntroduceSelf ()

{
Talk("Bla bla");

}
};
I n t r o d u c e S e l f ( ) ; T a l k ()
. t h i s
T a l k ( ), T a l k ( t h i s , " B la b l a " ).
t h i s
, . ,
S e t ( ) , 9.1,
:

238

9.

void SetAge(int HumansAge)

{
this->Age = HumansAge; // , Age = HumansAge

this .
, .
.
,
, ,
this .



c l a s s , ,
. s i z e o f ( ) , 3,
, ,
, .
, , ,
.
s i z e o f ()
. -
. 9.12.
9,12. sizeof ()

0
1

#include <iostream>
using namespace std;

3
4
5
6
7
8

9
10
11
12

13
14
15
16
17
18
19
20
21

class MyString
{
private:
char* Buffer;
public:
//
MyString(const char* Initiallnput)

{
if(Initiallnput != NULL)

{
Buffer = new char [strlen(Initiallnput) + 1];
strcpy(Buffer, Initiallnput);

}
else
Buffer = NULL;

}
//


12

MyString(const MyString& CopySource)

3
_i

23 9

if(CopySource.Buffer != NULL)

15
16

{
Buffer = new char [strlen(CopySource.Buffer) + 1];
strcpy(Buffer, CopySource.Buffer);

18
19
2D

}
else
Buffer = NULL;

}
52
53

^MyString ()

24
25
26

{
if (Buffer != NULL)
delete [] Buffer;

}
/

28
29

int GetLength()

4D

{
return strlen(Buffer);

42
43
44

const char* GetStringO

{
46

return Buffer;

47

48
49
53

}
};
class Human

{
52 private:
53
int Age;
54
55
56

53
59
60
61
62
63
64
65

bool Gender;
MyString Name;
public:
Human(const MyString& InputName, int InputAge, bool InputGender)
: Name(InputName), Age (InputAge), Gender(InputGender) {}
int GetAge ()

{
return Age;

}
};

66

67

int main ()

68

69

'0
'1
'2

73
74
75

MyString FirstMan ("Adam") ;


MyString FirstWoman("Eve");
cout
cout
cout

"sizeof(MyString) = " sizeof(MyString) endl;


"sizeof(FirstMan) = " sizeof(FirstMan) endl;
"sizeof(FirstWoman) = " sizeof(FirstWoman) endl;

240
76:
77:
78:
79:
80:

9.
Human FirstMaleHuman(FirstMan, 25, true);
Human FirstFemaleHuman(FirstWoman, 18, false);
cout
cout

cout <<
<<

81:
82:
83:
84: }

"sizeof(Human) = " sizeof(Human) << endl;


"sizeof(FirstMaleHuman) = " sizeof(FirstMaleHuman)
endl;
"sizeof(FirstFemaleHuman) = " sizeof(FirstFemaleHuman)
endl;

return 0;

sizeof(MyString) = 4
fcizeof(FirstMan) = 4
sizeof(FirstWoman) = 4
sizeof(Human) = 12
sizeof(FirstMaleHuman) = 12
sizeof(FirstFemaleHuman) = 12

, , , M y S t r i n g ,
9.9 (, ),
Human, M y S t r i n g (Name),
b o o l ( G e n d e r ) .
. ,
s i z e o f () . ,
s i z e o f ( M y S t r i n g ) , s i z e o f ( F i r s t M a n ) ,
, ,
. , F i r s t Man F i r s t W o m a n , , Adam, E v e ,
M y S t r i n g : : B u f f e r ,
c h a r * , 4 ( 32-
) , .
Hu man , 12.
5 3 -5 5 , H u m a n i n t , b o o l
M y S t r i n g . ,
3.4. , i n t 4 , b o o l 1
, M y S t r i n g 4 , 12,
. , s i z e o f ()
.


s t r u c t ,
C++ , c l a s s .
( p u b l i c p r i v a t e ) ,

241

. , ,
( p u b l i c ) , ( p r i v a t e ) ,
,
, . 10,
.
Human 9.12 :
struct Human

{
// , (
// )
Human(const MyString& InputName, int InputAge, bool InputGender)
: Name(InputName), Age (InputAge), Gender(InputGender) {}
int GetAge ()

{
return Age;

}
private:
int Age;
bool Gender;
MyString Name;

, Human Human
:
Human FirstMan("Adam", 25, true); // Human


- .
,
f r i e n d (friend), 9.13.

9.13. friend,
DisplayAge () -____________________
3:
1:
2:
3:
4:
5:
6:
7:
8:

#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
string Name;
int Age;

9:
10:

friend void DisplayAge(const

Human& Person);

11:

12: public:
13:
Human(string InputName,

intInputAge)

242
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:

9.
{
Name = InputName;
Age = InputAge;
}
};
void DisplayAge(const Humans Person)

{
cout

Person.Age

endl;

}
int main()
{
HumanFirstMan("Adam",
25);
cout "Accessing private member Age via friend: ";
DisplayAge(FirstMan);
return 0;
}

Accessing private member Age via friend: 25

10 , ,
D is p la y A g e ()
Human. 10,
22.
, ,
9.14.

9.14. friend,
-__________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

#include <iostream>
#include <string>
using namespace std;
class Human
{
private:
string Name;
int Age;
friend class

Utility;

public:
Human(string InputName, int InputAge)
{
Name = InputName;

243

Age = InputAge;

class Utility
::: {
11: public:
1::
static void DisplayAge(const Human& Person)

14:

I::

cout

Person.Age

endl;

}
};
1?: int main()
31:
31:
3 2:

Human FirstMan("Adam", 25);


cout "Accessing private member Age via friend class: ";
Utility::DisplayAge(FirstMan);

3::

return 0;

31: }

Accessing private member Age via friend class: 25

10 U t i l i t y Human.
U t i l i t y -
Human.

!
C++ c l a s s . , - . ,
, p u b l i c p r i v a t e , ,
.
,
C++11
. ,
, , .


?
, . , .

244

9.

: ( . )
(-> )?

, .
, .
?

- ,
STL, s t d : : v e c to r,
, ,
. , ( in t*
s t d : : v e c to r < in t> ) ,
,
, .

,
. ?

. , ,
.
.

,
S e tA g e ( ) , Human: :A g e?
,
?

- Human: : Age
. -
. , G etAge () S etA g e (),
,
, , , Human: : Age
.

, . ,
, ,
.


, ,
. ,
, .
,
.


1. new, ,
?

245

2. i n t * .
s i z e o f
?
3. ,
. ?
4. ?
5. ?
6. ?

1. : ?
Class Human
{
int Age;
string Name;
public:
Human () {}

}
2. 1 -
H um an: : Age?
3. 1,
.
4. C i r c l e , ,
.
,
.

10

-
: (encapsulation),
abstraction), (inheritance) (polymorphism).

.
.

C++.

, .

,
.

248

10.


, , , , ,
. , ,
, , ,
. !
.
,

. ,
, .
,
, ,
, , .
.
- (. 10.1).

. 1 0 .1 .


. 10.1 (base class)
(derived class).
, ; ,
,
, .

(public inheritance).

,
,
.

249

, B i r d ().
B i r d Crow ( ), P a r r o t ( ) K i w i ().
B i r d , ,
, ( ). ,
Brow, P a r r o t Kiwi, (,
K i w i F l y () ()).
. 10.1.
10.1.

i s h ()

G o l d f i s h ( ), C a r p (), T u n a () (

Mammal

Human (), E l e p h a n t (), L i o n (), P l a t y p u s ()

)
)

( )

B i r d ()

Cr ow (), P a r r o t (), O s t r i c h (), K i w i (),


P l a t y p u s () ( !)

S h a p e ( )

C i r c l e (), P o l y g o n ( ) ( )

Polygon

T r i a n g l e (), O c t a g o n () (

, )

, - ,
. F i s h
Tuna, , ,
, .
, , . ,
T u n a C a r p F i s h ,
,
(. 10.2).

. 10.2. Tuna, Carp Fish

, ,
, ( ), , ,
. , P l a t y p u s

250

10.

, Mammal B i r d ,
. (m ultiple inheritance)
.

C++
C a rp F i s h
? C++ :
//
class
{
// ...

};
//
class :
{
// ...

};

, p u b
l i c , (is-a),
p r i v a t e p r o t e c t e d
(has-a).
C a r p F i s h
:
class Fish
{
// ... Fish

};
class Carprpublic Fish

<

// ... Carp

};
C a rp T una, F is h ,
10.1.


, , (inherits from)
(derives from). .
(base class) (super class).
, , (derived class),
(subclass).


10,1, ________
: #include <iostream>
1: using namespace std;
2: class Fish
4: {
5: public:
6:
bool FreshWaterFish;
2:

void Swim()

3:

22:
22:
Li:
22:
14:
25: };

if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;
}

2": class Tuna: public Fish


26: {
26: public:
22:
Tuna()
22:
{
22:
FreshWaterFish = false;

2c: class Carp: public Fish


2 ":

26: public:
2 6:
Carp()

22:

22:
FreshWaterFish = true;
22:
}
23: };
zi :
25: int main()
26: {
2":
Carp myLunch;
26:
Tuna myDinner;
42:

cout

"Getting

my food to swim"

42:
4 3:

cout "Lunch: ";


myLunch.Swim();

11:
45:
46:

cout "Dinner:
myDinner.Swim();

return 0;

";

endl;

251

252

10.

Getting my food to swim


Lunch: Swims in lake
Dinner: Swims in sea

37 38 m a in ( ) , L u n ch m y D in n e r C a rp T una . 43 46
, Swim ( ) , .
, T u n a 1 7-24 C a rp
26 -3 3 . , , , ,
, Swim ( ) , m a in ().
, Swim () F is h , 3 -1 5 ,
. F i s h Swim () ,
T u n a C a r p ( ,
17 26) . ,
C a rp T una F r e s h W a te r F is h .
, F i s h : : Swim ().

protected
10.1 F i s h F r e s h W a t e r F i s h ,
T u n a C a rp , (
(specialize))
. 10.1 : ,
m a in () ,
p u b l i c , , F i s h
, , :
myDinner.FreshWaterFish = true; // !

, , . ,
,
. , F r e s h W a t e r F i s h F is h
T u n a C a rp , ,
m a in ( ) , T u n a C a rp .
p r o t e c t e d .
protected (), public () |
private () .
protected, - j

, - j
, main ().
|

,
, p r o t e c t e d ,
10.2.


10.2. Fish, protected
- _______
I: #include <iostream>
2: using namespace std;
5: class Fish
4: {
5: protected:
6:
bool FreshWaterFish; //
:: public:
9:
void Swim ()

:::

11:
12:
15:
14:

if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;

15:

}
};

15: class Tuna: public Fish

19: {
2 5: public:
21:
Tuna()

22:

22:
24:

FreshWaterFish = false; //
//
}

2: class Carp: public Fish


25: {
29: public:
2:
Carp()
22:
{
22:
FreshWaterFish = false;

26: int main()


2 ": {

28:
29:

Carp myLunch;
Tuna myDinner;

42:

cout

43:
44:

cout "Lunch: ";


myLunch.Swim();

46:
4":

cout "Dinner:
myDinner.Swim();

"Getting

my food to swim"

endl;

";

// ,
//
// myLunch.FreshWaterFish = false;

52
53

return 0;

253

254

10.

Getting my food to swim


Lunch: Swims in lake
Dinner: Swims in sea

10.1 10.2, F i s h ,
3 -1 6 , .
- F i s h : : F r e s h W a t e r F i s h ,
, m a in (), 51 (
, ).
p r o t e c t e d T una C a rp ,
23 32 .
p r o t e c t e d
, , .
-

,
.



, ,
?
?

, :
class Base

{
public:
Base(int SomeNumber) //

{
// SomeNumber

}
};
Class Derived: public Base

{
public:
Derived(): Base(25) // Base 25

{
//

}
};
F i s h
, -
F i s h : : F r e s h W a t e r F i s h . , F i s h ,

255

, ,
* 10.3.

10.3. ____________
2: #include <iostream>
1: using namespace std;
2: class Fish

4: {
5: protected:
6:
bool FreshWaterFish; //
5: public:
2:
// Fish
12:
Fish(bool IsFreshWater) : FreshWaterFish(IsFreshWater){}
12:
13:
14:
15:
16:
1":

void Swim()
{
if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;

Is :

13: };
11: class Tuna: public Fish
22: {

22: public:
24:
Tuna():
23: };
2":
2 =:
12:
21:
:1:

Fish(false)

{}

class Carp: public Fish


{

public:
Carp() : Fish(true)
};

{}

2 2: int main()
:4: {
25:
Carp myLunch;
26:
Tuna myDinner;
cout

"Getting my food to swim"

*]:
-1:

cout "Lunch: ";


myLunch.Swim();

-2:
-4:

cout "Dinner:
myDinner.Swim();

*5:

:2:
-1: }

endl;

";

// 48,
//
// myLunch.FreshWaterFish = false;
return 0;

256

10.

Getting my food to swim


Lunch: Swims in lake
Dinner: Swims in sea

F i s h ,
, F i s h : : F r e s h W a te r F is h . ,
F i s h ,
. , F i s h ,
,
. T u n a C a rp
, F i s h
( t r u e f a l s e , , ), 24
30 .

10.3,
- Fish::FreshWaterFish,
, ,
Fish.
,
, private.

,


, , ,
, :
class Base

{
public:
void DoSomething()

{
// ...

class Derived:public Base


{
public:
void DoSomething()

{
// ...

257

, D o S o m e th in g ()
D e r iv e d ,
B a se .
T u n a C a rp S w im ( ) ,
F i s h : : Swim ( ) , m a in ()
, 10.3,
36:
Tuna myDinner;
// ...
44:
myDinner.Swim();

T u n a : : Swim ( ) , ,
, F i s h : : Swim () . 10.4.

10.4. Tuna Carp,


SwimQ Fish
.: #include <iostream>
1: using namespace std;
3: class Fish

{
:: private:
5:
bool FreshWaterFish;
3: public:
5:
// Fish
II:
Fish(bool IsFreshWater) : FreshWaterFish(IsFreshWater){}
.1:

3:

void Swim()

.4:
15:
.5:
13:

if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;
}

15: };
11: class Tuna: public Fish

11: {
13: public:
14:
Tuna(): Fish(false)
15:

void Swim()

1":

13:

cout

{}

"Tuna swim^ real fast"

32: class Carp: public Fish


34: public:
35:
Carp(): Fish (true) {}

3ak. 3626

endl;

259

10.5
.


F i s h : : Swim () ,
, .
T u n a : : Swim () C a r p : : Swim ()
F i s h : : Swim ( ), ( : : ) ,
:
class Carp: public Fish

{
public:
Carp(): Fish(true)

{}

void Swim()

{
cout "Carp swims real slow" endl;
Fish::Swim(); // ::

10.5.

10.5. (::)
main ()
*: #include <iostream>
1: using namespace std;
5: class Fish
5: private:
6:
bool FreshWaterFish;
8: public:
8:
// Fish
.1:
Fish(bool IsFreshWater) : FreshWaterFish(IsFreshWater){}
.2:

void

-3:

14:
15:
16:
1":
15:

Swim()

if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;
}

1*: } ;
class Tuna: public Fish
22

{
public:
Tuna(): Fish(false)

{}

260
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:

10.
voidSwim()
{
cout
}

"Tuna swims real fast"

endl;

};
class Carp: public Fish
{
public:
Carp(): Fish(true) {}
void Swim()
{
cout "Carp swims real slow" << endl;
Fish::Swim();
}
};
int main()
{
Carp myLunch;
Tuna myDinner;
cout

"Getting my food to swim"

endl;

cout "Lunch: ";


myLunch.Swim();
cout "Dinner: ";
myDinner.Fish::Swim();
return 0;
}

Getting my food to swim


Lunch: Carp swims real slow
Swims in lake
Dinner: Swims in sea

C a r p : : Swim () 37-41 F i s h : : Swim ()


( : : 55,
, ( : : )
F i s h : : Swim () m a in ()
, T una.

261

,
, T u n a : : Swim ()

F i s h : : Swim ( ) , ,
( (hidden)), 10.6.

10,6. Tuna: ;Swim() Fish: : Swim (bool)


I: #include <iostream>
1: using namespace std;
:: class Fish

4: {
:: public:
i:
void Swim()

{
::

cout

"Fish swims...

!"

endl;

void Swim(bool FreshWaterFish)

{
if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;

class Tuna: public Fish

:i:

.1: public:
void Swim()

{
cout

"Tuna swims real fast"

endl;

int main()

{
Tuna myDinner;
cout

"Getting my food to swim"

endl;

// myDinner.Swim(false); // : Fish::Swim(bool)
/ / Tuna::Swim()
myDinner.Swim();
return 0;

262

10.

Getting my food to swim


Tuna swims real fast

F i s h , .
,
F i s h Swim ( ) :
( 6 -9 ), b o o l ( 11-17).
T u na F i s h ( 20), ,
F i s h : : Swim () T una.
, T una T u n a : : Swim ()
( 2 3 -2 6 ), F i s h : : Swim ( b o o l) .
35, .
, F i s h : : Swim ( b o o l)
T una, .

1. m a in ():
myDinner.Fish::Swim();

2. T una u s i n g ,
Swim () F is h :
class Tuna: public Fish
{
public:
using Fish::Swim; // Swim()
// Fish
void Swim()

{
cout

Tuna swims real fast

endl;

}
};
3. Swim ()
T una ( , F i s h : : Swim ( . . . ) T u n a : : F i s h ( . . . ) ) :
class Tuna: public Fish
{
public:
void Swim(bool FreshWaterFish)

{
Fish::Swim(FreshWaterFish);

}
void Swim()

{
cout

Tuna swims real fast

endl;

263


T una, F is h ,
Tuna F i s h ? ,
, F i s h : : F r e s h W a te r F is h ,
? ,
. , F i s h T u n a
, , ,
, T una. F i s h
Tuna , F i s h : : F r e s h W a t e r F i s h ,
F i s h : : F i s h ( ) ,
. T u n a : : T u n a ().


T una , . 10.7
, .
10.7.

, _____________________________
I: #include <iostream>
1: using namespace std;
3: class FishDummyMember
{
:: public:
6:
FishDummyMember ()

{
::

cout

3:

"FishDummyMember constructor"

endl;

.1:

-FishDummyMember()

-I:

33:

cout

"FishDummyMember destructor"

-5: };
class Fish

-3: {
3 6: protected:
33:
FishDummyMember dummy;
33: public:
33:
// Fish
3 4:
Fish()

: =:

36:
3 ~:

cout

-Fish()

"Fish constructor"

endl;

endl;

264

10.

30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:

{
cout

"Fish destructor"

endl;

}
};
class TunaDummyMember
{
public:
TunaDummyMember()
{
cout "TunaDummyMember constructor"
}
-TunaDummyMember()
{
cout "TunaDummyMember destructor"
}
};

class Tuna: public Fish


{
private:
TunaDummyMember dummy;
public:
Tuna()
{
cout
}
-Tuna()
{
cout
}

"Tuna constructor"

"Tuna destructor"

};
int main()

68: {
69:
70: }

Tuna myDinner;

FishDummyMember constructor
Fish constructor
TunaDummyMember constructor
Tuna constructor
Tuna destructor
TunaDummyMember destructor
Fish destructor
FishDummyMember destructor

endl;

endl;

endl;

endl;

265

m a in ( ) , 6 7 -7 0 ,
. T u n a
, o u t
.
, FishDummyM ember TunaDummyMember, c o u t
. F i s h T una
( 20 53). ,
Tuna . , F i s h
T u n a , , F i s h : : dummy,
. F is h ,
, dummy.
T u n a T u n a : : dummy
T u n a : : T una ( ) . ,
.


(private inheritance) (
) ,
p r i v a t e :
class Base

{
// ... -

};
class Derived: private Base //

{
// ... -

};
,
(.. ) ,
. , B a s e
D e r iv e d , -,
D e r iv e d .
T u n a F i s h ,
10.1. m a i n ( ) 10.1
F i s h : : Swi m( ) T u n a,
i s h : : Swim () , T una
F i s h .
p u b l i c p r i v a t e 17, .
,
(is-a) ( , !).

, , ,

10.

266

(has-a).
(. 10.2).
10.2.

Motor ()

( )

Heart ()

Mammal ( )

Refill ()

( )

Moon ()

Sky ( )


( 10.8).
10.8. , Motor
0
1

#include <iostream>
using namespace std;

3
4
5

class Motor

{
public:
void Switchlgnition()

7
8
9

{
cout

"Ignition ON"

endl;

10

void PumpFuelO

11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

{
cout

"Fuel in cylinders"

}
void FireCylinders()

{
cout

"Vroooom"

}
};
class Car:private Motor

{
public:
void Move ()

{
Switchlgnition();
PumpFuel();
FireCylinders();

}
};
int main()

{
Car myDreamCar;
myDreamCar.Move();
return 0;

endl;

endl;

267

Ignition ON
Fuel in cylinders
Vroooom

M o to r, 3-18, ,
-, ( S w i t c h l g n i t i o n O ) , (Pump
F u e l ()) ( F i r e C y l i n d e r s ()). M o to r
p r i v a t e ( 20). , C a r : :Move ()
M o to r.
- a i n ( )
myDreamCar.PumpFuel();

e r r o r 2 2 4 7 : M o t o r : : P u m p F u el
T c t a c c e s s i b l e b e c a u s e C a r u s e s ' p r i v a t e ' t o i n h e r i t fro m 'M o t o r ' (
C2247: M o t o r : : P u m p F u el , 'C a r ' ' p r i v a t e '
' M o to r ').

, SuperCar, ,
, SuperCar
Motor. ,
Motor ,
, , , (..
), .
,
,
.


p r o
j e c t e d :
class Base
{
// ... -

};
class Derived: protected Base //

{
// ... -

};

:
(has-a).

268

10.

,
, :
class Derived2: protected Derived

{
// Base

};

(.. D e r iv e d 2 ) (
10.9). , D e r iv e d
B a s e p r i v a t e .

10.9. SuperCar, ,
Motor, ________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <iostream>
using namespace std;
class Motor
{
public:
void Switchlgnition()
{
cout "Ignition ON"
}
void PumpFuelO

endl;

11:

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

cout "Fuel in cylinders"


}
void FireCylinders()
{
cout "Vroooom" endl;
}
};
class Car:protected Motor
{

public:
void Move()
{
Switchlgnition();
PumpFuelO;
FireCylinders ;
}
};
class SuperCar:protected Car
{
public:
void Move()

endl;


25:
26:
27:
23:
29:
4 9:
41:
4 2 : };

269

{
Switchlgnition(); //
PumpFuelO;
// Motor
FireCylinders();
FireCylinders();
FireCylinders ();

43:
44: int main()
45: {

46:
47:
43:
49:

SuperCar myDreamCar;
myDreamCar.Move();
return 0;

- 3: }

Ignition ON
Fuel in cylinders
Vroooom
Vroooom
Vroooom

C a r M o to r ( 20). S u p e r C a r
( 31). ,
S u p e r C a r : :M ove () , 7o r. M o to r
M o to r.
, ,
M o to r,
. ,
S u p e r C a r . ,
31 p r o t e c t e d p u b l i c p r i v a t e ,
.


.
, (
Motor), () ,
. Motor , ,
, -
Motor .
, ,
,
.
, .

270

10.

Motor ,
, (composition) (aggregation).
:

class
{
private:
Motor heartOfCar;
public:
void Move()

{
heartOfCar.Switchlgnition ();
heartOfCar.PumpFuel();
heartOfCar.FireCylinders();

}
};
,
,
.


, ?
Derived objectDerived;
Base objectBase = objectDerived;

?
void FuncUseBase(Base input);
Derived objectDerived;
FuncUseBase(objectDerived); // objectDerived
//

,
, , , .
o b j e c t D e r i v e d ,
B a se , . , ,
, ,
, (slicing).

, .
( const)
.

271


,
(m ultiple inheritance), .
, , . C++
:
c la s s : 1, 2

{
/ /
};
. 10.3 ,
T u n a C a r p (. . 10.2).

-10-3. P latyp u s Mammal, R e p tile B ird


, C++ P l a t y p u s :
c l a s s P latyp u s: p u b lic Mammal, p u b lic R e p tile , p u b lic Bird
{
/ / . . . P latypu s
};
P l a t y p u s , ,
10.10.

10.10.
, , ________________

0:
1:
2:
3:
4:
5:
6:

# in clu d e <iostream >


u sin g namespace std ;
c l a s s Mammal
{
p u b lic :
v o id FeedBabyM ilk()

272
7:
8:
9:
10 :
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:

10.
{
cout

"Mammal: Baby says glug!"

endl;

}
};

class Reptile
{
public:
void SpitVenomO
{
cout "Reptile: Shoo enemy! Spits venom!"
}
};

endl;

class Bird
{

public:
void LayEggsO
{
cout "Bird: Laid my eggs, am lighter now!"
}
};

endl;

class Platypus: public Mammal, public Bird, public Reptile


{
public:
void Swim()
{
cout "Platypus: Voila, I can swim!" endl;
}
};
int main()
{
Platypus realFreak;
realFreak.LayEggs();
realFreak.FeedBabyMilk();
realFreak.SpitVenom();
realFreak.Swim();
return 0;
}

Bird: Laid my eggs, am lighter now!


Mammal: Baby says glug!
Reptile: Shoo enemy! Spits venom!
Platypus: Voila, I can swim!

273

P l a t y p u s ( 3 0 -3 7 ).
.-, : M am m al, R e p t i l e B i r d .
- a i n () 41-44
, r e a l F r e a k P l a t y p u s .
, M am m al, B i r d R e p t i l e , m a in ()
45 P l a t y p u s : : S w im ( ) .
, ,
( ) .
, . , 10.10
Platypus Fish
Fish: :Swim().
, ,
,
, .
-.

, ,
,
,

, ,
,
,

,



( ,
),

,
, ,
,

, ,
,

C++.
,

274

10.

, . ,
p r o t e c t e d
, .
, ,

, .
, ,
u s in g .
,
- .


Mammal
: Human, Lion Whale.
, , ?
, .
, Mammal , ,
Human, L io n W hale, .

?
, . , (.. )
.


. ?
. ,
.
(.. ) .
, ( f r i e n d ) .


, ,
. ,
, .
,
.


1. ,
, . ?
2. , ,
?
3. ? ?

275

4. u s i n g ?
5. D e r i v e d B a s e . , S u b D e r iv e d ,
D e r iv e d . S u b D e r iv e d
B a se ?

1. P l a t y p u s 10.10?
2. P o ly g o n ( ), T r i a n g l e () S h a p e ( )
.
3. D2 D1, B a se .
, D2
B a se ?
4. ?
class Derived: Base
{
// ... Derived

};
5. : :
class Derived: public Base
{
// ... Derived

};
void SomeFunc (Base value)

11

,
,
,
-
.
.

11.

278


, .
(polym orphism ) - ,
.
, C ++
, (subtype polym orphism ).


10, , , T u n a C a rp
S w im () F i s h (. 10.1). T u n a C a rp
T u n a : : Swim () C a r p : : Swim ( ) ,
-. ,
T una
F i s h : : Swim ( ) , F i s h : : Swim ( ),
T u n a : : Swim ( ), , F i s h
T una. 11.1.

,
,
, .
,
,
.

1 1 .1 .
Fish, Tuna________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <iostream>
using namespace std;
class Fish
{
public:
void Swim()
{
cout "Fish swims!"
}

endl;

1 0 : };
11:

12: class Tuna:public Fish


13: {
14: public:
15:
// Fish::Swim
16:
void Swim()
17:
{
cout << "Tuna swims!" endl;
18:
19:
}
2 0 : };

279

12: void MakeFishSwim(Fish& InputFish)


13: {
24:
// Fish::Swim
15:
InputFish.Swim();
16: }
IB: int main()
13: {
11:
Tuna myDinner;
22:
2 3:

// Tuna::Swim
myDinner.Swim();

ji :
25:
26:
*->.

// Tuna Fish
MakeFishSwim(myDinner);

23:
19: }

return 0;

Tuna swims!
Fish swims!

T u n a F i s h ,
12. F i s h : :S w im ( ) . m a in ()
T u n a : :S w im () 33 m y D in n e r (
T un a) M a k e F ish S w im ( ) ,
F ish & , ( 22). ,
M akeFishSw im (F ish & ) , T una,
F i s h F i s h : : Swim ( ). ,
, T una , F i s h ,
( C a rp ).
, , , T una
, F i s h : : Swim ( ). , I n p u t F i s h .
Swim () 25, , T u n a : : Swim ().
, F i s h
, T una,
, F i s h : : Swim () .

,

F i s h F is h * F ish & .
F i s h T una
C a rp , F i s h . , ,
Swim ( ) , :

280

11.

pFish->Swim();
myFish.Swim();

, F i s h , ,
T una, , C a rp , ,
F i s h ,
T u na C a rp . , Swim ()
F i s h (virtual function):
class Base
virtual ReturnType FunctionName (Parameter List);

};
class Derived

{
ReturnType FunctionName (Parameter List);

};
v i r t u a l ,
.
, Swim () v i r t u a l , m y F is h . Swim () (m y F ish
F ish & ) T u n a : : Swim ( ), 11.2.

11.2. Fish: :Swim() ________________


0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <iostream>
using namespace std;
class Fish
{
public:
virtual void Swim()
{
cout "Fish swims!"
}

1 0 : };
11:

12:
13:
14:
15:
16:
17:
18:
19:
20:

endl;

class Tuna:public Fish


{
public:
// Fish::Swim
void Swim()
{
cout "Tuna swims!" endl;
}
};

21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:

class Carp:public Fish


{
public:
// Fish::Swim
void Swim()
{
cout "Carp swims!" endl;
}
};


52

void MakeFishSwim(Fish& InputFish)

53
34

56
57
58

}
int main()

59

40
41
42
43
44
45
46
47
43
49
30

281

// Swim()
InputFish.Swim();

Tuna myDinner;
Carp myLunch;
// Tuna Fish
MakeFishSwim(myDinner);
// Carp Fish
MakeFishSwim(myLunch);
return 0;

Tuna swims!
Carp swims!

M a k e F is h S w im (F is h & ) 11.1,
. F i s h : : Swim () -
T u n a : : Swim () C a r p : : Swim ( ) ,
F i s h : : Swim ( ),
. . , ,
, F is h ,
M ak eF ish S w im () Swim (),
.
: F i s h ,
Swim ( ) ,
.


, 11.1, :
,
. , d e l e t e , B a se* ,
?
? 11.3.
1 1 .3 . , delete Base*

0: #include <iostream>
1: using namespace std;
2:

282
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

11.
class Fish
{
public:
Fish()
{
cout
}
~Fish()

"Constructed Fish"

endl;

cout

"Destroyed Fish"

endl;

}
};
class Tuna:public Fish
{
public:
TunaO
{

cout

22:

23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

-TunaO
{
cout
}

"Constructed Tuna"

"Destroyed Tuna"

endl;

endl;

};
void DeleteFishMemory(Fish* pFish)
{
delete pFish;
}
int main()
{
cout "Allocating a Tuna on the free store:"
Tuna* pTuna = new Tuna;
cout "Deleting the Tuna: " endl;
DeleteFishMemory(pTuna);

endl;

cout "Instantiating a Tuna on the stack:" endl;


Tuna myDinner;
cout "Automatic destruction as it goes out of scope:
endl;

44:
45:
46: }

return 0;

Allocating a Tuna on the free store:


Constructed Fish
Constructed Tuna
Deleting the Tuna:
Destroyed Fish
Instantiating a Tuna on the stack:

283

Constructed Fish
Constructed Tuna
Automatic destruction as it goes out of scope:
Destroyed Tuna
Destroyed Fish

m a in () T u n a ,
new 37, ,
D e le te F is h M e m o r y () 39. :
T una m y D in n e r ( 42)
m a in ().
c o u t F i s h T una. :
, , T una F is h , ,
new,
F is h , T una.
m y D in n e r, .
10.7
, , ,
- T u n a ( ). - .
, ,
new, ,
d e l e t e B a s e * .
, .
, ,
11.4.
1 1 .4 .
Base*___________________

3: #include <iostream>
1: using namespace std;
2:

3: class Fish
4: {
5: public:
6:
Fish()

>:

3:
cout "Constructed Fish" endl;
9:
}
13:
virtual -Fish() // !
11:
{
12:
cout "Destroyed Fish" endl;
13:
}
14: };
15:
15: class Tuna:public Fish

17: {
13: public:
19:
TunaO
23:
{

284

11.

21:

cout << "Constructed Tuna"

23:

~Tuna()

24:

25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

endl;

22:

cout

"Destroyed Tuna"

endl;

}
};
void DeleteFishMemory(Fish* pFish)
{
delete pFish;
}
int main()
{
cout "Allocating a Tuna on the free store:" e n d l ;
Tuna* pTuna = new Tuna;
cout "Deleting the Tuna: " endl;
DeleteFishMemory(pTuna);
cout "Instantiating a Tuna on the stack:" endl;
Tuna myDinner;
cout "Automatic destruction as it goes out of scope:
endl;

44:
45:
46: }

return 0;

Allocating a Tuna on the free store:


Constructed Fish
Constructed Tuna
Deleting the Tuna:
Destroyed Tuna
Destroyed Fish
Instantiating a Tuna on the stack:
Constructed Fish
Constructed Tuna
Automatic destruction as it goes out of scope:
Destroyed Tuna
Destroyed Fish

11.4 11.3
v i r t u a l 10, F i s h .
, , ,
T u n a : : -T u n a () F i s h : : - F i s h ( ),
d e l e t e F is h * , T u n a,
31. ,
, , T una

285

new, 37,
, ( 42).

virtual:

class Base
{
public:
virtual ~Base() {}; //

};
, Base*
delete ,
.

, .
, .

M a k e F is h S w im (F is h & ) 11.2
: : Swim () T u n a : : Swim ( ), ,
F i s h : : S w im ( ) . ,
, ,
Sw im () . ,
, Swim () ,
, ,
.
B a se , N :
class Base

{
public:
virtual void FunclO
{
// F u n d

}
virtual void Func2()

{
// Func2

}
// ...
virtual void FuncNO
{
// FuncN

286

11.

D e r iv e d , B a se , B a s e : : F u n c2 ().
B a se :
class Derived: public Base
{
public:
virtual void Funcl()

{
// Func2 Base::Func2

}
// Func2
virtual void FuncN()

{
// FuncN

};
, B a se
, D e riv e d .
, (Virtual
Function Table V FT), , ,
, . , B ase D e riv e d
.
, ( VFT*)
VFT.
, ,
( ), (. 11.1).

. 1 1 .1 . Derived Base

287

, ,
. D e r iv e d ,
VFT,
D e r iv e d . D e r i v e d
B a s e : : F unc2 ( ), ,
B ase.
, D e r iv e d
CDerived objDerived;
objDerived.Func2();

V FT D e r i v e d
B a s e : : F u n c2 (). ,
:
void DoSomething(Base& objBase)

{
objBase.F u n d () ; // Derived: :F u n d

}
int main()

{
Derived objDerived;
DoSomething(objDerived);

, , o b j D e r iv e d
r b jB a s e B a se , V FT
, D e r iv e d . , F u n d ( ),
VFT, , , D e r iv e d : : F u n d ().
C++.
11.5 V FT
, ,
1 .

11.5. VFT
,
3: #indude <iostream>
1: using namespace std;
3: class SimpleClass
4: {
5:
int a, b;

6:
7: public:
3:
void FuncDoSomething() {}
9: };
13:
11: class Base
12:

13:
14:

int a, b;
public:

288

11.

16:
virtual void FuncDoSomething() {}
17: };
18:
19: int main()
20: {

21:
22:
23:
24:
25: }

cout
cout

"sizeof(SimpleClass) = " sizeof(SimpleClass)


"sizeof(Base) = " sizeof(Base) endl;

endl;

return 0;

sizeof(SimpleClass) = 8
sizeof(Base) = 12

. , S i m p l e C l a s s B a se ,
, F u n c D o S o m e th in g ()
B a s e , S i m p l e C l a s s
. v i r t u a l ,
B a s e
B a s e , . 4
32 - ,
.
C++ Base*, Derived*,
dynamic_cast
.
(Run Time Type
Identification - RTTI), ,
C++. ,

.
R7TI dynamic_cast 13,
.


, ,
(abstract base class).
. C ++ ,
.
(pure virtual), :
class

289

p u b lic :
v i r t u a l v o id () = 0 ; / /
};
, , , ()
, :
c la s s : p u b lic
{
p u b lic :
v o id () / /
{
cout "Implemented v i r t u a l fu n c tio n " e n d l;
}
,
( ).

(interface).
F i s h . , , T u n a
F i s h : :S w im ( ) .
. F i s h
Swim ( ) , , T una, F i s h ,
T u n a : : Swim ( ) , .. , .
11.6.
1 1 .6 . F is h Tuna Carp________
0: # in c lu d e < io stre am >
1: u s in g nam espace s t d ;
2:

3: c l a s s F ish
4: {
5: p u b lic :
6:
/ / Swim
7:
v i r t u a l v o id Swim() = 0;
8:

};

9:
10: c l a s s T u n a :p u b lic F ish
11: {
12: p u b lic :
13:
v o id Swim()
14:
{
15:
c o u t "Tuna swims f a s t in th e s e a ! "
16:
17: };
18:

19: c l a s s C a r p :p u b lic F is h
20: {
21:
v o id Swim()
22:
{
23:
c o u t "C arp swims slow in th e la k e ! "
24:
}

. 3626

e n d l;

e n d l;

290

11.

25: };
26:
27: void MakeFishSwim(Fish& inputFish)
28: {
2 9:
inputFish.Swim();
30: }
31:
32: int main()
33: {
34:
// Fish myFish; // ,
//
35:
Carp myLunch;
36:
Tuna myDinner;
37:
38:
MakeFishSwim(myLunch);
39:
MakeFishSwim(myDinner);
40:
41:
return 0;
42: }

Carp swims slow in the lake!


Tuna swims fast in the sea!

( ) m a in () ( 34).
, F i s h .
- , , F i s h ( T una,
), .
F i s h : : Swim ( ), 7, , T una C a rp ,
T u n a : : Swim () C a r p : : Swim () . 2 7 -3 0 ,
M a k eF ish S w im ( F is h & ) , , ,
, .
,
. T r o u t ( ),
F is h , T r o u t : : Swim ( ) ,
.

(Abstract Base Class)

291




10, ,
, , , .
P l a t y p u s M am m al, B i r d R e p t i l e .
, , , A n im a l
), . 11.2.

. 11.2. ,
P l a t y p u s ?
A n im a l P l a t y p u s ? 11.7
.

11.7.
- Animal Platypus________________________________

3: #include <iostream>
1: using namespace std;
class Animal

290

11.

25: };
26:
27: void MakeFishSwim (Fish& inputFish)
28: {
2 9:
inputFish.Swim();
30: }
31:
32: int main()
33: {
34:
// Fish myFish; //,
//
35:
Carp myLunch;
36:
Tuna myDinner;
37:
38:
MakeFishSwim(myLunch);
39:
MakeFishSwim(myDinner);
40:
41:
return 0;
42: }

Carp swims slow in the lake!


Tuna swims fast in the sea!

( ) m a in () ( 34).
, F i s h .
- , , F i s h ( T una,
), .
F i s h : : Swim ( ), 7, , T una C a rp ,
T u n a : : Swim () C a r p : : Swim () . 2 7 -3 0 ,
M a k eF ish S w im ( F is h & ) , , ,
, .
,
. T r o u t ( ),
F is h , T r o u t : : Swim ( ),
.
(Abstract Base Class)

291




10, ,
, , , .
P l a t y p u s Mammal, B i r d R e p t i l e .
, , , A n im a l
), . 11.2.

. 11.2. ,
P l a t y p u s ?
A n im a l P l a t y p u s ? 11.7
.

11.7.
- Animal Platypus__________________________________

3: #include <iostream>
1: using namespace std;
class Animal

292
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:

11.
{
public:
Animal()
{
cout
}

"Animal constructor"

endl;

//
int Age;
};
class Mammal:public Animal
{
};
class Bird:public Animal
{
};
class Reptile:public Animal
{
};
class Platypus:public Mammal, public Bird, public Reptile
{
public:
Platypus ()
{
cout "Platypus constructor" endl;
}
};
int main()
{
Platypus duckBilledP;

42:
43:
44:
45: }

//
//
//
//


. ,
Animal
duckBilledP.Age = 25;

return 0;

Animal constructor
Animal constructor
Animal constructor
Platypus constructor

293

,
P l a t y p u s ( , , A n im a l)
A n im a l. , P l a t y p u s ,
38, A n im a l.
, ,
Mammal, B i r d R e p t i l e .
A n im a l .
A nim al A n im a l: : Age (
). - A n im a l: : Age
P l a t y p u s , 42, ,
, -
Mammal: : A n im a l: :A ge, B i r d : : A n im a l: : Age, R e p t i l e : : A n im a l: :A ge.
, :
duckBilledP.Mammal::Animal::Age = 25;
duckBilledP.Bird::Animal::Age = 25;
duckBilledP.Reptile::Animal::Age = 25;

, .
P l a t y p u s Mammal, B i r d R e p t i l e .
(virtual inheritance). ,
,
v i r t u a l :
class Derivedl: public virtual Base

{
// ...

};
class Derived2: public virtual Base

{
// ...

};
P l a t y p u s ( Mammal, B i r d R ep
t i l e ) 11.8.
1 1 .8 . virtual
Animal ___________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11 :

#include <iostream>
using namespace std;
class Animal
{
public:
Animal ()
{
cout
}

"Animal constructor"

//

endl;

294
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:

11.
int Age;

class Mammal:public virtual Animal


{
};

class Bird:public virtual Animal


{
};
class Reptile:public virtual Animal
{
};
class Platypus:public Mammal, public Bird, public Reptile
{
public:
Platypus ()
{
cout "Platypus constructor" endl;
}
};
int main ()
{
Platypus duckBilledP;
// , Animal
duckBilledP.Age = 25;
return 0;
}

Animal constructor
Platypus constructor

11.7, ,
A n im a l , , , ,
. v i r t u a l ,
Mammal, B i r d R e p t i l e ,
A n im a l,
P l a t y p u s . ; 41,
, 11.7.

295

,
, ,

, (diamond problem).
", ,
(. . 11.2),
.

virtual C++
. ( , -
apt.) .
,
, .
,

virtual, Derivedl Derived2,


Base, , , Derived3,
Derivedl Derived2,
Base.
, virtual
.

?
.
C ++ .
( , ) B a s e * ,
:
// Tuna, Carp Trout Fish
Fish* pFishes[3];
Fishes [0] = new TunaO;
Fishes[1] = new Carp();
Fishes[2] = new Trout();

,
, ,
T u n a, C a rp T r o u t T u n a, C a rp
T ro u t, , F is h * .
.
, v i r t u a l
, ,
, .
, , ,
, , C ++
.

296

11.


, :
class Fish

{
public:
virtual Fish* Clone() const = 0 ;

//

class Tuna:public Fish

{
// ...
public:
Tuna * Clone() const //

{
return new Tuna(*this); // Tuna,
//

, C lo n e ()
, , 11.9.

11.9. Tuna Carp Clone () ,


______________________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
class Fish
{
public:
virtual Fish* Clone
virtual void Swim()

()= 0;
= 0;

8: };
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28

class Tuna: public Fish


{

public:
Fish* Clone()
{
return new Tuna (*this);
}
void Swim()
{
cout

"Tuna swims fast in the sea"

}
};

class Carp: public Fish


{
Fish* Clone ()
{
return new Carp(*this);

endl;

297

void Swim ()

{
cout

"Carp swims slow in the lake"

endl;

6: int main()
const int ARRAY_SIZE = 4;
Fish* myFishes[ARRAY_SIZE] = {NULL};
myFishes[0] = new Tuna();
myFishes[1] = new Carp();
myFishes[2] = new Tuna();
myFishes[3] = new Carp();

Fish* myNewFishes[ARRAY_SIZE];
for (int Index = 0; Index < ARRAY_SIZE; ++Index)
myNewFishes[Index] = myFishes[Index]->Clone();

r6

49 :

5j:
52:

//
for (int Index = 0; Index < ARRAY_SIZE; ++Index)
myNewFishes[Index]->Swim();

53:
54:

//
for (int Index = 0; Index < ARRAY_SIZE; ++Index)

56:

{
delete myFishes[Index];
delete myNewFishes[Index];

53 :

59:

50:
return 0;

-2: -}

Tuna
Carp
Tuna
Carp

swims
swims
swims
swims

fast
slow
fast
slow

in
in
in
in

the
the
the
the

sea
lake
sea
lake

4 0 -4 4 m a in ()
F i s h *
T u n a , C a r p , T u n a C a r p .
, m y F is h e s , , ,
F i s h .
,
i n t . ,
m y N e w F is h e s F i s h *

298

11.

F i s h : : C l o n e ( ) , 48. , :
. ,
,
. 52 ,
F i s h : : S w im () , ,
C l o n e () T u n a T u n a , F i s h .
, .

,
,

vir
tual

C ++
.
, ,
,
. ,
,
,
, . ,
, , ,
.


v i r t u a l
, ?
v i r t u a l ,
o b j B a s e . F u n c t i o n ( ) ,
D e r i v e d : : F u n c t i o n ( ) . , .

299

?
,
.

?
. , :
Base* pBase = new Derived();
delete pBase;
delete Base*
~Derived(). ~Base()
.

,
?
;
. ,
, ,
.

v i r t u a l
?
v i r t u a l ,
.

- - ?
. , ,
,
.


, ,
. ,
, .
,
.


1. ( ) ,
A re a () P r i n t ( ). ?
2. ?
3. F i s h ,
-. ?

300

11.

1. , 1
.
2. : :
class Vehicle
{
public:
Vehicle () {}
^Vehicle (){}

};
class Car: public Vehicle
{
public:
Car() {}
~Car () {}

};
3.
2, :
Vehicle* pMyRacer = new Car;
delete pMyRacer;

12



c l a s s
, ,
.
, ,
, 5, ,
". ,
.
.

o p e r a t o r .

++11.

, .

302

12.

C++

o p e r a t o r .
:
_ _ operator _ ( . . . .. . ) ;

_ ,
. + ( ) && ( )
.. .
C ++ , ?
D a t e , , :
Date Holiday (25, 12, 2011); // 25 2011

, 26 ,
?

1. :

2. D a t e : : I n c r e m e n t ():

++ Holiday;

Holiday.Increment(); // 26 2011

, , I n c r e m e n t ( ) .
.
(<) D a t e :
if(Datel < Date2)

{
//

}
else
//

}
, , .
(+),
, , M y S t r i n g (. 9.9):
MyString sayHello ("Hello ");
MyString sayWorld ("world");
MyString sumThem (sayHello + sayWorld); // +
// ( 9.9)

C ++ :
.

303


, (unary operator)
. ,
-:
_ _ operator _ (_)

{
// ...

}
, , :
_ _ operator _ ()

{
// ...


, ( ),
. 12.1.

12.1.

++

->
1

NOT

&


(++)
:
// ()
Dates operator ++ ()

{
//
return *this;

(++), ,
( ):

304

12.

Date operator ++ (int)

{
// ,
//
Date Copy (*this);
// ( )
// ,
return ;

}
,
, , ++.
12.1 D a te , ,
(++).
1 2 .1 . , ,
, __________________________________________

0:
1:
2:
3:
4:
5:
6:

#include <iostream>
using namespace std;

class Date
{
private:
int Day; // : 1 - 3 0 ( ,
// 30 )
7:
int Month;
8:
int Year;
9:
10: public:
11:
// , ,
12:
Date (int InputDay, int InputMonth, int InputYear)
13:
: Day (InputDay), Month (InputMonth), Year (InputYear) {};
14:
15:
// ()
16:
Dates operator ++ ()
17:
{
18:
++Day;
19:
return *this;
20:
}
21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:

//
Dates operator ()
{
Day;
return *this;
}
void DisplayDate ()
{
cout Day " /
}

()

Month

" / "

Year

endl;

305

33: };
34:
35: int main ()
36: {
37:
//
// 25 2011
38:
Date Holiday (25, 12, 2011);
39:
40:
cout "The date object is initialized to: ";
41:
Holiday.DisplayDate ();
42:
43:
//
44:
++ Holiday;
45:
46:
cout "Date after prefix-incrementis: ";
47:
48:
//
49:
Holiday.DisplayDate ();
50:
51:
Holiday;
52:
Holiday;
53:
54:
cout "Date after two prefix-decrements is: ";
55:
Holiday.DisplayDate ();
*
56:
57:
return 0;
58: }

The date object is initialized to: 25 / 12 / 2011


Date after prefix-increment is: 26 / 12 / 2011
Date after two prefix-decrements is: 24 / 12 / 2011

16-27
D a te ,
44, 51 52 m a in ( ) .
, .

, ,

(++) ( ). , 30 ,
.


D a te :
//
//

306

12.

Date operator ++ (int)

{
// ,
//
Date Copy (Day, Month, Year);
++Day;
// ,
return ;

}
//
Date operator (int)

{
Date Copy (Day, Month, Year);
Day;
return Copy;

}
D a te
,
:
Date Holiday (25, 12, 2011);
++ Holiday; //
Holiday ++; //
Holiday; //
Holiday ; //

//
++
++

,
,
; .
, , ++
; ++;, ,
.


m a in () 12.1
cout

Holiday; // -

e r r o r : b i n a r y ' ' : n o o p e r a t o r
f o u n d w h ic h t a k e s a r i g h t - h a n d o p e r a n d o f t y p e ' D a t e ' ( o r t h e r e i s n o a c c e p t
a b l e c o n v e r s i o n ) ( : b i n a r y ' ' : ,
' D a t e 1 ( )). ,
, c o u t , D a te ,
.

307

c o u t c o n s t
ch a r* :
std::cout

"Hello world"; // const char* !

, c o u t D a te ,
, c o n s t c h a r * :
operator const char*()

{
// , char*

}
12.2 .

12.2. c o n s t ch a r* D ate
0:
1:
2:
3:
4:
5:
6:
7:
8:

#include <iostream>
#include <sstream>
#include <string>
using namespace std;
class Date
{

private:
int Day; // : 1 - 3 0 ( ,
// 30 )
9:
int Month;
10:
int Year;
11:

12:
string DatelnString;
13:
14: public:
15:
16:
// , ,
17:
Date (int InputDay, int InputMonth, int InputYear)
18:
: Day (InputDay), Month (InputMonth), Year (InputYear) {};
19:
20:
operator const char*()

21:

22:
ostringstream formattedDate;
23:
formattedDate Day " / " Month " / "
24:
25:
DatelnString = formattedDate.str();
26:
return DatelnString.c_str();
27:
}
28: };
29:
30: int main ()
31: {
32:
//

// 25 2011
33:
Date Holiday (25, 12,2011);
34:
35:
cout "Holiday is on: " Holiday endl;
36:
37:
return 0;
38: }

Year;

308

12.

Holiday is on: 25 / 12 / 2011

c o n s t
c h a r * ( 2 0 -2 7 )
35 m a in ( ) . D a te
c o u t , c o n s t
c h a r * . (
) c o u t ,
. c o n s t c h a r *
s t d : : o s t r i n g s t r e a m , s t d : : s t r i n g
( 23 25). f o r m a t t e d D a t e . s t r (),
D a t e : : D a t e l n S t r i n g ( 25),
f o r m a t te d D a t e ,
. , , s t r (), .
D a te .
:
string strHoliday (Holiday);

// OK!
// const char*
strHoliday = Date(11, 11, 2011); // OK!

,
.
, :

operator int()

{
//

}
Date :

SomeFuncThatTakesInt(Date(25, 12, 2011));

(*)
(->)
(*) (-> )
.
(sm art pointer) ,
( ),
.
.
26, ,
, .

309

s t d : : u n i q u e _ p t r 12.3
, (*) (-> )
.

12.3. unique_ptr
Date___________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <iostream>
#include <memory> // , std::unique_ptr
using namespace std;
class Date
{
private:
int Day;
int Month;
int Year;

10:
11:
string DatelnString;
12:
13: public:
14:
// , ,
15:
Date (int InputDay, int InputMonth, int InputYear)
16:
: Day (InputDay), Mopt.h (InputMonth), Year (InputYear) {};
17:
18:
void DisplayDate()
19:
{
20:
cout Day " / " Month " / " Year endl;

21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

}
};

int main()
{
unique_ptr<int> pDynamicAllocInteger(new int);
*pDynamicAllocInteger = 42;
// int*
cout "Integer value is: " *pDynamicAllocInteger
endl;
unique_ptr<Date> pHoliday (new Date(25, 11, 2011));
cout "The new instance of date contains: ";
// pHoliday Date*
pHoliday->DisplayDate();
// unique_ptr :
// delete pDynamicAllocInteger;
// delete pHoliday;
return 0;
}

310

12.

Integer value is: 42


The new instance of date contains: 25 / 11 / 2011

26 i n t .
u n iq u e _
p t r . 32
D a te . .

, ,
, 14, " .

,
( 30 36). 30
i n t , * p D y n a m i c A llo c I n t e g e r ,
36 p H o l i d a y - > D i s p l a y D a t a ( ) ,
i n t * D a te * .
s t d : : u n i q u e _ p t r , (*) (-> ). 12.4
.

12.4. (*) (->)


_______________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <iostream>
using namespace std;
template ctypename T>
class smart_pointer
{
private:
T* m_pRawPointer;
public:
smart_pointer (T* pData)

10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

~smart_pointer

T& operator* () const //


{
return * (m_pRawPointer);
}
T* operator-> () const //
{
return m_pRawPointer;
}

2 1 : };

22
23
24

: m_pRawPointer (pData) {}
//
() {delete m_pRawPointer ;} //

class Date

311

25: private:
26:
int Day, Month, Year;
1":
string DatelnString;
19: public:
22:
// , ,
21:
Date (int InputDay, int InputMonth, int InputYear)
22:
: Day (InputDay), Month (InputMonth), Year (InputYear) {};
24:
35:
26:
2 ":

void DisplayDate()
{
cout << Day " / "

Month << " / " << Year << endl;

43: int main()


42
43
44
45
46
47
43
49

smart_pointer<int> pDynamicInt(new int (42));


cout "Dynamically allocated integer value = "

*pDynamicInt;

smart_pointer<Date> pDate(new Date(25, 12, 2011));


cout "Date is = ";
pDate->DisplayDate();
return 0;

53

Dynamically allocated integer value = 42


Date is = 25 / 12 / 2011

12.3, s m a r t _ p o i n t e r ,
3 -2 4 . ,
, ,
i n t , 45, D a te , 48.
, ,
7. ,
, ,
, 10. , ,
new, d e l e t e
, .
* 12-15, & (.. ,
).
( 14). -> , 17-20, *
(.. , ).
-> 19 .
, s m a r t _ p o i n t e r
,
.

312

12.

,
,
.
26, .
unique_ptr 12.3 ,
, ,
<memory>,
.


, ,
(binary operator). ,
-, :
_ _ _ (1, 2) ;

, ,
:
_ _ _ ();

,
.


,
C++, .* 12.2.

12.2.

I =

,__

&

AND

&&

AND

&=

AND

*=

+=

-=

-> *

313

. 12.2

/=

<

<=

==

>

>=

>>

OR

__

OR

OR

|=

OR

11

OR

[]


( +) ( - )
,
, ,
, .
D a te . ,
,
, , .
(+), 12.5.
1 2 .5 . __________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <iostream>
using namespace std;
class Date
{
private:
int Day, Month, Year;
public:
// , ,

314
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31: };
32:
33: int
34: {
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50: }

12.
Date (int InputDay, int InputMonth, int InputYear)
: Day (InputDay), Month (InputMonth), Year (InputYear)

{};

//
Date operator + (int DaysToAdd)
{
Date newDate (Day + DaysToAdd, Month, Year);
return newDate;
}
//
Date operator - (int DaysToSub)
{
return Date(Day - DaysToSub, Month, Year);
}
void DisplayDate ()
{
cout Day " / "
}

Month

" / "

Year

endl;

main ()
//
// 25 2011
Date Holiday (25, 12, 2011);
cout "Holiday on:
Holiday.DisplayDate

";
();

Date PreviousHoliday (Holiday - 19);


cout "Previous holiday on: ";
PreviousHoliday.DisplayDate();
Date NextHoliday(Holiday + 6);
cout "Next holiday on: ";
NextHoliday.DisplayDate ();
return 0;

Holiday on: 25 / 12 / 2011


Previous holiday on: 6 / 12 / 2011
Next holiday on: 31 / 12 / 2011

14-25 (+) ( -) ,
, 41
45 m a in ().

315


. 9, ,
M y S tr in g , ,
(. 9.9). ,
:
MyString Hello("Hello ") ;
MyString World(" World");
MyString HelloWorld(Hello + World); // : +

, (+)
M y S trin g , , :
MyString operator* (const MyString& AddThis)

{
MyString NewString;
if (AddThis.Buffer != NULL)

{
NewString.Buffer = new char[GetLength() \
+ strlen(AddThis.Buffer) + 1];
strcpy(NewString.Buffer, Buffer);
strcat(NewString.Buffer, AddThis.Buffer);

}
return NewString;

}
,
9.9 M y S tr in g ()
. M y S tr in g (+)
12.12.
.
, .
, Date ,
MyString (+).
,
.


(+=) (-=)
, += ; ,
.
, ,
b . 12.6
C D ate.

316

12.

12.6. (+=) (-=)


_______________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

#include <iostream>
using namespace std;
class Date
{
private:
int Day, Month, Year;
public:
// , ,
Date (int InputDay, int InputMonth, int InputYear)
: Day (InputDay), Month (InputMonth), Year (InputYear) {};
//
void operator+= (int DaysToAdd)
{
Day += DaysToAdd;
}
// Binary subtraction assignment
void operator-= (int DaysToSub)
{

Day -= DaysToSub;
}
voidDisplayDate
()
{
cout Day " / "
}

Month

" / "

};

int main()
{
//
// 25 2011
35:
Date Holiday (25, 12, 2011);
36:
37:
cout "Holiday is on: ";
38:
Holiday.DisplayDate ();
39:
40:
cout "Holiday -= 19 gives: ";
41:
Holiday -= 19;
42:
Holiday.DisplayDate();
43:
44:
cout "Holiday + = 2 5 gives: ";
45:
Holiday += 25;
46:
Holiday.DisplayDate ();
47
48
return 0;
49 }

Year

endl;

317

Holiday is on: 25 / 12 / 2011


Holiday -= 19 gives: 6 / 12 / 2011
Holiday += 25 gives: 31 / 12 / 2011

,
14-24.
m a in ( ) , , :
41:
45:

Holiday -= 19;
Holiday += 25;

D a te ,
, ,
i n t .
(+=), CDays:
// , CDays
void operator += (const CDays& mDaysToAdd)

{
Day += mDaysToAdd.GetDays ();

*=,
/=, %=, -=,
= , = , X0R
=, OR | = AND
&= ,
12.6.
-
, ,
. ,
Date
AND &=.
( ) , , ,
greatDay &= 20;.

(=) (!=)
D a te ,
:
if (Datel == Date2)

{
//
else

{
//

318

12.


t r u e , .
( D a te ), ,
, , ,
, ( c h a r * ) , M y S trin g ,
9.9.
, (
), f a l s e .
, .
:
bool operator== (const & )

{
// , true false
//

}
:
bool operator!= (const & )

{
I I , true false
/ /

}
( N O T )
. 12.7 ,
D a te .

12.7. == !=________________________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:

#include <iostream>
using namespace std;
class Date
{
private:
int Day, Month, Year;
public:
// , ,
Date (int InputDay, int InputMonth, int InputYear)
: Day (InputDay), Month (InputMonth), Year (InputYear) {};
bool
{

operator== (const Dates compareTo)


return ((Day == compareTo.Day)
SS (Month == compareTo.Month)
SS (Year == compareTo.Year));

}
bool
{

operator!= (const Dates compareTo)

46:
47:
48:

void DisplayDate ()
{
cout Day " / "
}

Month

V
V

44:
45:

return !(this->operator==(compareTo));
}

V
V

23:
24:
25:
26:
27:
28:
29:
30: };
31:
32: int
33: {
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:

319

main ()
Date Holidayl (25, 12, 2011);
Date Holiday2 (31, 12, 2011);
cout "Holiday 1 is: ";
Holidayl.DisplayDate();
cout "Holiday 2 is: ";
Holiday2.DisplayDate();
if (Holidayl == Holiday2)
cout "Equality operator: The two are on
endl;
else
cout "Equality operator: The two are on
endl;
if (Holidayl != Holiday2)
. cout "Inequality operator: The two are <
endl;
else
cout "Inequality operator: The two are <
endl;

49:
50:
51:
52:
53: }

return 0;

Holiday 1 is: 25 / 12 / 2011


Holiday 2 is: 31 / 12 / 2011
Equality operator: The two are on different days
Inequality operator: The two are on different days

(==) ,
, , , 14-19.
(! =) ,
23. ( H o l i d a y l
H o lid a y 2 ) D a te m a in () ( 42 47).

320

12.

<, >, <= >=


12.7 D a te ,
, D a te .
, :
if (Datel < Date2)

{// }

:
if (Datel <= Date2)

{// }

:
if (Datel > Date2)

{// }

:
if (greatDay >= Date2)

{// }

,
, ,
. ,

, , 12.8.

12.8. =, > >=___________________________________


0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

22:
23:
24:
25:
26:
27:

#include <iostream>
using namespace std;
class Date
{
private:
int Day, Month, Year;
public:
// , ,
Date (int InputDay, int InputMonth, int InputYear)
: Day (InputDay), Month (InputMonth), Year (InputYear) {};
bool operator== (const Dates compareTo)
{
return ((Day == compareTo.Day)
&& (Month == compareTo.Month)
&& (Year == compareTo.Year));
}
bool operator< (const Dates compareTo)

{
if (Year < compareTo.Year)
return true;
else if (Month < compareTo.Month)
return true;
else if (Day < compareTo.Day)

return true,*'

else

20
21

return false;

22

23
34
35
26
37
28

bool operator<= (const Dates compareTo)

39

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81

{
if (this->operator== (compareTo))
return true;
else
return this->operator< (compareTo);

bool operator > (const Dates compareTo)

{
return !(this->operator<= (compareTo));

}
bool operator>= (const Dates compareTo)

{
if(this->operator== (compareTo))
return true;
else
return this->operator> (compareTo);

}
bool operator!= (const Dates compareTo)

{
return !(this->operator==(compareTo));

}
void DisplayDate ()

{
cout

Day

" / "

Month

" / "

Year

int main()

11 3ak. 3626

Date Holidayl (25, 12, 2011);


Date Holiday2 (31, 12, 2011);
cout "Holiday 1 is: ";
Holidayl.DisplayDate();
cout "Holiday 2 is: ";
Holiday2.DisplayDate();
if (Holidayl < Holiday2)
cout "operatorC Holidayl happens first"

endl;

if (Holiday2 > Holidayl)


cout "operator>: Holiday2 happens later"

endl;

if (Holidayl <= Holiday2)1

endl;

321

322

12.

82:

cout

83:
84:
85:

"operator<=: Holidayl happens on or before Holiday2"


endl;

if (Holiday2 >= Holidayl)


cout "operator>=: Holiday2 happens on or after Holidayl"

endl^-

eS:
87:

return 0;

88:

Holiday 1 is: 25 / 12 / 2011


Holiday 2 is: 31 / 12 / 2011
operatorc Holidayl happens first
operator>: Holiday2 happens later
operator<=: Holidayl happens on or before Holiday2
operator>=: Holiday2 happens on or after Holidayl

2 1 -5 2
== 12.7. ,
: .
7 5 -8 4 m a in () ,
D a te
.

(=)

:
Date Holiday(25, 12, 2011);
Date AnotherHoliday(1, 1, 2010);
AnotherHoliday = Holiday; //

,
, .
,
, .
, ,
:
ClassType& operator= (const ClassType& CopySource)

{
if(this != &copySource) //

{
//

}
return *this;

323

, , ,
M y S tr in g , 9.9.
, ,
, c h a r * B u f f e r , ,
, . ,
.
, , 12.9.

12.9. MyString 9.9


_______________________
0
1

#include <iostream>
using namespace std;

3
4
5

6
7
8
9

10
11
12

13
14
15
16
17
18
19
20

21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

class MyString

{
private:
char* Buffer;
public:
//
MyString(const char* Initiallnput)

{
if(Initiallnput != NULL)

{
Buffer = new char [strlen(Initiallnput) + 1];
strcpy(Buffer, Initiallnput);

}
else
Buffer = NULL;

}
// 9.9
MyString(const MyString& CopySource);
//
MyString& operator= (const MyString& CopySource)

{
if ((this != &CopySource) && (CopySource.Buffer != NULL))

{
if (Buffer != NULL)
delete[] Buffer;
//
//
Buffer = new char [strlen(CopySource.Buffer) + 1];
//
strcpy(Buffer, CopySource.Buffer);

}
return *this;

324
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:

12.
I I
-MyString ()
{
if (Buffer != NULL)
delete [] Buffer;
}
int GetLengthO
{
return strlen(Buffer);
}
operator const char*()
{
return Buffer;
}
};
int main ()
{
MyString Stringl("Hello ");
MyString String2(" World");
cout
"Before assignment: " endl;
cout
Stringl String2 endl;
String2 = Stringl;
cout "After assignment String2 = Stringl: "
cout
Stringl String2 endl;

endl;

return 0;
}

Before assignment:
Hello World
After assignment String2 = Stringl:
Hello Hello

,
( ; . 9.9).
2 5 -3 9 .
, , ,
.
M y S tr in g ,
, s t r c p y () ,
36.

325

12.9 9.9 ,
Getstring () const char*,
53-56. MyString,
68, cout
MyString.

,
, , ..,
( )

.
,
, .

, ,
. (
) ,

.

([])
[ ], ,
(subscript operator).
:
_ _ operator [] (_& );

, , M y S tr in g ,
c h a r * B u f f e r ,
:
class MyString

{
// ...
public:
/*const*/ char& operator [] (int Index) /*const*/

{
//

}
};
12.10 , ( [ ])
, M y S tr in g ,
.

326

12.

12.10. ([ ]) Mystring,
MyString::Buffer
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
#include <string>
using namespace std;
class MyString
{
private:
char* Buffer;

8:

9:
//
10:
MyString() {}
11:
12: public:
13:
//
14:
MyString(const char*Initiallnput)
15:
{
16:
if(Initiallnput != NULL)
17:
{
18:
Buffer = new char [strlen (Initiallnput) + lb19:
strcpy(Buffer, Initiallnput);
20:
}
21:
else
22:
Buffer = NULL;
23:
}
24:
25:
// : 9.9
26:
MyString(const MyString& CopySource);
27:
28:
// : 12.9
29:
MyString& operator= (const MyString& CopySource);
30:
31:
const char& operator[] (int Index) const
32:
{
33:
if (Index < GetLengthO)
34:
return Buffer[Index];
35:
}
36:
37:
//
38:
~MyString()
39:
{
40:
if (Buffer != NULL)
41:
delete [] Buffer;
42:
}
43:
44:
int GetLengthO const
45:
{
46:
return strlen(Buffer);
47:
}
48:
49:
operator const char*()
50:
{
return Buffer;
51

327

:5: int main()

: 6: {
53:
:9:
cl:

cout "Type a statement: ";


string strlnput;
getline(cin, strlnput);
MyString youSaid(strlnput.c_str());

t2 :
-3:
t'4:
-5:
~6:

cout "Using operator[] for displaying your input: "


for(int Index = 0; Index < youSaid. GetLength () ; ++Index)
cout youSaid [Index] " ";
cout endl;

endl;

il:
t8:
i9 :
"9:
1:
"2:
"3:
~4:
"5: }

cout "Enter index 0 - " youSaid.GetLength() - 1 ": ";


int Inindex = 0;
cin Inindex;
cout "Input character at zero-based position: " Inindex;
cout " is: " youSaid[Inindex] endl;
return 0;

Type a statement: Hey subscript operators[] are fabulous


Using operator[] for displaying your input:
H e y s u b s c r i p t o p e r a t o r s [ ] a r e f a b u l o u s
Enter index 0 - 3 7 : 2
Input character at zero-based position: 2 is:

, , M y S tr in g ,
, 61, f o r
( [ ]) ,
( 64 65). ( [ ]) 3 1 -3 5 ,
, ,
c h a r * B u f f e r . ,
, ,
12.10. ,
, , .
:
, :
char& operator [] (int nlndex); // /
//
char& operator [] (int nlndex) const; //
/ /

328

12.


const.
, 12.10
([ ]) const char&.
const,
, :

MyString sayHello("Hello World");


sayHello[2] = 'k' // : operator[]
const
MyString::Buffer
[]. const,
const,
.
, const,

.

,
M y S tr in g .
, ( )
. , ,
. (. . 12.2),
, .
, .
, , ,
. , , D a te ,
, ,
, , .
,
.

()
(), , ,
(function operator). (STL)
, , STL.
;
(predicate), . 12.11
, , !

12.11. , ( )_______________
1: #include <iostream>
2: #include <string>
3:using namespace std;
4:
5: class CDisplay

()
6:

329

7: public:
8:
void operator () (string Input) const
9:
{
10:
cout << Input endl;
11:
1 2 : };

13:
14:int main ()
15: {
16:
CDisplay mDisplayFuncObject;
17:
18:
//
// mDisplayFuncObject.operator () ("Display this string!");
19:
mDisplayFuncObject ("Display this string!");
20:

21:
22:

return 0;

Display this string!

8-11 ( ) , 18
m a in (). , m D is p la y F u n cOb j e c t ( 18) ,
() .
, ( ) ,
C D is p la y , (functor).
21, .

++11____________________________________________



, --11,
, (r-, )
. ,
, , .


, 12.5,
. .
, M y S tr in g ,
:

330

12.

MyString Hello("Hello ");


MyString World("World");
MyString CPP(" of C++");
MyString sayHello(Hello + World + CPP); // +,
MyString sayHelloAgain ("overwrite this");
sayHelloAgain = Hello + World + CPP;
// +, ,
// =

,
(+), :
MyString operator+ (const MyString& AddThis)

{
MyString NewString;
if (AddThis.Buffer != NULL)

{
// NewString

}
return NewString; // ,
//

}
(+),
,
. s a y H e l l o
; + ,
M y S tr in g ,
.
, . ,
(-),
, , ,
C++. , .
. + + 1 1

, .



:
Class MyClass
private:
Type* PtrResource;
public:
MyClass(); //
MyClass(const MyClass& CopySource); //
MyClass& operator= (const MyClassS CopySource); //
//
MyClass(MyClass&& MoveSource) // ,
// &&

()

331

{
PtrResource = MoveSource.PtrResource; // ,
//
MoveSource.PtrResource = NULL;

}
MyClass& operator= (MyClass&& MoveSource) //
// , &&

{
if(this != &MoveSource)
delete [] PtrResource; //
PtrResource = MoveSource.PtrResource; //
// ,
MoveSource.PtrResource = NULL; //
//

}
,
,
MyClass&&. ,
, , .
,
.
C + + ,
(r-) , ,
.

. 12.12
++11 M y S tr in g .

12.12. MyString
_______
0: #include <iostream>
1: using namespace std;
2:

3: class MyString
4: {
5: private:
6:
char* Buffer;
7:
8:
//
9:
MyString(): Buffer(NULL)
10:

11:
cout "Default constructor called"
12:
}
13:
14: public:
15:
//
16:
~MyString()

endl;

332
17:
18:
19:
20:
21:
22:
23:
24:

25 :
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:

66:
67:

12.

if (Buffer != NULL)
delete [] Buffer;

}
int GetLengthO

{
return strlen(Buffer);

}
operator const char*()

{
return Buffer;

MyString operator* (const MyStringS AddThis)

{
cout operator* called: "
MyString NewString;
if (AddThis.Buffer

endl;

NULL)

{
NewString.Buffer = new char[GetLength() \
+ strlen(AddThis.Buffer) + 1];
strcpy(NewString.Buffer, Buffer);
strcat(NewString.Buffer, AddThis.Buffer);

return NewString;

}
//
MyString(const char* Initiallnput)

{
cout "Constructor called for: "
if(Initiallnput != NULL)

Initiallnput

endl;

{
Buffer = new char [strlen(Initiallnput) + 1];
strcpy(Buffer, Initiallnput);

}
else
Buffer = NULL;

}
//
MyString(const MyString& CopySource)

{
cout"Copy constructor to copy from: " CopySource.Buffer
endl;
if(CopySource.Buffer != NULL)

{
// ,
//
Buffer = new char [strlen(CopySource.Buffer) + 1];

68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:

//
strcpy(Buffer, CopySource.Buffer);
else
Buffer = NULL;

}
//
MyString& operator= (const MyString& CopySource)

{
cout"Copy assignment operator to copy from: "
CopySource.Buffer endl;
if ((this != &CopySource) && (CopySource.Buffer != NULL))
{
if (Buffer != NULL)
delete[] Buffer;

80:
81:
82:
83:
84:
85:

// ,
//
Buffer = new char [strlen(CopySource.Buffer) + 1];

86 :
87:
88:

89:
90:
91:
92:
93:
94:
95:
96:
97:
98:

//
strcpy(Buffer, CopySource.Buffer);

return *this;

}
//
MyString(MyString&& MoveSource)

{
cout "Move constructor to move from: "
MoveSource.Buffer endl;
if(MoveSource.Buffer != NULL)

99:
100:
101:

{
Buffer = MoveSource.Buffer; //
//
MoveSource.Buffer = NULL;
//
//

102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:

113:
114:


.e . ''

}
}
//
MyStringS operator= (MyString&& MoveSource)

{
cout"Move assignment operator to move from: "
MoveSource.Buffer endl;
if ((MoveSource.Buffer != NULL) && (this != &MoveSource))
{
delete Buffer; //
Buffer = MoveSource.Buffer; //
// .e . ''

334

12.
MoveSource.Buffer = NULL; //
//

115:
116
117
118
119
1 2 0 : };
121
122 int
123: {
124
125
126
127
128
129
130
131
132: }

return *this;

main ()
MyString Hello("Hello ");
MyString World("World");
MyString CPP(" of C++");
MyString sayHelloAgain ("overwrite this");
sayHelloAgain = Hello + World + CPP;
return 0;


( 95-119):
Constructor called for: Hello
Constructor called for: World
Constructor called for: of C++
Constructor called for: overwrite this
operator+ called:
Default constructor called

Copy constructor to copy from: Hello World


operator+ called:
Default constructor called

Copy constructor to copy from: Hello World of C++


Copy assignment operator to copy from: Hello World of C++
:
Constructor called for: Hello
Constructor called for: World
Constructor called for: of C++
Constructor called for: overwrite this
operator+ called:
Default constructor called

Move constructor to move from: Hello World


operator+ called:
Default constructor called

Move constructor to move from: Hello World of C++


Move assignment operator to move from: Hello World of C++

335

,
.
95-119,
. ,
++11, . ,
, .

, ,
( 101
114 ).
N U LL ( 102
115). , ,
d e l e t e ( 16-20) ,
. ,
,
. ,

.

. ,
.
+ + 11 ,
,
, .

,

, C ++
,
, . ,
, . 12.3.
12.3. ,

::

? :

sizeof

*36

12.

,
,

,

,
,
,


( )
,


(
) ,
, ,
,
, C++! 1

,

,
,


,
,

,
,
(*) (->),
,

, . , ,
, .
, , , , .
I , , ,
s i z e o f ,
[.


I .
?

,
, ,
, . ,
, .

337

,
.

o b j e c t . : co u t
o b je c t;. ?
,
, s t d : : c o u t .
, c h a r * (),
12.2.

.
?

: * p S m a r t P t r p S m a r t P t r - > F u n c ( ) . (*)
(-> ). , ,
, ,
, ,
,
.


, ,
. ,
, .
,
.


1. [ ]
?
const Types o p erator[ ] (int Index);
Types o p erator[ ] (in t Index); / / ?
2.
p riv a te ?
3.
D a te ?

1. D a te ,
.
2.
D y n I n t e g e r s ,
i n t * .

13

(casting) ,
.
,
. , ,
(casting operator).
.


C++.

C++.

C++
.

340

13.


C++
.
,
, .

, .
: C++
b o o l , ,
, .

. , b o o l
:
typedef unsigned short BOOL;

, ,
BOOL IsX ();

, ,
C++,
B00L, , C++.
:
bool bCPPResult = (bool)IsX (); //

C++ ,
C ++ :
,
, C++.
: C++
, , ,
. ,
C++, .
,
,
.



C++
(type safety) ,
C++, .
C++ :

C++

341

char* pszString = "Hell'o World!";


int* pBuf = pszString; // : char* int*

.. ., !
C++
,
,
int* pBuf = (int*)pszString; //


, ,
, ,
, , . ,
C++, , ,
, - .

C++
,
.
. , C ++ ,
, .
C++:

s ta tic _ c a s t

d y n a m ic _ c a s t

re in te rp re t_ c a s t

c o n s t_ c a s t
:
_ = _ <_> (_);

sta tic_ ca st
s t a t i c _ c a s t
,
. ,
s t a t i c _ c a s t
. ,

. s t a t i c c a s t ,
, :
Base* pBase = new Derived ();
// Derived
Derived* pDerived = static_cast<Derived*>(pBase); // ok!
// CUnrelated Base
CUnrelated* pUnrelated = static_cast<CUnrelated*>(pBase); //
// ,

342

13.


(upcast) :

Derived objDerived;
Base* pBase = &objDerived; // ok!

(downcast)
:

Derived objDerived;
Base* pBase = &objDerived; // -> ok!
Derived* pDerived = pBase; // :

, s t a t i c _ c a s t ,
. . ,
s t a t i c _ c a s t :
Base* pBase = new Base ();
Derived* pDerived = static_cast<Derived*>(pBase); //
// !

p D e r i v e d D e r iv e d ,
, , B a se ().
s t a t i c c a s t ,
, , p D e r iv e d > S o m e D e r iv e d C la s s F u n c tio n () , , ,
.
, s t a t i c _ c a s t

:
double dPi = 3.14159265;
int Num = static_cast<int>(dPi); //

Num = d P i
. s t a t i c _ c a s t
(, s t a t i c _ c a s t ) ,

, .

dynamic_cast

, ,

( ) .
d y n a m ic c a s t ,
.
d y n a m ic _ c a s t :

C++

343

_* = dynamic_cast <_*> () ;
if () I I ,
//
->();

:
Base* pBase = new Derived();
//
Derived* pDerived = dynamic_cast <Derived*> (pBase);
if (pDerived) //
pDerived->CallDerivedClassFunction ();

,
, d y n a m ic _ c a s t ,
, .
: , D e r iv e d .
. , ,
D e r iv e d * , B a se * .
d y n a m i c _ c a s t ,
, , . ,
d y n a m i c _ c a s t
, . 13.1
T una C a rp , F is h , D e te c t F is h T y p e ()
, F is h * T una*
C a rp * .


(runtime type
identification), R777.

1 3 .1 . ,
Fish Tuna Carp_______________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

#include <iostream>
using namespace std;
class Fish
{
public:
virtual void Swim()
{
cout "Fish swims in water"
}

endl;

//
virtual -Fish() {}
};
class Tuna: public Fish

344
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67
68
69

13.
{
public:
void Swim()
{
cout

"Tuna swims real fast in the sea"

endl;

void BecomeDinner()
{
cout "Tuna became dinner in Sushi"
}

endl;

};
class Carp: public Fish
{
public:
void Swim()
{
cout "Carp swims real slow in the lake"
}
void Talk()
{
cout
}

"Carp talked crap"

endl;

endl;

};
void DetectFishType(Fish* InputFish)
{
Tuna* pIsTuna = dynamic_cast <Tuna*>(InputFish);
if (pIsTuna)
{
cout "Detected Tuna. Making Tuna dinner: " endl;
pIsTuna->BecomeDinner(); // Tuna::BecomeDinner
}
Carp* plsCarp = dynamic_cast <Carp*>(InputFish);
if(plsCarp)
{
cout "Detected Carp. Making carp talk: "
pIsCarp->Talk(); // Carp::Talk
}

endl;

cout "Verifying type using virtualFish::Swim:


"
InputFish->Swim(); // Swim
}
int main()
{
Carp myLunch;
Tuna myDinner;
DetectFishType(SmyDinner);
cout endl;

endl;

C++
70:
71:
72:
73:}

345

DetectFishType(&myLunch);
return 0;

Detected Tuna. Making Tuna dinner:


Tuna became dinner in Sushi
Verifying type using virtual Fish::Swim:
Tuna swims real fast in the sea
Detected Carp. Making carp talk:
Carp talked crap
Verifying type using virtual Fish::Swim:
Carp swims real slow in the lake

T u n a , C a r p F i s h , 10,
. ,
. S w im ( ), ,
, T u n a : : B e c o m e D in n e r ( ) C a r p : : T a l k ( ) .
, , F i s h * ,
, T u n a C a r p .

D e t e c t F i s h T y p e ( ) , 4 3 -6 1 . 45 d y n a m ic _ c a s t
F i s h *
T u n a * . T u n a , ,
N U LL. , d y n a m ic c a s t
. 46
, p I s T u n a T u n a ,
T u n a : : B e c o m e D in n e r ( ) ,
49. C a r p : : T a l k ( ) ,
56. D e t e c t F i s h T y p e ()
, F i s h : : S w im ( ), , ,
S w im ( ) , T u n a C a r p .
dynamic_cast
. ,
NULL.

reinterpret_cast
C ++ r e i n t e r p r e t c a s t .
, ,
, .. :

346

13.

Base * pBase = new Base ();


CUnrelated * pUnrelated = reinterpret_cast<CUnrelated*>(pBase);
// , !

,
s t a t i c _ c a s t .
(, , ),
, A PI ( ,
A PI , .. u n s i g n e d c h a r * ):
SomeClass* pObject = new SomeClass ();
// ...
unsigned char* pBytes = reinterpret_cast cunsigned char*>(pObject);

, ,
,
, S o m e C la s s .
C ++ , r e i n t e r p r e t _ c a s t
.

r e i n t e r p r e t ^
c a s t ,
X Y, ,
.

const_cast
c o n s t _ c a s t c o n s t .
, , , , .
, ,
c o n s t . ,
, , :
class SomeClass
{
public:

//

. . .

void DisplayMembers ; //
//

};
, , :
void DisplayAllData (const SomeClass& mData)

{
mData.DisplayMembers (); //
// :
//

C++

347

, , m D ata .
,
-, ..
, . D isp la y M e m c e r s ( ), , , .
S o m eC lass ,
D isp la y M e m b e rs ().
,
. c o n s t c a s t .
D is p la y M e m b e rs () :
void DisplayAllData (const SomeClass& mData)

{
SomeClass& refData = const_cast <SomeClass&>(mData);
refData.DisplayMembers(); // !

, c o n s t _ c a s t
. ,
c o n s t _ c a s t
.
, c o n s t _ c a s t :
void DisplayAllData (const SomeClass* pData)

{
// pData->DisplayMembers(); // :
// !
SomeClass* pCastedData = const_cast <SomeClass*>(pData);
pCastedData->DisplayMembers(); // !


C++
C++, ,
.
.
:
double dPi = 3.14159265;
// C++: static_cast
int Num = static_cast <int>(dPi); // : nNum 3
//
int Num2 = (int)dPi; // : Num2 3
//
int Num3 = dPi; // : Num3 3. !

.
, , , .

348

13.

. ,
, . ,
.
, s t a t i c c a s t
, , , :
/ / s t a t i c _ c a s t
Derived* pDerived = s t a t i c _ c a s t <D erived*>(pBase);
/ / . . .
Derived* pDerivedSimple = (Derived*) pBase;
, s t a t i c c a s t
. (B jam e
Stroustrup) : , s t a t i c _ c a s t
, , , ,
. , C ++
, , . (. frequently asked questions
about C ++ style and technique h t t p : / / w w w . r e s e a r c h . a t t . c o m /~ b s /b s _ f a q 2 . h tm l.)
. r e i n t e r p r e t c a s t
, s t a t i c _ c a s t ;
c o n s t c a s t , c o n s t . ,
C++, d y n a m ic c a s t , C++.
,
.
, C++
. ,
, , , ,
.

, D e riv e d *

Base* ,

dynamic_cast

, Base*
Derived*
, ,
dynamic^

RTTI
dynamic_cast

cast
,

,

349

C++,
. ,
.



co n st_ c a st?
, .
.

B ird*, Dog*.
Dog B ird*. ,
r e in t e r p r e t _ c a s t Dog* B ird*,
, , F ly () Bird. ?
. r e i n t e r p r e t _ c a s t
, , (
Dog). F l y () D og ,
.

D erived pBase, Base*.


, pBase D erived ,
dynam ic_cast?
, , , D e r iv e d ,
s t a t ic _ c a s t .

C++ ,
. ?
, ,
, ? , .


, ,
. ,
, .
,
.


1. p B a s e .
, : D e r i v e d l D e r iv e d 2 ?

350

13.

2. , . ,
.
c o n s t _ c a s t ?
3. r e i n t e r p r e t _ c a s t ,
s t a t i c c a s t , ,
. ?
4. , , s t a t i c _
c a s t , , C ++
?

1. : ?
void DoSomething(Base* pBase)

{
Derived* pDerived = dynamic_cast <Derived*>(pBase);
pDerived->DerivedClassMethod();

}
2. p F is h * , T una.
Fish* pFish = new Tuna;
Tuna* pTuna = <what cast?>pFish;

, T una*
T una? .

14



C++. , C++,
, ,
.
.

#def ine .

++11
, static_assert.

352

14.


2, C + + .
(preprocessor), ,
. ,
, . (preprocessor
directive) #. :
// iostream
#include <iostream>
//
#define ARRAY_LENGTH 25
int MyNumbers[ARRAY_LENGTH]; // 25
//
#define SQUARE() (() * ())
int TwentyFive = SQUARE(5);

,
; # d e f i n e
, . ,
,
(A R R AY LEN G TH SQUARE) , .

.
, .

#deine

# d e f i n e :
#define

, ARRAY_LENGTH , 25, :
#define ARRAY_LENGTH 25

A R R A Y _ LE N G T H 25 ,
:
int MyNumbers [ARRAY_LENGTH] = {0};
double Radiuses [ARRAY_LENGTH] = {0.0};
std::string Names [ARRAY_LENGTH]';

#define
int MyNumbers [25] = {0};
double Radiuses [25] = {0.0};
std::string Names [25];

353

// 25
// 25 double
// 25 std::strings

, f o r , :
for(int Index = 0; Index < ARRAY_LENGTH; ++Index)
MyNumbers[Index] = Index;

f o r :
for(int Index = 0; Index < 25; ++Index)
MyNumbers[Index] = Index;

, 14.1.

14.1. ,
0:
1:
2:
3:
4:
5:
6:
7:

tinclude <iostream>
#include<string>
using namespace std;
#define
#define
#define
#define

ARRAY_LENGTH 25
PI 3.1416
MYJXXJBLE double
FAV_WHISKY "Jack Daniels"

8:

9: int main()
10: {
11:
int MyNumbers [ARRAY_LENGTH] = {0};
12:
cout "Array's length: " sizeof(MyNumbers) / sizeof(int)
endl;
13:
14:
cout "Enter a radius: ";
15:
MY_DOUBLE Radius = 0;
16:
cin Radius;
17:
cout "Area is: " PI * Radius * Radius endl;
18:
19:
string FavoriteWhisky (FAV_WHISKY);
20:
cout "My favorite drink is: " FAV_WHISKY endl;
21:
22:
return 0;
23: }

Array's length: 25
Enter a radius: 2.1569
Area is: 14.7154
My favorite drink is: Jack Daniels

ARRAY_LENGTH, P I, MY_DOUBLE FAV_WHISKY -,


3 -7 . ,

12 3. 3626

354

14.

11,
s i z e o f () 12. M Y_D O U B LE
R a d iu s d o u b le 15, P I
17. , F A V _ W H IS K Y
s t d : : s t r i n g 19
c o u t ( 20). ,
.
, , ,
14.1, .
,
( ).
f a v _ w h i s k y 7 14.1 :

#define FAV_WHISKY 42 // "Jack Daniels"


19
std::string, ,
:

favorite drink is: 42


, , , ,
. ,
p i : double float? :
. pi - , 3.1416.
.
, const
. :

const int ARRAY_LENGTH = 25;


const double PI = 3.1416;
const char* FAV_WHISKY = "Jack Daniels";
typedef double MY_DOUBLE; // typedef



C++, ,
. h, (header file).
. , ,
# i n c l u d e <>.
( c l a s s l .h ) , ,
c l a s s 2 .h , c l a s s l .h c l a s s 2 .h .
,
c l a s s 2 . h c l a s s l . h!
, ,
. ,
# i f n d e f # e n d if .
h e a d e r 1 . h, h e a d e r 2 . h, :

#(1
#ifndef HEADER1_H_
#define HEADER1_H_

355

// :
//
//

#include <header2.h>
class Classl
{
//

};
#endif // headerl.h

h e a d e r 2 . h ,
h e a d e r l . h :
#ifndef HEADER2_H_ //
#define HEADER2_H_
#include <headerl.h>
class Class2
{
//

};
#endif // header2.h

#ifndef .
,
, . #endif
.

, h e a d e r l . h ,
# i f n d e f , , HEADER1_H_
, . # i f n d e f
HEADER1_H_, ,
, # i f n d e f ,
. h e a d e r 2 ,h . ,
,
C++.

#define

,
, , :
#define SQUARE() (() * ())

. ,
, :
#define PI 3.1416
#define AREA_CIRCLE(r)

(PI*(r) * (r) )

356

14.

(m acro function)
. ,
, ,
. 14.2
.
14.2. , ,
, ________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:

#include <iostream>
#include<string>
using namespace std;
#define
#define
#define
#define
#define

SQUARE(x) ((x) * (x))


PI 3.1416
AREA_CIRCLE(r) (PI*(r)* (r))
MAX (a, b) (((a) > (b) ) ? (a) : (b) )
MIN(a, b) (((a) < (b)) ? (a) : (b))

int main()
{

cout "Enter an integer: ";


int Inputl = 0;
cin Inputl;
cout
cout
cout

"SQUARE(" Input1 ") = "


"Area of a circle with radius
AREA_CIRCLE(Inputl) endl;

SQUARE(Input1) endl;
" Inputl " is:

cout "Enter another integer: ";


int Input2 = 0;
cin Input2;
cout "MIN(" Inputl ", " Input2
cout MIN (Inputl, Input2) endl;

") = ";

cout "MAX(" Inputl ", " Input2


cout MAX (Inputl, Input2) endl;

") = ";

return 0;
}

Enter an integer: 36
SQUARE(36) = 1296
Area of a circle with radius 36 is: 4071.51
Enter another integer: -101
MIN(36, -101) = -101
MAX(36, -101) = 36

#define

357

4 -8 ,
, , .
, A R E A C I R C L E 6 ,
P I , ,
. ,
. 25, MIN:
cout

MIN (Inputl, Input2)

endl;

, ,
:
cout

(((Inputl) < (Input2)) ? (Inputl)

: (Input2))

endl;

, , .
, a r e a _ c i r c l e
double,
.

?
:
#define AREA_CIRCLE() (PI*()* ())

.
A r e a () 7.1 7, .
// ()
double Area(double InputRadius)

{
return Pi * InputRadius * InputRadius; // ,

}
,
? ,
, .. .
:
#define AREA_CIRCLE() (PI*r*r)

:
cout

AREA_CIRCLE (4+6);

:
cout

(1*4+6*4 + 6) ; // , 1*10*10

, ,
, :
cout

(1*4+24+6); // 42.5664 ( )

358

14.

!
:
#define AREA_CIRCLE() (PI*()* ())
cout AREA_CIRCLE (4+ 6);

:
cout

(PI*(4+6)*(4+6)); // 1*10*10,

,
.

assert
, ,
, .
,
.
a s s e r t . a s s e r t ,
a s s e r t . h, :
assert (, tr u e f a l s e ) ;

a s s e r t ( ) , :
#include <assert.h>
int main ()

{
char* sayHello = new char [25];
assert(sayHello != NULL); // ,
//
delete [] sayHello;
return 0;

}
a s s e r t () , .
s a y H e l l o NULL
V isual Studio ,
. 14.1.
, a s s e r t ( ), M icrosoft Visual Studio,
R etry ( ) ,
, a s s e r t . a s s e r t ()
; ,
.
.

#define

359

. 1 4 .1 . , assert

assert () ,

.
, , .

assert ,
(,
dynamic_cast)
, if. assert
, , .



.
14.2:
#define MIN(, b) ((() < ()) ? () : ())
M IN :
cout

MIN(25, 101)

endl;

d o u b le :
cout << MIN(0.1, 0.2)

endl;

, , M IN () ,
: M IN _ IN T ( ) , i n t
i n t , M IN _ D O U B LE ( ) , , d o u b le .


. ,
, ,

360

14.

, . ,
, ..,
, MIN.
, :
. ,
.
, ,
,
. ,
( in lin e ) .


i n l i n e 7.10 7, .

, ,



, # if n d e f, # d e fin e
# e n d if


a s s e r t () -
,


(tem plate) , , C++,
.
, , :
: Y te m -p le t\
:
: , templet,
, , templum

temple (),

: 1 6 7 7
1.

, ,
( ).

2. (1). , ( ),
; (2) : ( ),
( ) : .
3.

361

, ,
C++. C ++ ,
. ,
( ,
), , , ,
.


t e m p l a t e ,
(type param eter). :
template < >
/ ..

t e m p l a t e ,
. ty p e n a m e ,
o b j e c t T y p e , ,
.
template ctypename Tl, typename T2 = Tl>
bool TemplateFunction(const T1& paraml, const T2& param2);
//
template <typename Tl, typename T2 = Tl>
class Template
{
private:
Tl m_Objl;
T2 m_Obj 2;
public:
Tl GetObjlO {return m_Objl; }
// ...

,
1 2, 2 1.


:
;
;
- - ;
- ;
- , ;
- .

362

14.


, .
!
,
, :
template <typename objectType>
const objectTypeS GetMax (const objectType& valuel,
const objectType& value2)
if (valuel > value2)
return valuel;
else
return value2;

:
int Integerl = 25;
int Integer2 = 40;
int MaxValue = GetMax <int> (Integerl, Integer2);
double Doublel = 1.1;
double Double2 = 1.001;
double MaxValue = GetMax <double> (Doublel, Double2);

< i n t > , G etM ax ().


o b j e c t T y p e i n t .
GetM ax ( ),
:
const ints GetMax (const int& valuel, const int& value2)

{
//.

. .

const doubles GetMax (const doubles valuel, const doubles value2)

{
//

. . .

}

. , :
int MaxValue = GetMax(Integerl, Integer2);

, ,
. , ,
, 14.3.

14.3. GetMax,
0:
1:
2:
3:
4:

#include<iostream>
#include<string>
using namespace std;
template <typename Type>

363

5: const & GetMax (const Types valuel, const Types value2)


6: {
7:
if (valuel > value2)
8:
return valuel;
9:
else
10:
return value2;
11: }
12:

13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:

template ctypename Type>


void DisplayComparison(const Types valuel, const Types value2)
{
cout "GetMax(" valuel
", " value2 ") = ";
cout GetMax(valuel, value2) endl;
}
int main()
{

int Inti = -101, Int2 = 2011;


DisplayComparison(Inti, Int2);
double dl = 3.14, d2 = 3.1416;
DisplayComparison(dl, d2);
string Namel("Jack"), Name2("John");
DisplayComparison(Namel, Name2);
return 0;
}

GetMax(-101, 2011) = 2011


GetMax(3.14, 3.1416) = 3.1416
GetMax(Jack, John) = John

: G etM ax () ( 4 -1 1 ),
D is p la y C o m p a r is o n () ( 13-18). 23, 26 29
m a in ()
: i n t , d o u b le s t d : : s t r i n g . ,
( , - ),
, , !
: D is p la y C o m p a r is o n ()
:
23:

DisplayComparison<int>(Inti, Int2);

.
( ) ,
. , , .

364

14.


D is p l a y C o m p a r i s o n () G etM ax ( ) ,
14.3, . , ,
, :
DisplayComparison(Integer, "Some string");


9, , ,
, ,
. , , , i n t Age Human.
, .
, , () Human ( )
( ), 15. ,
l o n g l o n g , , , ,
s h o r t ? .
(tem plate class) C++. .
,
. Human
lo n g lo n g , i n t , s h o r t .

:
template <typename >
class MyFirstTemplateClass
{
public:
void SetValue (const T& newValue) { Value = newValue; }
const T& GetValueO const {return Val-ue;}
private:
T Value;

};
M y F i r s t T e m p l a t e C l a s s
, .
:
MyFirstTemplateClass <int> Holdlnteger; //
Holdlnteger.SetValue(5) ;
std::cout "The value stored is: " Holdlnteger.GetValue()
std::endl;


i n t ; .. i n t .

:
MyFirstTemplateClass <char*> Holdstring;
Holdstring.SetValue("Sample string");


std::cout

"The value stored is: "


std::endl;

365

Holdstring.GetValue()

,
, .
Human, ,
:
template <typename >
class CustomizableHuman
{
public:
void SetAge (const T& newValue) { Age = newValue; }
const T& GetAgeO const {return Age;}
private:
T Age; // T , !


:
CustomizableHuman<int> NormalLifeSpan;

//
// int

NormalLifeSpan.SetAge(80);
CustomizableHuman<long long> LongLifeSpan; //
//
LongLifeSpan.SetAge(3147483647) ;
//
CustomizableHuman<short> ShortLifeSpan;
//
ShortLifeSpan.SetAge(40);


long long

short


, .
(instantiation)
(object o f class).
, ,

.
:
template <typename >
class TemplateClass

{
m_member;

};
:
TemplateClass <int> IntTemplate;

(specialization).

366

14.



, . , ,
, , ,
(
):
template ctypename Tl, typename T2>
class HoldsPair
{
private:
Tl Value1;
T2 Value2;
public:
// , -
HoldsPair (const T1& valuel, const T2& value2)

{
Valuel = valuel;
Value2 = value2;

};
// ...

};
H o l d s P a i r 1 2.
:
// int double
HoldsPair <int, double> pairlntDouble (6, 1.99);
// int int
HoldsPair <int, int> pairlntDouble (6, 500);



H o l d s P a i r < . . . > ,
i n t :
template ctypename Tl=int, typename T2=int>
class HoldsPair
{
// ...

};

, .
H o l d s P a i r :
// int int ( )
HoldsPair pairlntDouble (6, 500);

367

HoldsPair
H o ld s P a ir .
14.4.

14.4.
0: // .
// int, float

1: template ctypename Tl=int, typename T2=double>


2 : class HoldsPair
3: {
4: private:
5:
T1 Valuel;
6:
T2 Value2;
7: public:
// , -
8:
9:
HoldsPair (const T1& valuel, const T2& value2)
10:
11:

{
Valuel = valuel;
Value2 = value2;

12:
13:
14:
15:
16:
17:
18:
19:
20:

};
//
const T1 & GetFirstValue () const
{
return Valuel;

};

21:

const T2& GetSecondValue () const

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

{
return Value2;

};
#include <iostream>
using namespace std;
int main ()

35;
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47: }

// HoldsPair
HoldsPair <> mlntFloatPair (300, 10.09);
HoldsPair <short,char*> mShortStringPair(25, \
"Learn templates, love C++");
// ,
cout "The first
cout
"Value 1:
cout
"Value 2:

...
object contains -" endl;
" mlntFloatPair.GetFirstValue () endl;
" mlntFloatPair.GetSecondValue () endl;

// , ...
cout "The second object contains -" endl;
cout
"Value 1: " mShortStringPair.GetFirstValue ()
cout
"Value 2: " mShortStringPair.GetSecondValue ()
endl;
return 0;

endl;

368

14.

The first object contains Value 1: 300


Value 2: 10.09
The second object contains Value 1: 25
Value 2: Learn templates, love C++

H o ld s P a i r ,
, . 1
, , 1
2, i n t d o u b l e . ,
G e t F i r s t V a l u e () G e tS e c o n d V a lu e ( ) , ,
. , G e t F i r s t V a l u e () G e tS e c o n d
V a lu e ()
. ,
H o l d s P a i r ,
. ,
.


, ,
.
? 9, , ,
.
,
. ,
X
, i n t . X
, d o u b le ,
, i n t . ,
: X i n t X d o u b l e
( 14.5).

14.5.
____________________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
using namespace std;
template ctypename T>
class TestStatic
{
public:
static int StaticValue;

8: };

369

//
template<typename > int TestStatic<T>::StaticValue;

12

int main ()

14
15
16
27
18
19
:
:i

{
TestStatic<int> Int_Year;
cout "Setting StaticValue for Int_Year to 2011"
Int_Year.StaticValue = 2011;
TestStatic<int> Int_2;
TestStatic<double> Double_l;
TestStatic<double> Double_2;
cout "Setting StaticValue for Double_2 to 1011"
Double_2.StaticValue = 1011;

22

23

24
25
26
27
23
29

cout
cout

endl;

endl;

"Int_2.StaticValue = " Int_2.StaticValue endl;


"Double_l.StaticValue = " Double_l.StaticValue
endl;

return 0;

Setting StaticValue for Int_Year to 2011


Setting StaticValue for Double_2 to 1011
Int_2.StaticValue = 2011
Double_l.StaticValue = 1011

17 21 S t a t i c V a l u e
i n t d o u b le . 25 26 m a in ()
I n t _ 2 D o u b le l .
, S t a t i c V a l u e 2011
, i n t ,
1011 ,
d o u b le .
,
.
.


11 14.5.

template<typename > int TestStatic<T>::StaticValue;


:

te m p ia te < > <


> ::;

370

14.

--11___________________________________
sta tic_ a sse rt

C++11 ,
. ,
. , , ,
i n t ! s t a t i c _ a s s e r t
( ):
static_assert( , " ,
") ;

i n t ,
s t a t i c _ a s s e r t () s i z e o f ( ) ,
s i z e o f ( i n t ) ,
:
static_assert(sizeof() != sizeof (int), "No int please!");

, s t a t i c _ a s s e r t
, 14.6.
14.6. ,
int___________________________________________
:
1:
2:
3:
4:
5:
6:
7:

template <typename >


class EverythingButlnt
{

public:
EverythingButlnt()
{
static_assert(sizeof(T)
}

!= sizeof(int), "No int please!");

8: };
9:
10: int main()
11: {

12:
13:
14: }

EverythingButInt<int> test; //
// int.
return 0;

, :
error: No int please!

371

, 6, . ,
s t a t i c _ a s s e r t , ++11
.


C++

(Standard Template Library STL). STL
, .
STL ,
-, ,
, , .
, ,
STL,
. STL, ,
C++
STL,
.

, ,
,


. , , ,
, # d e f in e .
,
.
, .
,
.
,
.
. , ,
STL!

372

14.


?
# i f n d e f , # d e f i n e # e n d i f
,
.

,
?
, , ,
, .
, .

?
, ,
.


?
,
. , i n t , s t r i n g X,

.


, ,
. ,
, .
,
.


1. ?
2. :
#define SPLIT() / 5

20?
3. , S P L IT 2

10 + 10 ?
4. SPLIT, ?

373

1. , .
2. , 4.
3. sw ap () .
4. : ,
?
#define QUARTER() ( / 4)

5. , ,
. 10,
,
.

III

(STL)
15.
16. STL
17. STL
18.
STL
19. STL
20. STL

15

, (STL)
,
.
.


STL.

378

15.

STL
(container) STL,
. STL :

STL ,
(container adapter), ,

.


, (sequential container)
,
. ,
.
STL.

s t d : : v e c t o r . .
,
.

s t d : : d e q u e . s t d : : v e c t o r ,
.

s t d : : l i s t . . ,
.
(.. ) .

s t d : : f o r w a r d l i s t . s t d : : l i s t ,
.

v e c t o r STL
, ..
, ([ ]), . ,
STL , ,
.

v e c t o r STL
(.. ).
;
, . 4.4,
v e c t o r 17,
STL .
l i s t STL .
, STL,
, ,

STL

379

. s t d : : l i s t
, .
STL 18,
STL .


(associative container),
, . ,
, .
STL .
s t d : : s e t .
1 (logarithm ic com plexity).
s t d : : u n o r d e r e d _ s e t .
(near constant com plexity).
C++11.
s t d : :map. -
.
s t d : : u n o r d e r e d _ m a p . -
.
C++11.
s t d : : m u l t i s e t . s e t .
; ..
.
s t d : : u n o r d e r e d _ m u l t i s e t . u n o r d e r e d _ s e t .

, .. .
s t d : : m u ltim a p . .
- .
s t d : : u n o r d e r e d _ m u l t i m a p . u n o r d e r e d _ m a p .
-
. + + 11.
STL
.

STL
, hash_set, hash_multiset, hash_map hash_multimap. unordered_*,
. hash_* unordered_*
,
(

,
. . .

380

15.

). ,
, , ,
.
,
, ,
. ,

.


, STL
. ,
.
,
(. 15.1).

15.1. STL

std::vector

( )

(
)

std::deque
(
)


vector,




,


reserve (),
,
,

std::list

)


, ,

STL

381

. 15.1

std::forward_list



,
, ,

,


,
,


,
,
()


,

unordered_set

std::set

)

std::unordered_set
^
)

std::multiset

)

std::unordered
-.ultiset

)

push_front()

,
unordered_set,
:
,

std::map

)

std::unordered_map

)

std::multimap

)

-

,

, ,

,

()
, ,
,



,
,


, ,



std: :map,
,
- , ,

382

15.

std::unordered
multimap
(
)

__________________ ------------

multimap,
- ",

. 15.1


(container adapter)

. .

s t d : : s t a c k . LIFO (L ast-In-F irst-O ut


, ), - .

s t d : : q u e u e . FIFO (First-In-First-O ut ,
), .

s t d : : p r i o r i t y q u e u e . ,
, .

24,
: .

STL
(iterator)
. ,
, .
STL ,
.
, STL .
STL, .
,
, .
STL .
(input iterator).
. .
.

STL

383

(output iterator). .
.
, ,
.
(forw ard iterator). ,
, . ,
, , ,
, . ,
.
(bidirectional iterator).
, , , .
, , .
(random access iterator).
,
,
.
, , .

STL
, ,
,
. STL
STL, , ,
.
STL.

s t d : : f i n d . .

s t d : : f i n d _ i f .
.

s t d : : r e v e r s e . .

s t d : : r e m o v e _ if .
.

s t d : : t r a n s f o r m .
.

s t d .
< a l g o r it h m > .

384

15.

,
STL. , 15.1,
STL s t d : : v e c t o r , ,
, s t d : : f i n d .
, STL.
. ,
s t d : : v e c t o r , , s t d : : f i n d ,
17, STL 23,
STL . ,
.
1 5 .1 . ___________________________________

1:
2:
3:
4:
5:
6:
7:
8:
9:

# in clu d e <iostream >


# in clu d e < vector>
# in clu d e <algorithm >
u sin g namespace std ;
in t main ()
{
/ /
v e c to r < in t> vecIn tegerA rray;

10:

11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

/ /
vecIn tegerA rray.p u sh _b ack
vecIn tegerA rray.p u sh _b ack
vecIn tegerA rray.p u sh _b ack
vecIn tegerA rray.p u sh _b ack
cou t


(50);
(2991);
(23);
(9999);

"The c o n te n ts o f th e v e c to r are: "

en d l;

/ /
v e c to r < in t> : : it e r a t o r iArrayWalker = v ec In te g er A r ra y .b e g in ();

21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:

w h ile (iArrayWalker != v ec In te g er A r ra y . end ())


{
/ /
cou t << *iArrayWalker << en d l;
/ /
++ iArrayWalker;
}
/ / (, 2991)
/ / ' f i n d ' . . .


22:
23:
24:
35:
26:

// ,
if (iElement != vecIntegerArray.end ())

23:

385

vector <int>::iterator iElement = find (vecIntegerArray.begin()


, vecIntegerArray.end (), 2991);

38:
29:
40:
41:

// ... :
int Position = distance (vecIntegerArray.begin (), iElement);
cout "Value " *iElement;
cout " found in the vector at position: " Position
endl;

42:
43:
44:
45: }

}
return 0;

The contents of the vector*are:


50
2991
23
9999
Value 2991 found in the vector at position: 1

15.1 , , f i n d , ,
v e c t o r . iA r r a y W a lk e r 20
, .. - b e g i n ()
v e c t o r . 2 2 -2 9
, .
STL.
b e g i n ( ) , , e n d ( ),
. w h i l e
22 e n d ( ) , .
32 f i n d
v e c t o r . ,
, 36.
, (
). d i s t a n c e () ( )
.
15.1 ' v e c t o r ' ' d e q u e ',
.
.

* 3 . 3626

386

15.

++11____________________________________________
auto

15.1 . :
20:

vector <int>::iterator iArrayWalker = vecIntegerArray.begin ();

. ,
C++11, :
20:

auto iArrayWalker = vecIntegerArray.begin (); //


//

, , a u t o ,
(
).

STL
STL ,
. s t d : : b a s i c _ s t r i n g <>
.

s t d : : s t r i n g . s t d : : b a s i c _ s t r i n g c h a r ,
.

s t d : : w s t r i n g . s t d : : b a s i c _ s t r i n g w c h a r _ t,
.

16,
STL , , .

STL,
, . b a s i c _ s t r i n g
<>, . ,
STL,
STL .

17-25.

387


, ,
. STL ?
s t d : : v e c t o r s t d : : d e q u e .
.

.
?
, s t d : :map s t d : : s e t ,
.

- .
, . ?
s t d : : m u ltim a p . m u ltim a p
- ,
.

.
.
s td : :map std : :hash_map?
,
.
, + + 1 1,
s td : : u n o r d e r e d _ m a p .


, ,
. ,
, .
,
.


1. ,
, ?
2. . ?
3. s t d : : s e t ,
,
. ?
4. STL ,
?
5. h a s h _ s e t
C++?

16


STL
(STL)
,
. s t r i n g
, ,
( ),
. ,
,
.
.

s t r i n g STL.

STL ,
, , .


STL.

390

16. STL


C++ . 4,
, :
char staticName [20];

( )
( , ) 20 . ,
,
. .
C++
. :
char* dynamicName = new char [ArrayLength];

,
A rrayLength,
, , .
,
,
.
, .
, ,
,
, .
,
, .

.
.
s t d : : s t r i n g STL , s t d : :w s tr in g
, .
.

.

.
, ,
, .
.
,
.

STL

391

std::string std: :wstring


std::basic_string<T> ,
char wchar_t, .
, .

s t d : : s t r i n g
, STL.

STL
.
.
.
.
.
,
.
STL
< s trin g > .

STL
s t r i n g ,
. ,
s t d : : s t r i n g
:
const char* constCStyleString = "Hello String!";
std::string strFromConst (constCStyleString);

std::string strFromConst = constCStyleString;

:
std::string str2 ("Hello String!");

, s t r i n g

s t r i n g .
s t r i n g
:
std::string str2Copy (str2);

s t r i n g
:
// 5
std::string strPartialCopy (constCStyleString, 5);

392

16. STL


:
// 10 ''
std::string strRepeatChars (10, '');

16.1
s t d : : s t r i n g .
1 6 .1 , STL _________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <string>
#include <iostream>
int main
{
using
const
cout

()
namespace std;
char* constCStyleString = "Hello String!";
"Constant string is: " << constCStyleString

endl;

std::string strFromConst (constCStyleString); //


cout "strFromConst is: " strFromConst endl;

11:

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25: }

std::string str2 ("Hello String!");


std::string str2Copy (str2);
cout "str2Copy is: " str2Copy

<< endl;

// 5
std::string strPartialCopy (constCStyleString, 5);
cout "strPartialCopy is: " strPartialCopy endl;
// 10 'a'
std::string strRepeatChars (10, 'a');
cout "strRepeatChars is: " strRepeatChars << endl;
return 0;

Constant string is: Hello String!


strFromConst is: Hello String!
str2Copy is: Hello String!
strPartialCopy is: Hello
strRepeatChars is: aaaaaaaaaa

s t r i n g
,
. c o n s t C S t y l e S t r i n g ,
6. 9 ,
s t d : : s t r i n g . 12 s t r 2

STL

393

s t d : : s t r i n g , 13
s t d : : s t r i n g ,
s t d : : s t r i n g s tr 2 C o p y . 17
, 21 s t d : : s t r i n g
.
, s t d : : s t r i n g
, .


, 9 16.1 :

const char* constCStyleString = "Hello World!";


// , ...
char * pszCopy = new char [strlen (constCStyleString) + 1];
strcpy (pszCopy, constCStyleString); //
// pszCopy
delete [] pszCopy;
, .
,
. STL !

s t d : : s trin g
STL
,
[ ].
- c _ s t r () ( 16.2).
1 8 .2 . STL: ([ ])

0:
1:
2:
3:
4:
5:

#include <string>
#include <iostream>
int main ()
{
using namespace std;

6:

7:
8:

//
string strSTLString ("Hello String");

9:
10:
11:
12:
13:
14:
15:
16:
17:

//
//
cout"Displaying the elements in the string using array-syntax:"
endl;
for ( size_t nCharCounter = 0
;nCharCounter < strSTLString.length ()
;++ nCharCounter )
{
cout "Character [" nCharCounter "] is: ";
cout strSTLString [nCharCounter] endl;

394
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39: }

16. STL
}
cout

endl;

//
cout "Displaying the contents of the string using iterators: "
endl;
int charOffset = 0;
string::const_iterator iCharacterLocator;
for ( iCharacterLocator = strSTLString.begin ()
; iCharacterLocator !- strSTLString.end ()
; ++ iCharacterLocator )
{
cout "Character [" charOffset ++ "] is: ";
cout ^iCharacterLocator endl;
}
cout endl;
//
cout "The char* representation of the string is: ";
cout strSTLString.c_str () endl;
return 0;

Displaying the elements in the string using array-syntax:


Character [0] is: H
Character [1] is: e
Character [2] is: 1
Character [3] is: 1
Character [4] is: 0
Character [5] is:
Character [6] is: S
Character [7] is: t
Character [8] is: r
Character [9] is: i
Character [10] is:: n
Character [11] is:
:g
Displaying the contents of the string using iterators:
Character [0] is: H
Character [1] is: e
Character [2] is: 1
Character [3] is: 1
Character [4] is: 0
Character [5] is:
Character [6] is: S
Character [7] is: t
Character [8] is: r
Character [9] is: i
Character [10] is:
:n
Character [11] is:
:g
The char* representation of the string is: Hello String

STL

395

.
, - s t r i n g
. 12-18
s t d : : s t r i n g [ ], .
, ,
17. , ..
. 25 -3 1
, .


+=,
- a p p e n d ():
string strSamplel ("Hello");
string strSample2 (" String!");
strSamplel += strSample2; // std::string::operator+=
// std::string::append()
strSamplel.append (strSample2); // ( char*)

16.3 .
1 6 .3 .
(+=) append ()____________________________________

0:
1:
2:
3:
4:
5:

#include <string>
#include <iostream>
int main ()
{
using namespace std;

6:

7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

string strSamplel ("Hello");


string strSample2 (" String!");
//
strSamplel += strSample2;
cout strSamplel endl

string strSample3 (" Fun is not needing to use pointers!");


strSamplel.append (strSample3);
cout strSamplel endl endl;
const char* constCStyleString = " You however still can!";
strSamplel.append (constCStyleString);
cout strSamplel endl;

21:
22:
23: }

endl;

return 0;

396

16. STL

Hello String!
Hello String! Fun is not needing to use pointers!
Hello String! Fun is not needing to use pointers! You however still can!

11, 15 19 STL.
+= a p p e n d ( ) ,
, (
11) .


s t r i n g STL - f i n d ()
.
s t r i n g .
// "day" strSample,
size_t charPos = strSample.find ("day", 0);
// , , string::npos
if (charPos != string::npos)
cout "First instance of \"day\" was found at position "
charPos;
else
cout "Substring not found." endl;

16.4 s t d : : s t r i n g : : f i n d ().
16.4, string: :find()
0:
#include <string>
1:
#include <iostream>
2:
3: int main ()
4: {
5:
using namespace std;
6:

7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

string strSample ("Good day String! Today is beautiful!");


cout "The samplestring is: " endl;
cout strSample endl endl;
// "day"...
size_t charPos = strSample.find ("day", 0);
// , ...
if (charPos != string::npos)
cout "First instance of \"day\" was found at position "
charPos;

STL
17:
18:
19:
20:

else
cout
cout

"Substring not found."

endl

endl;

endl;

21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53: }

cout
"Locating all instances ofsubstring \"day\""
size_t SubstringPos = strSample.find ("day", 0);
while (SubstringPos !=string::npos)
{
cout "\"day\" found at position "

endl;

SubstringPos

// ,
size_t nSearchPosition = SubstringPos + 1;
SubstringPos = strSample.find ("day", nSearchPosition);
}
cout

endl;

cout "Locating all instances of character 'a'"


const charcharToSearch = 'a';
charPos = strSample.find (charToSearch, 0);

endl;

while (charPos !=string::npos)


{
cout "'" charToSearch "' found";
cout " at position: " charPos endl;
//
,
size_t charSearchPos = charPos + 1;
charPos = strSample.find (charToSearch, charSearchPos);
}
return 0;

The sample string is:


Good day String! Today is beautiful!
First instance of "day" was found at position 5
Locating all instances of substring "day"
"day" found at position 5
"day" found at position 19
Locating all
'a' found at
'a' found at
'a' found at

instances of character 'a'


position: 6
position: 20
position: 28

endl;

397

398

16. STL

12-18 f i n d ()
. f i n d ()
s t d : : s t r i n g : :n p o s ( -1) ,
. f i n d () n p o s, ,
.
f i n d () w h i l e
STL.
f i n d ( ) , :
, , .
STL , find(),
find_first_of (), find_first_not_of (), find_last_of ()
find_last_not_of (),
.

STL
s t r i n g STL - e r a s e ( ),
:

, .
string strSample ("Hello String! Wake up to a beautiful day!");
strSample.erase (13, 28); // Hello String!

, .
strSample.erase (iCharS); //

, .
//
strSample.erase (strSample.begin(), strSample.end());

16.5
s t r i n g : : e r a s e ( ) .
16.5. string:: erase ()
, , ____________________________

0:
#include <string>
1:
#include <algorithm>
2:
#include <iostream>
3:
4: int main ()
5: {
6:
using namespace std;
7:
8:
string strSample ("Hello String! Wake up to a beautiful day!");
9:
cout "The originalsample string is: " endl;
10:
cout strSample endl
endl;
11:

STL
12:
13:
14:
15:
16:
17:
18:
19:

399

// ,
cout "Truncating the second sentence: " endl;
strSample.erase (13, 28);
cout strSample endl endl;
// 'S', STL
string::iterator iCharS = find ( strSample.begin ()
, strSample.end (), 'S');

20:

21:
22:
23:
24:
25:
26:
27:
28:

// ,
cout "Erasing character 'S' from the sample string:"
if (iCharS != strSample.end ())
strSample.erase (iCharS);
cout

29:
30:
31:
32:
33:
34:
35:
36:
37: }

strSample

endl

endl;

endl;

// ,
// erase ()
cout "Erasing a range between begin() and end(): "
strSample.erase (strSample.begin (), strSample.end ());

endl;

// erase()
if (strSample.length () == 0)
cout "The string is empty" endl;
return 0;

The original sample string is:


Hello String! Wake up to a beautiful day!
Truncating the second sentence:
Hello String!
Erasing character 'S' from the sample string:
Hello tring!
Erasing a range between begin() and end():
The string is empty

e r a s e ().
, , 14.
, ,
24. ,
, ( 30).
- b e g i n () e n d () s t r i n g ,
, e r a s e ()
. : s t r i n g
c l e a r ( ) ,
s t r i n g .

400

16. STL

++11____________________________________________

auto
C++11 , ,
16.5:
18:
19:

string::iterator iCharS = find ( strSample.begin ()


, strSample.end (), 'S');

, a u t o ,
3, , :
auto iCharS = find ( strSample.begin ()
, strSample.end (), 'S');

iC h a r S ,
s t d : : f i n d .


. ,
, 1.

. s t d : : r e v e r s e ()
STL :
string strSample ("Hello String! We will reverse you!");
reverse (strSample.begin (), strSample.end ());

16.6 s t d : : r e v e r s e ()
s td : : s trin g .
1 6 .6 . std::reverse ()

0
1
2

#include <string>
#include <iostream>
#include <algorithm>

3
4
5

int main ()

{
using namespace std;

7
8

9
10

string strSample ("Hello String! We will reverse you!");


cout "The original sample string is: " endl;
cout strSample endl endl;

11
12

reverse (strSample.begin (), strSample.end ());

13
14
15

cout
cout

"After applying the std::reverse algorithm: "


strSample endl;

. . .

endl;

STL

401

16 :

17:

return 0;

-8: }

The original sample string is:


Hello String! We will reverse you!
After applying the std::reverse algorithm:
!uoy esrever lliw eW !gnirtS olleH

s t d : : r e v e r s e (), 12,
, .
, .
, . :
e n d ().


s t d : : t r a n s f o r m ( ),
.
s t r i n g . 16.7
.
1 6 -7 -
std::transform ()_________

#include <string>
2

#include <iostream>
#include <algorithm>

3
4
5

int main ()

{
using namespace std;

7
8

cout "Please enter a string for case-convertion:" << endl;


cout << "> ";

:
11
12

13
14
15

16
17
19:

string strlnput;
getline (cin, strlnput);
cout endl;
transform(strlnput.begin(),strlnput.end(),strlnput.begin(),\
toupper);
cout "The string converted to upper case is: " endl;
cout strlnput endl endl;
transform(strlnput.begin(),strlnput.end(),strlnput.begin(),\
tolower);

402
20:
21:
22:
23:
24: }

16. STL
cout "The string converted to lower case is: "
cout << strlnput endl endl;

endl;

return 0;

Please enter a string for case-convertion:


> ConverT this StrINg!
The string converted to upper case is:
CONVERT THIS STRING!
The string converted to lower case is:
convert this string!

15 19 ,
s t d : : t r a n s f o r m () .

STL
, s t d : : s t r i n g
STL s t d : : b a s i c _ s t r i n g < T > .
b a s i c _ s t r i n g :
templatecclass _Elem,
class _Traits,
class _Ax>
class basic_string

: _ 1 .
, b a s i c _ s t r i n g . , s t d : : s t r i n g
b a s i c _ s t r i n g _ E le m = c h a r, w s t r i n g
_ E le m = w c h a r_ t. , s t r i n g
STL :
typedef basic_string<char, char_traits<char>, allocator<char> >
string;

w s t r i n g STL :
typedef basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >
string;

, , ,
b a s i c _ s t r i n g ,
w s trin g .

403

std::wstring ,
, .

s t r i n g STL.
,
.
,
.


, s t d : : r e v e r se ().
, ?
s t d : : r e v e r s e () ,
< a lg o r ith m > .

s t d : : tran sform ()
to lo w er () ?
s t d : : t r a n s f o r m () t o l o w e r ()
s t r i n g , .

std : :w str in g s t d : : s t r in g
-?
s t d : : b a s i c _ s t r i n g .


STL?
.


, ,
. ,
, .
,
.


1. STL s t d : : s t r i n g ?
2. ,
?
3. STL ?

404

16. STL

1. .
: ATOYOTA ,
2. ,
.
3. .
4. , *
I , L ove , STL S tring .
.

17

STL
,
, ,
.
, ,
(STL)
s t d : : vec to r.
.

s t d : :vector.

deque STL.

406

17. STL

s t d : :vecto r
v e c t o r
.

, ..
. .

, v e c t o r
.

(vector) , ,
. 17.1.

[0]

11]

[2]

...................................... -J

-17-1.

s t d : : v e c t o r , :

#include <vector>


s t d : : v e c t o r C++.
, , ,
C++, .


v e c t o r ,
14, . v e c t o r
, .
v e c t o r :
s t d : : v e c t o r < i n t > vecDynamicIntegerArray; / /
s t d : :v e c t o r < f l o a t > vecDynamicFloatArray; / / f l o a t s
s t d : :vector<Tuna> vecDynamicTunaArray;
/ / Tuna
, ,
s t d : :v e c t o r < i n t > : : c o n s t _ i t e r a t o r iE lem en tln S et;

, i t e r a t o r c o n s t _ i t e r a t o r .
s t d : : v e c t o r ,
, ,
( ) .

407

17.1.
1 7 .1 . std: : vector:
,

3: #include <vector>
2: int main ()
3: {
4:
std::vector <int> veclntegers;
6:
7:

// 10 (
/ / )
std::vector <int> vecWithTenElements
(10);

8:

9:
13:
12:
13:
14:
15:
16:
17:
18:
19:

// 10 ,
// 90
std::vector <int> vecWithTenlnitializedElements (10, 90);
//
//
std::vector <int> vecArrayCopy(vecWithTenlnitializedElements);
//
// 5
std::vector <int> vecSomeElementsCopied ( \
vecWithTenElements.cbegin ()
, vecWithTenElements.cbegin () + 5 );
return 0;

10: }

v e c t o r
i n t ; , .
v e c l n t e g e r s ,
, .. ,
.
10 13, , ,
, , 10 . ,
, .
16 17
, , v e c t o r ,
.
STL. . v e c S o m e E le m e n ts C o p ie d
v e c W ith T e n E le m e n ts .

.
, vecArrayCopy
, .
, , float, .

408

17. STL

cbegin ()

cend()?
, ,
C++11, begin () end (
cbegin () cend () .
cbegin () cend () ( ) ,
, .


push_back ()

.
p u s h _ b a c k ():
vector <int> veclntegers; // int
// :
veclntegers.push_back (50);
veclntegers.push_back (1);

17.2 p u s h _ b a c k () :
s t d : : v e c t o r .
1 7 .2 . push back ()

0: #include <iostream>
1: #include <vector>
2 : using namespace std;

3:
4: int main ()
5: {
6: vector <int> veclntegers;
7:
8: // :
9: veclntegers.push_back (50);
1 0 : veclntegers.push_back (1);
1 1 : veclntegers.push_back (987);
12 : veclntegers.push_back (1001);
13:
14: cout "The vector contains ";
15: cout veclntegers.size (.) " Elements"
16:
17: return 0;
18: }

The vector contains 4 Elements

endl;

409

p u s h _ b a c k ( ) , 9 -1 2 , v e c t o r ,
.
s i z e ( ) , , .

++11

++11 s td : . : i n i t i a l i z e _ l i s t < > ,
,
:
vector<int> veclntegers = {50, 1, 987, 1001};
// :
vector<int> vecMorelntegers {50, 1, 987, 1001};

17.2.
, M icrosoft Visual C++ 2010
s t d : : v e c t o r .


in s e rt ()
p u s h b a c k () .
? STL,
s t d : : v e c t o r , i n s e r t () .
:
//
veclntegers.insert (veclntegers.begin (), 25);

,
:
// 2 45
veclntegers.insert (veclntegers.end (), 2, 45);

:
// , 30
vector <int> vecAnother (2, 30);
// [1]
veclntegers.insert (veclntegers.begin () + 1 ,
vecAnother.begin (), vecAnother.end ());

i n s e r t () , ,
, b e g i n () e n d ().

410

17. STL

STL,
std::find (),
( ).

v e c t o r : : i n s e r t () 17.3.
1 7 .3 . vector :: insert ()
_____________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:

#include <vector>
#include <iostream>
using namespace std;
void DisplayVector(const vector<int>& veclnput)
{
for (auto iElement = veclnput.cbegin() // auto cbegin(): C++11
; iElement != veclnput.cend() // cend() C++11
; ++ iElement )
cout *iElement '
cout

endl;

int main ()
{
// 4 ,
// 90
17:
vector <int> veclntegers (4, 90);
18:
19:
cout "The initial contents of the vector: ";
20:
DisplayVector(veclntegers);
21:
22:
// 25
23:
veclntegers.insert (veclntegers.begin (), 25);
24:
25:
// 2 45
26:
veclntegers.insert (veclntegers.end (), 2, 45);
27:
28:
cout "Vector after inserting elements at beginning and end: ";
2 9:
DisplayVector(veclntegers);
30:
31:
// , 30
32:
vector <int> vecAnother (2, 30);
33:
34:
// [1]
35:
veclntegers.insert (veclntegers.begin () + 1,
36:
vecAnother.begin (), vecAnother.end ());
37:
38:
cout "Vector after inserting contents from another vector: ";
39:
cout "in the middle:"
endl;
40:
DisplayVector(veclntegers);
41:
42:
return 0;
43: }

411

The initial contents of the vector: 90 90 90 90


Vector after inserting elements at beginning and end: 25 90 90 90 90 45 45
Vector after inserting contents from another vector: in the middle:
25 30 30 90 90 90 90 45 45

i n s e r t ( ),
. 17 ,
90. ,
- v e c t o r : : i n s e r t (). 23
. 26 ,
45. 35
( 1).
v e c t o r : : i n s e r t () ,
p u s h _ b a c k ().
, i n s e r t ()
( , ),

( ). ,
, ,

. i n t ,
. .
,
s t d : : l i s t , 18,
" STL.

C++?
DisplayVector () 17.3
C++ auto 6.
,
++11, auto ,
vector<int>:: const_iterator.
, DisplayVector ()
:

// C++
void DisplayVector(const vector<int>& veclnput)

A
for (vector<int>::const_iterator iElement = veclnput.begin

0
; iElement != veclnput.end ()
; ++ iElement )
cout *iElement '
cout

endl;

412

17. STL



,
([ ]), - a t () .
17.1 ,
10 :
std::vector <int> vecArrayWithTenElements (10);

, ,
:
vecArrayWithTenElements[3] = 2011; // 4-

17.4
( [ ]).

17.4.
0
1

#include <iostream>
#include <vector>

int main ()

4
5
6
7

{
using namespace std;
vector <int> vecIntegerArray;

//
vecIntegerArray.push_back
vecIntegerArray.push_back
vecIntegerArray.push_back
vecIntegerArray.push_back

10
11
12

13
14
15
16
17
18
19
20

for (size_t Index = 0; Index < vecIntegerArray.size (); ++Index)

{
cout
cout

"Element[" Index "] = " ;


vecIntegerArray[Index] endl;

}
// 3- c 987 2011
vecIntegerArray[2] = 2011;
cout "After replacement: " endl;
cout "Element[2] = " vecIntegerArray[2]

21

22
23
24
25
26

:
(50);
(1);
(987);
(1001);

return 0;

Element[0] = 50
Element[1] = 1
Element[2] = 987

endl;

413

Element[3] = 1001
After replacement:
Element[2] = 2011

17,21 23 ,
,
; ]). ,
. , 15 f o r .
: v e c t o r : : s i z e ( ) ,
.

[ ]
, ; ..
.
([ ]) ,
( , ,
).
- at ():

// 2
cout vecIntegerArray.at (2);
// vector::at() 17 17.4:
cout vecIntegerArray.at(Index);
at ()
( ).
([ ]) , ,
, .



,
( 17.5).
1 7 .5 .
()____________________________________________________________

0: #include <iostream>
1: #include <vector>
2:

3: int main ()
4: {
5:
using namespace std;
6:
vector <int> veclntegers;
7:
8:
// :
9
veclntegers.push_back (50);

414

11
12

13
14
15
16
17
18
19
20

17. STL
veclntegers.push_back (1);
veclntegers.push_back (987);
veclntegers.push_back (1001);
// :
vector <int>::iterator iElementLocator = veclntegers.begin ();
// ,
// ++11 auto ( )
// auto iElementLocator = veclntegers.begin ();
while (iElementLocator != veclntegers.end ())

21

22
23
24
25
26
27
28
29
30
31
32

size_t Index = distance (veclntegers.begin (),


iElementLocator);
cout
cout

"Element at position ";


Index " is: " << ^iElementLocator

endl;

//
++ iElementLocator;

}
return 0;

Element
Element
Element
Element

at
at
at
at

position
position
position
position

0
1
2
3

is:
is:
is:
is:

50
1
987
1001

,
, 25,

(*), 29, ++
. 21
s t d : : d i s t a n c e ()
(.. ) b e g i n (
.


, p u s h _ b a c k () ,
p o p _ b a c k () .
p o p _ b a c k () , ..
. 17.6
p o p b a c k () .

415

1 7 .6 . pop back ()
0

1
2
3
4
5
6
7

#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void DisplayVector(const vector<T>& veclnput)

{
for (auto iElement = veclnput.cbegin() // auto cbegin(): C++11
; iElement != Input.cend()
// cend() C++11
; ++ iElement )
cout *iElement ' ';

10
11
12

cout

14
15

int main ()

16

17
18
19

endl;

vector <int> veclntegers;


// :
veclntegers.push_back (50);
veclntegers.push_back (1);
veclntegers.push_back (987);
veclntegers.push_back (1001);

:
21
22

23
24
25

cout "Vector contains "


" elements: ";
DisplayVector(veclntegers);

26

veclntegers.size ()

27

28
29

//
veclntegers.pop_back ();

30

31
32
33
34
35
36

cout "After a call to pop_back()" endl;


cout "Vector contains " veclntegers.size ()
" elements: ";
DisplayVector(veclntegers);
return 0;

Vector contains 4 elements: 50 1 987 1001


After a call to pop_back()
Vector contains 3 elements: 50 1 987

, p o p _ b a c k ( ) , 29,
, . 32
s i z e () ,
, .

416

17. STL

DisplayVector () 4-13 17.6


17.3,
.
float ( int):

vector <float> vecFloats;


DisplayVector(vecFloats); // ,
function
,
*, , cout.


(size) . (capacity
,
,
.
, s i z e ():
cout << "Size: "

veclntegers.size ();

c a p a c i t y ():
cout << "Capacity: "

veclntegers.capacity ()

endl;


.
- r e s e r v e ( ) . ,
, ,
.
,
.
17.7 .
1 7 .7 . size () capacity ()________________

0:
1:
2:
3:
4:
5:

#include <iostream>
#include <vector>
int main ()
{
using namespace std;

6:

7:
8:

// ,
// 5
vector <int> veclntegers (5);

9:
10:
11:

cout
cout

"Vector of integers was instantiated with "


"Size: " veclntegers.size ();

endl;


12:
13:
14:
15:
16:
17:
18:
19:

cout

", Capacity: "

veclntegers.capacity ()

417

endl;

// 6-
veclntegers.push_back (666);
cout
cout
cout

"After inserting an additional element..."


"Size: " veclntegers.size ();
", Capacity: " veclntegers.capacity ()

endl;
endl;

20:

21:
22:
23:
24:
25:
26:
27:
28:
29: }

//
veclntegers.push_back (777);
cout
cout
cout

"After inserting yet another element... "


"Size: " veclntegers.size ();
", Capacity: " veclntegers.capacity ()

endl;
endl;

return 0;

Vector of integers wasinstantiated with


Size: 5, Capacity: 5
After inserting an additionalelement...
Size: 6, Capacity: 7
After inserting yet another element...
Size: 7, Capacity: 7

8 ,
(0). 11 12
, ,
. 9 .
,
. , v e c t o r
.
,
; ,
.

.
s i z e ()
. 22
. ,
, ,
,
.

14 . 3626

418

17. STL


.
STL.

deque STL
d e q u e STL,
v e c t o r , ,
. d e q u e :
//
deque <int> dqlntegers;

std::deque, :

#include<deque>

(deque) , . 17.2.

................... ^

[0]

[1]

. 1 7 .2 .

,
p u s h b a c k () p o p _ b a c k ( ).
,
( [ ]).
, ,
p u s h _ f r o n t () p o p _ f r o n t () ( 17.8).
1 7 .8 . STL,
push front () pop front ()

0
1
2

#include <deque>
#include <iostream>
#include <algorithm>

3
4
5

int main ()

{
using namespace std;

7
8

//
deque <int> dqlntegers;

10
11
12
13
14

//
dqlntegers.push_back (3);
dqlntegers.push_back (4);
dqlntegers.push_back (5);

deque STL

419

//
dqlntegers.push_front (2);
dqlntegers.push_front (1);
dqlntegers.push_front (0);
cout
cout

"The contents of the deque after inserting elements


"at the top and bottom are:" endl;

//
for ( size_t nCount = 0
; nCount < dqlntegers.size ()
; ++ nCount )

{
cout
cout

"Element [" nCount "] = ";


dqlntegers [nCount] endl;

} '
cout

endl;

//
dqlntegers.pop_front ();

23
29

//
dqlntegers.pop_back ();

4z

cout
cout

"The contents of the deque after erasing an element ";


"from the top and bottom are:" endl;

43

46
47
48
49

// :
//
// auto
// deque <int>::iterator iElementLocator;
for (auto iElementLocator = dqlntegers.begin ()
; iElementLocator != dqlntegers.end ()
; ++ iElementLocator )

53

{
size_t Offset = distance (dqlntegers.begin (),
iElementLocator);
cout "Element [" Offset "] = " *iElementLocator
endl;

52:
53:
54:
55:
56:

}
return 0;

The contents of the deque after inserting elements at the top and bottom are:
Element [0] = 0
Element [1] = 1
Element [2] = 2
Element [3] = 3

420

17. STL

Element [4] = 4
Element [5] = 5
The contents of
Element [0] = 1
Element [1] = 2
Element [2] = 3
Element [3] = 4

10 .
,
. 11-14 - p u s h _ b a c k ( ) d e q u e , 16-19 - p u s h _ f r o n t ( ).
. p o p _ f r o n t () 37.
*
, , . ,
4 7 -5 3 ,
s t d : : d i s t a n c e ( ) , ,
17.5.

, popjoack ()

,
,

, pop_f ront ()

, pushjoack ()

,
,
push_back {) push__front {)


, .
, ,
,
. *
STL, ,
, .

421


?
, .


?
- push_back () .
?
- s i z e () , . ,
STL.

,
?
.
.

- r e se r v e () ?
,
.

.

,
?

, .
, .


, ,
. ,
, .
,
.


1.
?
2. s i z e () 10, c a p a c i t y ()
20.
?
3. p o p b a c k () ?

422

17. STL

4. v e c t o r < i n t > ,
v ecto r< C M am m al> ?
5. ? , ?
6. ?

1. ,
.
, .
2. 1 ,
, .
3. eBay. ,
, ,
.

18

STL
(STL)
(doubly linked list)
s t d : : l i s t .
.
++11 (singly
inked list) s t d : : f o r w a r d _ l i s t ,
.
.

l i s t f o r w a r d _ l i s t .

STL,
.

424

18. ST.

std: : l i s t
(linked list) (node), ,
,
, .. , . 18.1.

N + 1

- 1 8 -1 .

l i s t STL
, .

std::list, :

#include <list>


l i s t STL,
< l i s t > . l i s t , s t d ,
, ,
-.

std : : l i s t
s t d : : l i s t _
. ,
:
std::list<int> listlntegers; //
std::list<float> listFloats; // float
std::list<Tuna> listTunas;
// Tuna

, ,
:
std::list<int>::const_iterator iElementlnSet;


, i t e r a t o r c o n s t _ i t e r a t o r .
s t d : : l i s t ,
, .
18.1.

425

1 8 .1 . s t d : : l i s t :
_________________

3: tinclude <list>
1: #include <vector>
2:

3: int main ()

4: {
5:

using namespace std;

6:
7:
:

//
list <int> listlntegers;

:
13:
11:

// 10
list<int> listWithlOlntegers(10) ;

12:

13:
14:
15:
16:
17:
18:
19:
20:

// 4 ,
// 99
list<int> listWith4IntegerEach99 (10, 99);
//
list<int> listCopyAnother(listWith4IntegerEach99);
// 10 2011
vector<int> veclntegers(10, 2011);

21:

22:
23:
24:
25:
26:
27: }

//
//
list<int> listContainsCopyOfAnother(veclntegers.cbegin(),
veclntegers.cend());
return 0;

,
. 8
, 11 , 10 . 14
l i s t W i t h 4 I n t e g e r s E a c h 9 9 , 4 ,
99. 17 ,
. 2 0 -2 4 ! ,
10 , 2011, , 23,
, ,
, v e c t o r : : c b e g i n () v e c t o r : : c e n d ( ) (
C++11). 18.1 ,


( 23 24).

18. ST.

426

c b e g in ()
ce n d ()?

, ,
C++11, begin () end ()
cbegin () cend () . cbegin () cend ()
C++11, ,
.

18.1 17.1,
.
STL,
.


, ( , :
) p u s h _ f r o n t ( ) ,
p u s h _ b a c k ( ).
, :
listlntegers.push_back (-1);
listlntegers.push_front (2001);

18.2
.
1 8 .2 .
push_f ront () push_back ()_______________________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18
19
20
21

#include <list>
#include <iostream>
using namespace std;
template ctypename T>
void DisplayContents (const T& Input)
{

for (auto iElement = Input.cbegin() // auto cbegin: C++11


; iElement != Input.cend()
; ++ iElement )
cout *iElement ' ';
cout

endl;

}
int main ()
{
std::list <int> listlntegers;
listlntegers.push_front (10);
listlntegers.push_front (2011);
listlntegers.push_back (-1);


:2

427

listIntegers.push_back (9999);

;
14

DisplayContents(listlntegers);

16:

return 0;

2011 10 -1 9999

19-22 p u s h _ f r o n t () p u s h _ b a c k ( ).
, p u s h _ f r o n t ( ),
, p u s h _ b a c k () .
( D i s p l a y C o n t e n t s ()) ,
, .


auto?
DisplayContents () 18.2
++11 auto 7. ,
const_iterator cbeginO
cend(), C++11.

, ++11,
auto .
, DisplayContents ()
, .

template ctypename >


void DisplayContents (const T& Input)

{
for (T::const_iterator iElement = Input.begin ()
; iElement != Input.end ()
; ++ iElement )
cout *iElement '
cout endl;

DisplayContents () 4-13 18.2


DisplayVector () 17.6 (
).
,
.
DisplayContents () 18.2
, .

428

18. ST-


s t d : : l i s t )
. - i n s e r t ().
i n s e r t () l i s t .

1
iterator insert(iterator pos, const T& x)

i n s e r t ()
. , ,
.

2
void insert(iterator pos, size_type n, const T& x)

,
.

3
template <class InputIterator>
void insert(iterator pos, Inputlterator f, Inputlterator 1)

,
, .
: , I n p u t l t e r a t o r , ,
, , .
18.3
l i s t : : i n s e r t ().
1 8 .3 . ____________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <list>
#include <iostream>
using namespace std;
template <typename T>
void DisplayContents (const T& Input)
{

for (auto iElement = Input.cbegin() // auto cbegin: C++11


; iElement != Input.cend()
; ++ iElement )
cout *iElement '

11:

12:
13: }
14:
15: int
16: {
17:
18
19
20

cout

endl;

main ()
list <int> listlntegersl;
// ...
listlntegersl.insert (listlntegersl.begin (), 2);

429

listlntegersl.insert (listlntegersl.begin (), 1);


// ...
listlntegersl.insert (listlntegersl.end (), 3);
cout "The contents of list 1 after inserting elements:"
endl;
DisplayContents (listlntegersl);
*
29

list <int> listlntegers2;

// 4 0...
Iistlntegers2.insert (listlntegers2.begin (), 4, 0) ;

22
23
24

cout "The contents of list 2 after inserting


cout listlntegers2.size () "' elements of a value:"
endl;
DisplayContents (listlntegers2) ;

25
26
2*7

28

list <int> listlntegers3;

29

40
41
42
43
44
45
46
47
48

// ...
Iistlntegers3.insert (listlntegers3.begin (),
listlntegersl.begin (), listlntegersl.end ());
cout "The contents of list 3 after inserting the contents of";
cout "list 1 at the beginning:" endl;
DisplayContents (listlntegers3);
// ...
Iistlntegers3.insert (listlntegers3.end (),
listlntegers2.begin (), listlntegers2.end ());

49

50
51
52
53
54

cout "The contents of list 3 after inserting ";


cout "the contents of list 2 at the beginning:"
DisplayContents (listlntegers3);

endl;

55

56
57

return 0;

The
12
The
0 0
The
12
The
1 2

contents of
3
contents of
0 0
contents of
3
contents of
3 0 0 0 0

list 1

after inserting elements:

list 2

after inserting '4' elements of a value:

list 3

after inserting the contents of list 1 at the beginning:

list 3

after inserting the contents of list 2 at the beginning:

18. ST.

430

- b e g i n () e n d ( ) , ;
. STL, *
s t d : : l i s t . i n s e r t () , , >
. 24 ,
e n d ( ) , .
3 ,
32
0. 41 42 l i s t : : i n s e r t () *
. *
, ,
b e g i n () e n d ( ) , 18.1,
.


e r a s e () l i s t :
, ,
. l i s t : : e r a s e () 18.4.
.

18.4. ______________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:

#include <list>
#include <iostream>
using namespace std;
template <typename T>
void DisplayContents(const T& Input)
{

for(auto iElement = Input.cbegin() // auto cbegin: C++11


; iElement != Input.cend()
; ++ iElement )
cout *iElement '
cout

endl;

}
int main()
{
std::list <int> listlntegers;
// ...
listlntegers.push_back(4);
listlntegers.push_front(3);
listlntegers.push_back(5);
// , insert()
auto iValue2 = listlntegers.insert(listlntegers.begin(), 2);
cout

"Initial contents of the list:"

endl;


18:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43: }

431

DisplayContents(listlntegers);
listlntegers.erase(listlntegers.begin(), iValue2);
cout "Contents after erasing a range of elements:"
DisplayContents(listlntegers);
cout "After erasing element " *iValue2
listlntegers.erase(iValue2);
DisplayContents(listlntegers);

"':"

endl;

endl;

listlntegers.erase(listlntegers.begin(), listlntegers.end());
cout "Number of elements after erasing range: ";
cout listlntegers.size()
endl;
return 0;

Initial contents of the list:


2 3 4 5
Contents after erasing a range of elements:
2 3 4 5
After erasing element '2':
3 4 5
Number of elements after erasing range: 0

2 0 -2 5 m a in ()
. i n s e r t ( ) ,
.
2. 25 iV a l u e 2
e r a s e () 35 . 30
38 e r a s e () .
b e g i n () , 2 (
). b e g i n () e n d ( ) ,
.
40 18.4 ,
size () std::list,
. STL.



:
, .

432

18. STL

l i s t s o r t () r e v e r s e ().
STL ,
l i s t . , ,
,
.


l i s t : : r e v e r s e ( )
- r e v e r s e () l i s t
:
listlntegers.reverse(); //

r e v e r s e () 18.5.

18.5.
0
1
2

#include <list>
#include <iostream>
using namespace std;

3
4
5
6
7
8
9
10

template <typename T>


void DisplayContents(const T& Input)

{
for(auto
;
;
cout

iElement = Input.cbegin() // auto cbegin: C++11


iElement != Input.cend()
++ iElement )
*iElement '

11

12
13
14
15
16
17
18
19
20

cout

int main()

{
std::list <int> listlntegers;
//
listlntegers.push_front(4);
listlntegers.push_front(3);
listlntegers.push_front(2);
listlntegers.push_front(1);
listlntegers.push_front(0);
listlntegers.push_back(5);

21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

endl;

cout "Initial contents of the list:"


DisplayContents(listlntegers);

endl;

listlntegers.reverse();
cout "Contents of the list after using reverse():"
DisplayContents(listlntegers);
return 0;

endl;

433

Initial contents of the list:


0 1 2 3 4 5
Contents of the list after using reverse():
5 4 3 2 1 0

30, r e v e r s e ()
. , ,
, , .


- s o r t () l i s t :
listlntegers.sort(); //


, :
bool SortPredicate_Descending (const int& lsh, const int& rsh)

{
// list::sort: true
//
return (lsh > rsh);

}
// :
listlntegers.sort (SortPredicate_Descending);

18.6.
18.6.
list :: sort ()_____________ __________________

0:
1:
2:
3:
4:
5:
6:

#include <list>
#include <iostream>
using namespace std;

8:

bool SortPredicate_Descending (const int& lsh, const int& rsh)


{
// list::sort: true
//
7:
return (lsh > rsh);
9:
10: template <typename T>
11: void DisplayContents (const T& Input)
12:

13:
14:
15:
16:
17:

for (auto iElement = Input.cbegin() // auto cbegin: C++11


; iElement != Input.cend()
; ++ iElement )
cout *iElement i .

434
18:
19: }

18. STL
cout

endl;

20:

21: int main ()


22: {
23:
list <int> listlntegers;
24:
25:
//
26:
listlntegers.push_front (444);
27:
listlntegers.push_front (2011);
28:
listlntegers.push_front (-1);
29:
listlntegers.push_front (0);
30:
listlntegers.push_back (-5);
31:
32:
cout "Initial contents of the list are - " endl;
33:
DisplayContents (listlntegers);
34:
35:
listlntegers.sort ();
36:
37:
cout "Order of elements after sort():" endl;
38:
DisplayContents (listlntegers);
39:
40:
listlntegers.sort (SortPredicate_Descending);
41:
cout "Order of elements after sort() with a predicate:
endl;
42:
DisplayContents (listlntegers);
43:
44:
return 0;
45: }

Initial contents of the list are 0 -1 2011 444 -5


Order of elements after sort():
-5 -1 0 444 2011
Order of elements after sort() with a predicate:
2011 444 0 -1 -5


.
. 35 s o r t ()
, :
< (
).
, .
S o r t P r e d i c a t e D e s c e n d in g ( ), 4 -8 ,
, s o r t () ,
. . ,
, (

435

). s o r t () ( 40).
t r u e , .
, s o r t () ( l s h )
( r s h ) ,
. , ,
.

,

, , ,
i n t ? , , ,
, .. ,
?
.
, , <.
(binary predicate) ,
, ,
.
, STL,
; , , .
18.7 .
, .
1 8 .7 . : _________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

#include <list>
#include <string>
#include <iostream>
using namespace std;
template <typename T>
void DisplayContents (const T& Input)
{
for(auto iElement = Input.cbegin() // auto, cbegin cend: C++11
; iElement != Input.cend()
; ++ iElement )
cout *iElement endl;

12:

13:
cout endl;
14: }
15:
16: struct Contactltem
17: {
18:
string strContactsName;
19:
string strPhoneNumber;
20:
string strDisplayRepresentation;
21:

22:

//

18. STL

436
23:
24:
25:
26:
27:

Contactltem (const strings strName, const string & strNumber)


{
strContactsName = strName; '
strPhoneNumber = strNumber;
strDisplayRepresentation = (strContactsName + ": "\
+ strPhoneNumber);
}

28:
29:
30:
31:
32:
33:

// list::remove()
bool operator == (const ContactltemS itemToCompare) const
{
return (itemToCompare.strContactsName == \
this->strContactsName);
}

34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:

// list::sort()
bool operator < (const Contactltems itemToCompare) const
{
return (this->strContactsName < \
itemToCompare.strContactsName);
}
// DisplayContents cout
operator const char*() const
{
return strDisplayRepresentation.c_str();

}
};
bool SortOnPhoneNumber (const ContactltemS iteml,
const ContactltemS item2)
{
return (iteml.strPhoneNumber < item2.strPhoneNumber);
}
int main ()
{
list <ContactItem> Contacts;
Contacts.push_back(Contactltem("Jack Welsch",
"+1 7889 879 879"));
Contacts.push_back(Contactltem("Bill Gates",
"+1 97 7897 8799 8"));
Contacts.push_back(Contactltem("Angela Merkel",
"+49 23456 5466"));
Contacts.push_back(Contactltem("Vladimir Putin",
"+7 6645 4564 797"));
Contacts.push_back(Contactltem("Manmohan Singh",
"+91 234 4564 789"));
Contacts.push_back(Contactltem("Barack Obama",
"+1 745 641 314"));
cout "List in initial order: "
DisplayContents(Contacts);

endl;


57:
68:
69:
70:
71:
"2:
":
^4:

Contacts.sort ();
cout "After sorting in alphabetical order via operator<:"
endl;
DisplayContents(Contacts);
Contacts.sort(SortOnPhoneNumber);
cout "After sorting in order of phone numbers via predicate:"
endl;
DisplayContents(Contacts);

75 :
76:
77:
78:
79:
80:
31: }

cout "After erasing Putin from the list: ";


Contacts.remove(Contactltem("Vladimir Putin", ""));
DisplayContents(Contacts);
return 0;

List in initial order:


Jack Welsch: +1 7889 879 879
Bill Gates: +1 97 7897 8799 8
Angela Merkel: +49 23456 5466
Vladimir Putin: +7 6645 4564 797
Manmohan Singh: +91 234 4564 789
Barack Obama: +1 745 641 314
After sorting in alphabetical order via operatorC
Angela Merkel: +49 23456 5466
Barack Obama: +1 745 641 314
Bill Gates: +1 97 7897 8799 8
Jack Welsch: +1 7889 879 879
Manmohan Singh: +91 234 4564 789
Vladimir Putin: +7 6645 4564 797
After sorting in order of phone numbers via predicate:
Barack Obama: +1 745 641 314
Jack Welsch: +1 7889 879 879
Bill Gates: +1 97 7897 8799 8
Angela Merkel: +49 23456 5466
Vladimir Putin: +7 6645 4564 797
Manmohan Singh: +91 234 4564 789
After erasing Putin from the list:
Barack Obama: +1 745 641 314
Jack Welsch: +1 7889 879 879
Bill Gates: +1 97 7897 8799 8
Angela Merkel: +49 23456 5466
Manmohan Singh: +91 234 4564 789

437

18. STL

438

57-81 m a in ( ) . 57
C o n t a c t l t e m . 5 8 -6 3

. 66 .
l i s t : : s o r t 68.
o p e r a t o r < C o n t a c t l t e m ,
3 7 -4 0 . C o n t a c t l t e m : : o p e r a t o r <
l i s t : : s o r t (
).
, l i s t : : s o r t ( ) ,
S o r tO n P h o n e N u m b e r () ( 72). , 4 9 53, , C o n t a c t l t e m
, . , l i s t : : s o r t ()
,
. , 77 l i s t : : r e m o v e ()
. . l i s t : : r e m o v e ()

C o n t a c t l t e m : : o p e r a t o r s 3 0 -3 4 .
t r u e , , l i s t : : re m o v e ()
.

STL , ,
.

++11
s t d : : forw ard_list
C + + 11 s t d : : f o r w a r d _ l i s t
s t d : : l i s t . s t d : : f o r w a r d _ l i s t
, (. 18.2).

. 18.2.

st d : : f o r w a r d _ l is t
<forw ard _list> :

#include<forward list>

439

f o r w a r d _ l i s t l i s t ,
.
p u s h _ f r o n t ( ) , p u s h _ b a c k ( ) . ,
i n s e r t ()
.
18.8 f o r w a r d _ l i s t .
1 8 .8 . ____________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include<forward_list>
#include<iostream>
using namespace std;
template <typename T>
void DisplayContents (const T& Input)
{

for (auto iElement = Input.cbegin() // auto cbegin: C++11


; iElement != Input.cend ()
; ++ iElement )
cout << *iElement '

11:

12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:

cout

endl;

}
int main()
{
forward_list<int> flistlntegers;
flistIntegers.push_front(0);
flistlntegers.push_front(2);
flistlntegers.push_front(2);
flistlntegers.push_front(4);
flistlntegers.push_front(3);
flistlntegers.push_front(1);
cout "Contents of forward_list: "
DisplayContents(flistlntegers);

endl;

flistlntegers.remove(2);
flistlntegers.sort() ;
cout "Contents after removing 2 and sorting: "
DisplayContents(flistlntegers);
return 0;
}

Contents of forward_list:
1 3 4 2 2 0
Contents after removing 2 and sorting:
0 13 4

endl;

[40

18. STL

, f o r w a r d l i s t
i s t . f o r w a r d l i s t , o p e r a to r + + , o p e r a t o r .
[ re m o v e (2)
2 ( 28). 29 s o r t () s t d : : le s s < T > .
f o r w a r d l i s t , ,
, l i s t ( , ).

s t d : : l i s t

s t d : : l i s t

; v e c to r
deque

s t d : : v e c to r ,
,
,

, ,
,

, p u s h ^ f r o n t p u sh _
b ack {}

, s o r t ()
remove () l i s t ,

o p e r a to r< o p e r a t o r - -
,
STL, l i s t ,

,
,
l i s t " : : s i z e (),
STL
, ,

l i s t : : c l e a r (),
STL

l i s t .
l i s t ,
.

441


l i s t -, s o r t () remove () ?
l i s t STL ,
. STL
l i s t , -

.

, CAnimal.
CAnimal, -
?
== <
, STL.

auto :
list<int> listlntegers(10); // 10
auto iFirstElement = listlntegers.begin();

,
C++11, a u t o :
list<int> listlntegers (10); // 10
list<int>::iterator iFirstElement = listlntegers.begin();


, ,
. ,
, .
,
.


1.
STL, ?
2. STL,
.
?
3. ?
4. ?

442

18. STL

1. ,
.
2. , ,
, , ,
,
.
3. , ,
l i s t .
4. , .

19


STL
(STL)
, .
s t d : : s e t s t d : : m u l t i s e t


.
.
.

s e t , m u l t i s e t ,
u n o r d e r e d _ s e t u n o r d e r e d _ m u l t i s e t STL.

, .

444

19. STL


STL
s e t m u l t i s e t
, .. , . >
(set) (m ultiset) , ,
.
. 19.1 , ,
. ,
STL , ,
, , .

. 1 9 .1 .

, s e t m u l t i s e t STL
. ,
. , , ,
,
. , s e :
.

std: :set std: imultiset,


:

#include <set>


se t m u ltis e t STL
-
s e t m u l t i s e t , .

s t d : : set

s t d : : s e t s t d : : m u l t i s e t :

set multiset STL

445

std::set <int> setlntegers;


std:imultiset <int> msetlntegers;

, T una,
:
std::set <Tuna> setlntegers;
std:rmultiset <Tuna> msetlntegers;

, ,
:
std::set<int>::const_iterator iElementlnSet;
std::multiset<int>::const_iterator iElementlnMultiset;


, i t e r a t o r c o n s t _ i t e r a t o r .
s e t m u l t i s e t ,
s t d : : l e s s o ,
. ,
.
,
o p e r a t o r ( ) ,
t r u e .
:
//
// /
template <typename >
struct SortDescending
{
bool operator()(const T& lhs, const T& rhs) const
{
return (lhs > rhs);

};

:
// ( )
set <int, SortDescending<int> > setlntegers;
multiset <int, SortDescending<int> > msetlntegers;

,
( 19.1).
1 9 .1 . -______

0: #include <set>

1:
2: //
// /
3: template <typename >
4: struct SortDescending
5:

446

19. STL

6:
7:
8:
9:
10:
11:

booloperator()(const &
{
return (lhs > rhs);
}

lhs, const

& rhs) const

};

12: int main ()


13: {
14:
using namespace std;
15:
16:
// (
// )
17:
set <int> setlntegersl;
18:
multiset <int> msetlntegersl;
19:
20:
//

//
21:
set<int, SortDescending<int> > setlntegers2;
22:
multiset<int, SortDescending<int> > msetlntegers2;
23:
24:
//
25:
set<int> setlntegers3(setlntegersl);
26:
multiset<int> msetlntegers3(setlntegersl.cbegin(),
setlntegersl.cend());
27:
28:
return 0;
29: }

,
,
i n t . 17 18 ,
, ,
s t d : : le s s < T > , ( ).
,
, 3 -1 0 , m a in ( ) , 21
22. ( ).
, 25 26
, (
, STL,
, c b e g i n () c e n d ()).

c b e g i n ()
c e n d ()7

, ,
C++11, begin () end ()
cbegin () cend () . cbegin () cend ()
++11, ,
.

set multiset STL

447


s e t m u l t i s e t .
. ,
i n s e r t ( ) ,
:
setlntegers.insert ( 1);
msetlntegers.insert (setlntegers.begin (), setlntegers.end ());

19.2 .

19.2, STL___________
0:
1:
2:
3:
4:
5:

template ctypename T>


void DisplayContents (const T& Input)

6:

7:
8:
9:
10:

#include <set>
#include <iostream>
using namespace std;

for(auto
;
;
cout

iElement = Input.cbegin () // auto, cebgin(): C++11


iElement != Input.cend () // cend(): C++11
++ iElement )
*iElement

11:

12:
cout endl;
13: }
14:
15: int main ()
16: {
17:
set <int> setlntegers;
19:
20:
setlntegers.insert (60);
21:
setlntegers.insert (-1);
22:
setlntegers.insert (3000);
23:
cout "Writing the contents of the set to the screen" endl;
24:
DisplayContents (setlntegers);
25:
26:
msetlntegers.insert (setlntegers.begin (), setlntegers.end ());
27:
msetlntegers.insert (3000);
28:
29:
cout "Writing the contents of the multiset to the screen"
endl;
30:
DisplayContents (msetlntegers);
31:
32:
cout "Number of instances of '3000' in the multiset are: '";
33:
cout msetlntegers.count (3000) "'" endl;
34:
35:
return 0;
36: }

448

19. STL

Writing the contents of the set to the screen


-1 60 3000
Writing the contents of the multiset to the screen
-1 60 3000 3000
Number of instances of '3000' in the multiset are: '2'

4 -1 3 D i s p l a y C o n t e n t s ( ) ,
17 18,
STL . 17 18, ,
s e t m u l t i s e t . 2 0 -2 2 , i n s e r t ( ) . 26 i n s e r t ()
( s e t l n t e g e r s m s e t I n t e g e r s ) . 27
3000, . ,
. 32
33 - m u l t i s e t : : c o u n t ( ) ,
, .

,
, multiset:: count ().

a u to ?

DisplayContents () 19.2
C++11 auto 7. ,
const_iterator cbeginO
cend (), ++11.

, ++11,
auto .
, DisplayContents ()
:

template ctypename >


void DisplayContents (const T& Input)

{
for (T::const_iterator iElement = Input.begin () //

; iElement != Input.end ()
; ++ iElement )
cout *iElement '
cout endl;

set multiset STL

449


, s e t , m u lt is e t , map m ultim ap,
- f i n d (), :
auto iElementFound = setlntegers.find (-1);
// , ...
if (iElementFound != setlntegers.end ())
cout "Element " *iElementFound " found!"
else
cout "Element not found in set!" endl;

endl;

f in d () 19.3.
, ,
, .
19.3. - findQ_________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:

#include <set>
#include <iostream>
using namespace std;
int main ()
{
set<int> setlntegers;

15 3ak. 3626

//
setlntegers.insert
(43);
setlntegers.insert
(78);
setlntegers.insert
(-1);
setlntegers.insert (124);
//
for (auto iElement = setlntegers.cbegin ()
; iElement != setlntegers.cend ()
; ++ iElement )
cout *iElement endl;
//
auto iElementFound = setlntegers.find (-1);
// , ...
if (iElementFound != setlntegers.end
())
cout "Element " *iElementFound " found!"
else
cout "Element not found in set!" endl;
//
auto iAnotherFind = setlntegers.find

endl;

(12345);

// , ...
if (iAnotherFind != setlntegers.end ())
cout "Element " ^iAnotherFind
else

" found!"

endl;

450

19. STL

36:
37:
38:
39: }

cout

"Element 12345 not found in set!"

endl;

return 0;

-i

43
78
124
Element -1 found!
Element 12345 not found in set!

2 1 -2 7 - f i n d ( ) .
, e n d ( ), 24,
, . , i
, * iE le m e n tF o u n d .

19.3 , ..
6 set multiset, .


, s e t , m u l t i s e t , map m u ltim a p ,
- e r a s e ( ) , :
setObject.erase (key);

e r a s e () , !
:
setObject.erase (iElement);

,
, :
setObject.erase (iLowerBound, iUpperBound);

19.4 e r a s e ()
.
1 9 .4 . - erase () _______________

0:
1:
2:
3:
4:
5:

#include <set>
#include <iostream>
using namespace std;
template <typename T>
void DisplayContents (const T& Input)

set multiset STL


6: {
7:
8:
9:
10:

for(auto
;
;
cout

iElement = Input.cbegin () // auto, cebgin(): C++11


iElement != Input.cend () // cend(): C++11
++ iElement )
*iElement '

.1 :
12:
13:
14:
15:
16:
17:
18:
19:

cout

endl;

}
typedef multiset <int> MSETINT;
int main ()
{
MSETINT msetIntegers;

20:

21:
22:
23:
24:
25:
26:
27:
28:

//
msetlntegers.insert (43);
msetlntegers.insert (78);
msetlntegers.insert (78); //
msetlntegers.insert (-1);
msetlntegers.insert (124);

29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49: }

cout

cout

"multiset contains " msetlntegers.size ()


" elements.";
" These are: " endl;

//
DisplayContents(msetlntegers);
cout "Please enter a number to be erased from the set"
endl;
int nNumberToErase = 0;
cin nNumberToErase;
cout
cout

"Erasing " msetlntegers.count (nNumberToErase);


" instances of value " nNumberToErase endl;

//
msetlntegers.erase (nNumberToErase);
cout "multiset contains " msetlntegers.size ()
" elements.";
cout " These are: " endl;
DisplayContents(msetlntegers);
return 0;

multiset contains 5 elements. These are:


-1 43 78 78 124
Please enter a number to be erased from the set

451

452

19. STL

78
Erasing 2 instances of value 78
multiset contains 3 elements. These are:
-1 43 124

15 t y p e d e f .
38 c o u n t
. 42,
, .
, e r a s e ()
. , , , ,
, .
MSETINT::iterator iElementFound = msetlntegers.find (nNumberToErase);
if (iElementFound != msetlntegers.end ())
msetlntegers.erase (iElementFound);
else
cout "Element not found!" endl;

e r a s e ()
:
MSETINT::iterator iElementFound = msetlntegers.find (nValue);
if (iElementFound != msetlntegers.end ())
msetlntegers.erase (msetlntegers.begin (), iElementFound);


n V a lu e , . ,
- c l e a r ().
, ,
.
19.5 ,
, ,
.
1 9 .5 . ,
set STL____________________________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

#include <set>
#include <iostream>
#include <string>
using namespace std;
template ctypename T>
void DisplayContents (const T& Input)
{
for(auto iElement = Input.cbegin () // auto, cebgin(): C++11
; iElement != Input.cend () // cend(): C++11
; ++ iElement )
cout *iElement endl;

set multiset STL


13:
cout endl;
14: }
15:
16: struct Contactltem
17: {
18:
string strContactsName;
19:
string strPhoneNumber;
20:
string strDisplayRepresentation;

21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47: };
48:
49: int
50: {
51:
52:
53:
54:
55:
56:
57:

//
Contactltem (const strings strName, const string & strNumber)
{
strContactsName = strName;
strPhoneNumber = strNumber;
strDisplayRepresentation = (strContactsName + ": " \
+ strPhoneNumber);
}
// set::find()
bool operator == (const ContactltemS itemToCompare) const
{
return (itemToCompare.strContactsName == \
this->strContactsName);
}
//
bool operator < (const ContactltemS itemToCompare) const
{
return (this->strContactsName \
< itemToCompare.strContactsName);
}
// DisplayContents cout
operator const char*() const
{
return strDisplayRepresentation.c_str();
}

main ()
set<ContactItem> setContacts;
setContacts.insert(Contactltem("Jack Welsch",
"+1 7889 879 879"));
setContacts.insert(Contactltem("Bill Gates",
"+1 97 7897 8799 8"));
setContacts.insert(Contactltem("Angela Merkel",
"+49 23456 5466"));
setContacts.insert(Contactltem("Vladimir Putin",
"+7 6645 4564 797"));
setContacts.insert(Contactltem("Manmohan Singh",
"+ 91 234 4564 789"));
setContacts.insert(Contactltem("Barack Obama",
"+1 745 641 314"));

454
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76: }

19. STL
DisplayContents(setContacts);
cout "Enter a person whose number you wish to delete: ";
string Namelnput;
getline(cin, Namelnput);
auto iContactFound = setContacts.find(Contactltem(Namelnput,
if(iContactFound != setContacts.end())
{

// ,
setContacts.erase(iContactFound);
cout "Displaying contents after erasing: "
endl;
DisplayContents(setContacts);

Namelnput

}
else
cout

"Contact not found"

endl;

return 0;

Angela Merkel: +49 23456 5466


Barack Obama: +1 745 641 314
Bill Gates: +1 97 7897 8799 8
Jack Welsch: +1 7889 879 879
Manmohan Singh: +91 234 4564 789
Vladimir Putin: +7 6645 4564 797
Enter a person whose number you wish to delete: Jack Welsch
Displaying contents after erasing: Jack Welsch
Angela Merkel: +49 23456 5466
Barack Obama: +1 745 641 314
Bill Gates: +1 97 7897 8799 8
Manmohan Singh: +91 234 4564 789
Vladimir Putin: +7 6645 4564 797

18.7, ,
.
, ,
, .
, 64 f i n d ( ) ,
, 68 e r a s e ().

455

set
STL,
. ,
(, ), multiset
STL. setContacts ,
.
,
- count (), ,
.
. ,
find () .
.




s e t m u l t i s e t STL
, . ,
. , ,
. ,
,
, f i n d ().
f i n d () .

, .
, (, s t d : : f i n d ()),
.
,
, .

++11____________________________________________
- STL
s t d : :unordered_set s t d : :unordered_multiset
s t d : : s e t s t d : : m u l t i s e t STL (
) s t d : : l e s s < T >
, . ,
, , , s o r t ()
. , , ,
, .
, 10 000 , 100
(, 1002 = 10000 log(10000) = 2xlog(100)).

456

19. STL


(
) .
,
, -
. - -,
, . STL
- s t d : : u n o r d e r e d _
s e t.

std: :unordered_set
std: :unordered_multiset, :

#include<unordered set>

s t d : : s e t :
// :
unordered_set<int> usetlnt;
//
usetlnt.insert (1000);
// find() :
auto iPairThousand = usetlnt.find(1000);
if (iPairThousand != usetlnt.end())
cout *iPairThousand endl;

u n o r d e r e d map
- , :
unordered_set<int>::hasher HFn = usetlnt.hash_function();

19.6 ,
s t d : : h a s h _ s e t .

19.6. insert () ,find () fsize () ,max_bucket_


count (), load_factor () max_load_factor () std: :unordered_set______________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

#include<unordered_set>
#include <iostream>
using namespace std;
template ctypename T>
void DisplayContents(const T& Input)
{

cout "Number of elements, size() = " Input.size() endl;


cout "Max bucket count = " Input.max_bucket_count()
endl;
cout "Load factor: " Input.load_factor() endl;
cout "Max load factor = " Input.max_load_factor() endl;
cout "Unordered set contains: " endl;


13:
14:
15:
16:
17:
18:
19: }
20:
21: int
22: {
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50: }

for(auto iElement = Input.cbegin() // auto, cbegin: C++11


; iElement != Input.cend()
// cend: C++11
; ++ iElement )
co u t *iElement '
c o u t endl;

main()
// unordered_set:
unordered_set<int> usetlnt;
usetlnt.insert (1000);
usetlnt.insert(-3);
usetlnt.insert(2011);
usetlnt.insert(300);
usetlnt.insert(-1000);
usetlnt.insert(989);
usetlnt.insert(-300);
usetlnt.insert (111);
DisplayContents(usetlnt);
usetlnt.insert(999);
DisplayContents(usetlnt);
// find() :
cout "Enter int you want to check for existence in set:
int Key = 0;
cin Key;
auto iPairThousand = usetlnt.find(Key);
if (iPairThousand != usetlnt.end())
cout *iPairThousand " found in set" endl;
else
cout Key " not available in set" endl;
return 0;

Number of elements, size() = 8


Max bucket count = 8
Load factor: 1
Max load factor = 1
Unordered set contains:
1000 -3 2011 300 -1000 -300 989 111
Number of elements, size() = 9
Max bucket count = 64
Load factor: 0.140625
Max load factor = 1
Unordered set contains:
1000 -3 2011 300 -1000 -300 989 999 111
Enter int you want to check for existence in set: -1 0 0 0
-1000 found in set

457

458

19. STL

u n o rd e re d _ s e t ;
, ,
m a x _ b u ck e t_ co u n t (), lo a d _ f a c t o r () m a x _ lo a d _ fa c t o r () ,
8 -1 0 . , ,
1,
. u n o r d e r e d _ s e t ,
, 64 -, .
m a in () ,
u n o rd e re d _ s e t s e t. f i n d ()
, , 42,
.
- ,
,
std::unordered_map 20, STL".
std: :unordered_map -, - ;
++11.
!

, set multiset
STL

opera

, std: :multiset

(), std::set

multiset::count {
)

, set:: size {)
multiset::size

t o r operator^ ,
,
set multiset.
,
, set:: find ()

std:: set
std: multiset
.
,
std::vector std::list

s e t m u l t i s e t
STL, - .
,
.

459


,
?
s e t < i n t > .
s t d : : l e s s < T > ,
, s e t c i n t ,
l e s s < i n t > > .
s e t< in t, g r e a te r c in t .

, "Jack" ?
.
s t d : : s e t .

, -
"Jack"?
s e t .
m u l t i s e t .

- m u ltiset
?
c o u n t ( ) .

fin d (),
.
, ?
. STL
, , ,
f i n d (). .
, STL
.


, ,
. ,
, .
,
.


1. s e t < i n t > .
?
2. m u l t i s e t ?
3. s e t m u l t i s e t
?

460

19. STL

1.
C o n t a c t Ite m . (:
, ,
<.)
2. , ..
. (:
, : .)
3. , ,
, .

20


STL
(STL)
,
.
.

map, multimap, unordered_map


unordered_multimap STL.

, .

-.

462

20. STL

STL
m u ltim a p - ,
, . 20.1.

. 20.1. ,

( ) (m u ltim a p ) ,
, .
, m u ltim a p STL
. , ,
, . ,
, ,

. , ,
.

std::map std: :multimap,


:

#include<map>

std::map std::multimap STL

463

std: :
std: :multixnap STL
-
m u ltim a p STL, .

std: : std: :multimap



s t d : :map s t d : : m u ltim a p .

, () ,
.
:
#include <map>
using namespace std;
map <keyType, valueType, Predicate=std::less <keyType> > mapObject;
multimap <keyType, valueType, Predicate=std::less <keyType> > mmapObject;

, .
, ,
s t d : :m ap s t d : : m u ltim a p
s t d : : l e s s o . , ,
, :
std::map<int, string> mapIntToString;
std::multimap<int, string> mmapIntToString;

20.1 .
20.1. multimap,

_________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include<map>
#include<string>
template<typename >
struct ReverseSort
{
bool operator()(const KeyType& keyl, const KeyType& key2)
{
return (keyl > key2);
}
};

11:

12: int main ()


13: {
14:
usingnamespace
std;
15:
16:
//
int string

464
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39: }

20. STL
mapcint, string> mapIntToStringl;
multimap<int, string> mmapIntToStringl;
//
mapcint, string> mapIntToString2(mapIntToStringl);
multimapcint, string> mmapIntToString2(mmapIntToStringl);
//
mapcint, string> mapIntToString3(mapIntToStringl.cbegin(),
mapIntToStringl.cend());
multimapcint, string> mmapIntToString3(mmapIntToStringl.cbegin(),
mmapIntToStringl.cend()) ;
//
mapcint, string, ReverseSortcint> > mapIntToString4
(mapIntToStringl.cbegin(), mapIntToStringl.cend());
multimapcint, string, ReverseSortcint> > mmapIntToString4
(mapIntToStringl.cbegin(), mapIntToStringl.cend());
return 0;

12-39 m a in ( ) .
21 22.
2 5 -2 8 ,
. 3 1 -3 6
.
, ( )
s t d : : le s s C T > , .
, ,
, o p e r a t o r ( ). R e v e r s e S o r t
4 -1 0 32
35.

c b e g in ()
cend

,
0 + 1 1 , begin () end ()
cbegin () cend () . cbegin () cend ()
0 + 1 1 , ,
.

std::map std::multimap STL

465

STL
.
.
- i n s e r t ():
std::map<int, std::string> mapIntToStringl;
// make_pair()
mapIntToString.insert (make_pair (-1, "Minus One"));

- ,
s t d : : p a i r :
mapIntToString.insert (pair <int, string>(1000, "One Thousand"));

, ,
o p e r a t o r [ ]:
mapIntToString [1000000] = "One Million";

:
std::multimap<int, std::string> mmapIntToString(mapIntToString.cbegin(),
mapIntToString.cend());

20.2 .

20.2.
insert operator []_____________
0:
1:
2:
3:
4:
5:
6:
7:
8:

#include <map>
#include <iostream>
#include<string>
using namespace std;
//
typedef map <int, string> MAP_INT_STRING;
typedef multimap <int, string> MMAP_INT_STRING;

9:
10: template <typename T>
11: void DisplayContents (const T& Input)
12: {
13:
for(auto iElement = Input.cbegin() // auto and cbegin(): C++11
14:
; iElement != Input.cend()
// cend(): C++11
15:
; ++ iElement )
16:
cout << iElement->first " -> " iElement->second
endl;
17:
18:
cout endl;
19: }
20:
21: int main ()
22: {
23:
MAP_INT_STRING mapIntToString;
24:
25:
// "-"
// value_type

466
26:
27:
28:
29:
30:
31:
32:
33:
34:

20. STL
mapIntToString.insert (MAP_INT_STRING::value_type (3, "Three"));
// makejpair()
mapIntToString.insert (make_pair (-1, "Minus One"));
//
mapIntToString.insert (pair <int, string>(1000, "One Thousand"));

35:
36:
37:
38:
39:
40:
41:
42:
4 3:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59: }

// "-"
//
mapIntToString [1000000] = "One Million";
cout "The map contains " mapIntToString.size
cout " key-value pairs. They are: " endl;
DisplayContents(mapIntToString);

();

// ,
MMAP_INT_STRING mmapIntToString(mapIntToString.cbegin(),
mapIntToString.cend());
// insert() ,
// .
mmapIntToString.insert(make_pair
(1000, "Thousand"));
cout endl "The multimap contains "
mmapIntToString.size ();
cout " key-value pairs. They are: " endl;
cout "The elements in the multimap are: " endl;
DisplayContents(mmapIntToString);
//
cout \
"The number of pairs in the multimap with 1000 as their key:"
mmapIntToString.count (1000) endl;
return 0;

The map contains 4 key-value pairs. They are:


-1 -> Minus One
3 -> Three
1000 -> One Thousand
1000000 -> One Million
The multimap contains 5 key-value pairs. They are:
The elements in the multimap are:
-1 -> Minus One
3 -> Three
1000 -> One Thousand
1000 -> Thousand
1000000 -> One Million
The number of pairs in the multimap with 1000 as their key: 2

std::map std::multimap STL

467


m u lt im a p 7 8. (
). 10-19 D i s p l a y C o n t e n t s ( ) ,
,
f i r s t , , s e c o n d , . 2 6 -3 2
-
i n s e r t ( ). 35
o p e r a t o r [ ] .
, ,
47, . ,
( 42 43). ,
-
. ,
( 1000). 56
m u l t i m a p : : c o u n t ( ) ,
.

a u t o ?

DisplayContents () 20.2
C++11 auto 13. ,
const_iterator cbeginO
cend (), ++11.

, ++11,
auto .
, DisplayContents ()
:

template ctypename >


void DisplayContents (const T& Input)

{
for (T::const_iterator iElement = Input.begin ()
; iElement != Input.end ()
; ++ iElement )
cout iElement->first " -> " iElement->second
endl;
cout endl;

STL
, m u ltim a p , -
f i n d ( ) , .
:

468

20. STL

multimap <int, string>::const_iterator iPairFound = mapIntToString.


find(Key);

,
f i n d ():
if (iPairFound != mapIntToString.end())

{
cout
cout

"Key " iPairFound->first


iPairFound->second endl;

cout

"Sorry, pair with key "

" points to Value: ";

}
else

Key

" not in map"

endl;

, C++11,
auto:

auto iPairFound = mapIntToString.find(Key);


,
map::find().

20.3 m u l t i m a p : : f i n d ().

20.3. - find ()
-_______
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:

#include <map>
#include <iostream>
#include <string>
using namespace std;
template ctypename T>
void DisplayContents (const T& Input)
{
for(auto iElement = Input.cbegin () // auto and cbegin(): C++11
// cend(): C++11
; iElement != Input.cend()
; ++ iElement )
cout iElement->first " -> " iElement->second
endl;

12:

13:
cout endl;
14: }
15:
16: int main()
17: {
18:
map<int, string> mapIntToString;
19:
20:
mapIntToString.insert(make_pair(3, "Three"));
21:
mapIntToString.insert(make_pair(45, "Forty Five"));
22:
mapIntToString.insert(make_pair(-1, "Minus One"));
23:
mapIntToString.insert(make_pair(1000, "Thousand"));
24
cout "The multimap contains " mapIntToString.size();
25

std::map std::multimap STL


26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:

cout

" key-value pairs. They are: "

469

endl;

//
DisplayContents(mapIntToString);
cout "Enter the key you wish tofind:
int Key = 0;
cin Key;

";

auto iPairFound = mapIntToString.find(Key) ;


if (iPairFound !=mapIntToString.end())
{
cout "Key " iPairFound->first " points to Value: ";
cout iPairFound->second endl;
}
else
cout "Sorry, pair with key " Key " not in map"
endl;

43:
44:
45: }

return 0;

The multimap contains 4 key-value pairs. They are:


-1 -> Minus One
3 -> Three
45 -> Forty Five
1000 -> Thousand
Enter the key you wish to find: 45
Key 45 points to Value: Forty Five
( find() ):
The multimap contains 4 key-value pairs. They are:
-1 -> Minus One
3 -> Three
45 -> Forty Five
1000 -> Thousand
Enter the key you wish to find: 2011
Sorry, pair with key 2011 not in map

20 -2 3 m a in () ,
. ,
f i n d () 35 . m a p : : f i n d ()
, , ,
e n d ( ) , 36.
, s e c o n d ( 39).
2 011, ,
.

470

20. STL

f in d ( ) ,
.

STL
20.3 ,

, . ,
m u l t i s e t : : c o u n t () ,
, :
auto iPairFound = mmapIntToString.find(Key);
//
if(iPairFound != mmapIntToString.end())

{
//
size_t nNumPairsInMap = mmapIntToString.count(1000);
for( size_t nValuesCounter = 0
; nValuesCounter < nNumPairsInMap //
; ++ nValuesCounter )

{
cout
cout
cout

"Key: " iPairFound->first; //


", Value [" nValuesCounter "] = ";
iPairFound->second endl;
//

++ iPairFound;

}
else
cout

"Element not found in the multimap";

STL
- e r a s e ( ) ,
.
e r a s e () :
mapObject.erase (key);

e r a s e ()
:
mapObject.erase (iElement);

,
, :
mapObject.erase (iLowerBound, iUpperBound);

20.4 e r a s e ().

std::map std::multimap STL


20.4. _______________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:

#include<map>
#include<iostream>
#include<string>
using namespace std;
template<typename T>
void DisplayContents(const T& Input)
{
for(auto iElement = Input.cbegin () // auto cbegin(): C++11
; iElement != Input.cend()
// cend(): C++11
; ++ iElement )
c o u t iElement->first " -> " iElement->second endl;
c o u t endl;
}
int main()
{
multimapcint, string> mmapIntToString;
// "-"
mmapIntToString.insert(make_pair(3, "Three"));
mmapIntToString.insert(make_pair(45, "Forty Five"));
mmapIntToString.insert(make_pair(-1, "Minus One"));
mmapIntToString.insert(make_pair(1000, "Thousand"));
//
mmapIntToString.insert(make_pair(-1, "Minus One"));
mmapIntToString.insert(make_pair(1000, "Thousand"));
c o u t "The multimap contains " mmapIntToString.size ();
c o u t " key-value pairs. " "They are: " endl;
DisplayContents(mmapIntToString);
// -1
auto NumPairsErased = mmapIntToString.erase(-1);
c o u t "Erased " NumPairsErased " pairs with -1 as key."
endl;
//
auto iPairLocator = mmapIntToString.find(45);
if(iPairLocator != mmapIntToString.end())
{
mmapIntToString.erase(iPairLocator);
co u t "Erased a pair with 45 as key using an iterator"
endl;
}
// ...
c o u t "Erasing the range of pairs with 1000 as key." endl;
mmapIntToString.erase( mmapIntToString.lower_bound(1000)
, mmapIntToString.upper_bound(1000) );

471

472
51:
52:
53:
54:
55:
56: }

20. STL
cout<< "The multimap now contains " mmapIntToString.size();
c out " key-value pair(s)." "They are: " endl;
DisplayContents(mmapIntToString);
return 0;

The multimap contains 6 key-value pairs. They are:


-1 -> Minus One
-1 -> Minus One
3 -> Three
45 -> Forty Five
1000 -> Thousand
1000 -> Thousand
Erased 2 pairs with -1 as key.
Erased a pair with 45 as key using an iterator
Erasing the range of pairs with 1000 as key.
The multimap now contains 1 key-value pair(s).They are:
3 -> Three

2 1 -2 8 ,
( , ,
). ,
e r a s e ( ),
(-1), 35. m ap: : e r a s e (Key)
, . 39
, f i n d (4 5 ),
45. 48 49 ,
l o w e r _ b o u n d () u p p e r _ b o u n d ().



m u lt im a p ,
.
( ),
, s t d : : l e s s o , , ,
, o p e r a t o r s
,
, o p e r a t o r ():
template<typename >
struct Predicate
{
bool operator()(const keyl, const key2)

473

{
//

}
};
, s t d : : s t r i n g ,
<, s t d : : s t r i n g
s t d : : le s s < T > ,
. , ,
,
,
t r u e f a l s e :
<, , > ;

20.5 .
2 0 .5 .
___________________

0: #include<map>
1: #include<algorithm>
2 : #include<string>
3: #include<iostream>
4: using namespace std;

5:
6 : template ctypename T>
7: void DisplayContents (const T& Input)
8:

9:
10:
11:

12:

{
for(auto
;
;
cout

iElement = Input.cbegin () // auto cbegin(): C++11


iElement != Input.cend()
// cend(): C++11
++ iElement )
iElement->first " -> " iElement->second
endl;

13:
14:
cout endl;
15: }
16:
17: struct PredlgnoreCase
18: {
19:
bool operator()(const strings strl, const strings str2) const
20:
{
21:
string strlNoCase(strl), str2NoCase(str2);
22:
std: transform (strl .begin () , strl.endO, strlNoCase .begin () ,
tolower);
23:
std::transform(str2.begin(), str2.end(), str2NoCase.begin(),
tolower);
24:
25:
return(strlNoCase< str2NoCase);
26:
};
27: };
28:
29: typedef map<string, string> DIRECTORY_WITHCASE;
30: typedef map<string, string, PredIgnoreCase> DIRECTORY_NOCASE;
31:

474

20. STL

32: i n t m a i n ()
33: {
34:
/ / :
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:

69:
70:
71:
72:
73:
74:
75:
76:
77:
78:

/ /
DIRECTORY NOCASE d i r C a s e l n s e n s i t i v e ;
d i r C a s e l n s e n s i t i v e . i n s e r t ( m a k e _ p a i r (" J o h n " ,
d i r C a s e l n s e n s i t i v e . i n s e r t ( m a k e _ p a i r ("JOHN",
d i r C a s e l n s e n s i t i v e . i n s e r t ( m a k e _ p a i r (" S a r a " ,
d i r C a s e l n s e n s i t i v e . i n s e r t ( m a k e _ p a i r (" J a c k " ,

"2345764"));
"2345764"));
"42367236"));
"32435348"));

c o u t " D i s p l a y i n g c o n t e n t s o f t h e c a s e - i n s e n s i t i v e map:"
endl;
D isp la y C o n te n ts(d irC a seln sen sitiv e);
/ / :
/ /
DIRECTORY_WIAS dirCaseSensitive(dirCaselnsensitive.begin()

, d irC a se ln se n sitiv e .end());


cout "D isplaying co n te n ts of th e c a s e - s e n s i t i v e m a p :" endl
D isp la y C o n te n ts(d irC a seS en sitiv e );
/ /
c o u t " P l e a s e e n t e r a name t o s e a r c h : " e n d l "> ";
s t r i n g strN a m e In p u t;
c i n strN a m e ln p u t;
/ / . . .
a u t o iP a ir ln N o C a s e D i r = d i r C a s e l n s e n s i t i v e . f i n d ( s t r N a m e l n p u t ) ;
i f ( i P a i r l n N o C a s e D i r != d i r C a s e l n s e n s i t i v e . e n d ())
{
cout iP airIn N o C aseD ir-> first
" ' s number i n t h e c a s e - i n s e n s i t i v e " ;
c o u t " d i r e c t o r y i s : " iP a ir I n N o C a s e D i r - > s e c o n d e n d l
}
else
{
c o u t s t r N a m e I n p u t " ' s number n o t found ";
cout "in th e c a s e - in s e n s it iv e d i r e c t o r y " endl;
}
/ / . . .
auto iP airln C aseS en sD ir = d ir C a s e S e n s itiv e .f in d ( s tr N a m e ln p u t) ;
i f ( i P a i r l n C a s e S e n s D i r != d i r C a s e S e n s i t i v e . e n d ())
{
cout < < iP airIn C aseS en sD ir-> first
" ' s number i n t h e c a s e - s e n s i t i v e " ;
c o u t " d i r e c t o r y i s : " iP a ir I n C a s e S e n s D ir - > s e c o n d
endl;
}
else
{


79:
80:
81:
82:
83:
84:}

cout
cout

475

strNameInput
s number was not found ";
"in the case-sensitive directory" endl;

}
return 0;

Displaying contents of the case-insensitive map:


Jack -> 32435348
John -> 2345764
Sara -> 42367236
Displaying contents of the case-sensitive map:
Jack -> 32435348
John -> 2345764
Sara -> 42367236
Please enter a name to search:

> sara
Sara's number in the case-insensitive directory is: 42367236
sara's number was not found in the case-sensitive directory

:
s t d : : le s s < T >
s t d : : s t r i n g : : o p e r a t o r < ,
P r e d l g n o r e C a s e ( 17-27),
. , *s a r a '
S a r a ,
.

20.5 PredlgnoreCase ,
operator () public.
C++
.


, , ,
, .
, , o p e r a
t o r ( ) . .
(function object) (functor).
21, .

476

20. STL

std : :map -, ;
, .
, , |
. . I
, ,
, ..
.
, , 10 - j
, std : :map std : : s e t , j
, 100 .
, ..
10 000 100 , 100.

++11____________________________________________
std: :unordered_map STL
-
C++11 STL -
s t d : :u n o r d e r e d _ m a p .
:
#include<unordered_map>
u n o r d e r e d map
, .

-

( ), ,
- (hash table).
- - ,
. -
, - ,
( ).
-, :
= - (, ) ;

f i n d ( ) - ()
,
, . , - ()
, ,
, . ,
(collision),
.

477

- ++11:
unorderedjnap unordered_multimap

s t d : :m ap s t d : : m u ltim a p . ,
:
// unorderedjnap int string:
unorderedjnap<int, string> umapIntToString;
// insert ()
umapIntToString.insert(make_pair(1000, "Thousand"));
// find () :
auto iPairThousand = umapIntToString.find(1000);
cout << iPairThousand->first " > " << iPairThousand->second
// :
cout "umapIntToString[1000] = " umapIntToString[1000]

endl;

endl;

u n o r d e r e d j n a p
-, :
unorderedjnapcint, string>::hasher HFn =
umapIntToString.hash_function();

- , :
size_t HashingValuelOOO = HFn(1000);

u n o r d e r e d _ m a p - ,
,
:
cout
cout

cout

"Load factor: " umapIntToString.load_factor() endl;


"Max load factor = " umapIntToString.max_load_factor()
endl;
"Max bucket count = " umapIntToString.max_bucket_count()
endl;

l o a d _ f a c t o r () , ..
u n o r d e r e d j n a p . l o a d _ f a c t o r ()
m a x _ lo a d _ f a c t o r ( ) , ,
, -, 20.6.
std: :unordered_multimap unordered_
map, .
std: :unordered_multimap
std::multimap, -,
20.6.

478

20. STL

20.6. - unordered_,
insert (), find ,size ,max_bucket_count (),
load_f actor () max__load_factor ()
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;

template ctypename Tl, typename T2>


void DisplayUnorderedMap(unordered_map<Tl, T2>& Input)
{
cout "Number of pairs, size(): " Input.size() endl;
cout "Max bucket count = " Input.max_bucket_count()
endl;
10:
cout "Load factor: " Input.load_factor() endl;
11:
cout "Max load factor = " Input.max_load_factor() endl;
12:
cout "Unordered Map contains: " endl;
13:
14:
for(auto iElement = Input.cbegin() // auto, cbegin: C++11
15:
; iElement != Input.cend()
// cend(): C++11
16:
; ++ iElement )
17:
c o u t iElement->first " -> " iElement->second endl;
18: }
19:
20: int main()

21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:

unordered_map<int, string> umapIntToString;


umapIntToString.insert(make_pair(1, "One"));
umapIntToString.insert(make_pair(45, "Forty Five"));
umapIntToString.insert(make_pair(1001, "Thousand One"));
umapIntToString.insert(make_pair(-2, "Minus Two"));
umapIntToString.insert(make_pair(-1000, "Minus One Thousand"));
umapIntToString.insert(make_pair(100, "OneHundred"));
umapIntToString.insert(make_pair(12, "Twelve"));
umapIntToString.insert(make_pair(-100, "Minus One Hundred"));
DisplayUnorderedMapcint, string>(umapIntToString);
cout "Inserting one more element" endl;
umapIntToString.insert(make_pair(300, "Three Hundred"));
DisplayUnorderedMap<int, string>(umapIntToString);
cout "Enter key to find for: ";
int Key = 0;
cin Key;
auto iElementFound = umapIntToString.find(Key);
if (iElementFound != umapIntToString.end())
{
cout "Found! Key " iElementFound->first
" points to value ";
cout iElementFound->second endl;
}


48:
49:

479

else
cout

50:
51:
52: }

"Key has no corresponding value in unordered map!"


endl;

return 0;

Number of pairs, size(): 8


Max bucket count = 8
Load factor: 1
Max load factor = 1
Unordered Map contains:
-1000 -> Minus One Thousand
1001 -> Thousand One
1 -> One
-100 -> Minus One Hundred
45 -> Forty Five
-2 -> Minus Two
12 -> Twelve
100 -> One Hundred
Inserting one more element
Number of pairs, size(): 9
Max bucket count = 64
Load factor: 0.140625
Max load factor = 1
Unordered Map contains:
1 -> One
-1000 -> Minus One Thousand
1001 -> Thousand One
-100 -> Minus One Hundred
45 -> Forty Five
-2 -> Minus Two
300 -> Three Hundred
12 -> Twelve
100 -> One Hundred
100 -> One Hundred
Enter key to find for: 300
Found! Key 300 points to value Three Hundred

, u n o rd e r e d _ m a p ,
,
. 64.
m a x _ b u c k e t_ c o u n t ( ) , l o a d _ f a c t o r () m a x _ lo a d _
f a c t o r () 9 -1 1 , ,
s t d : :m ap.
f i n d () 42, , s t d : :m ap,
e n d ( ) ,
.

480

20. STL

unordered_map
.
, , ,
..
, ;
.
|

std: :unordered_map
( )
.
std: :unordered_map std: :map,
. , .

|
i
'
j

,
.

,
-"

, multimap::count
{)
,

,
-,
(,
)


find (), end ()

, , ,
STL,
size (),

unorderedjmap
unordeed_mu 11imap,

(,
)

m u ltim a p
STL, - . ,
STL
- unordered_m ap unordered_m ultim ap.
,
.
, 20.5.

48 1


,
?
m a p < in t> .
s t d : : le s s < T > ,
. m a p < in t, l e s s < in t> > .
m a p c i n t , g r e a t e r < i n t > > .

"Jack" ?
.
s t d : :map .

, -
"Jack"?
.
m u ltim a p .

- multimap
?
c o u n t ( ) .
f i n d (),
.
, ?
. STL
, , ,
f i n d (). .
, STL
.

,
auto. ,
map:: f in d () ?
:
< >::iterator ;

, :
std::map<int>::iterator iPairFound = maplntegers.find(1000);
if (iPairFound != maplntegers.end())
; //


, ,
. ,
, .
,
.

16 . 3626

482

20. STL


1. i n t> .
?
2. ?
3. m u ltim a p
?
4. ?

1. , ,
. ?
.
2. :
map <wordProperty, string, fPredicate> mapWordDefinition;

:
struct wordProperty
{
string strWord;
bool blsFromLatin;

};
3. f P r e d i c a t e ,
w o r d P r o p e r t y , .
4. ,
, .

IV

STL
21.
22. - ++11
23. STL
24. :
25.
STL

21

(function object), (functor),


- , ,
, , , ,
.
.

486

21.



,
. ,
o p e r a t o r ( ).
, ,
o p e r a t o r () (.. ),
(STL).
, , STL
.

(unary function). ,
f ( ) . b o o l ,
(predicate).
(binary function). ,
f (, ) . b o o l,

(binary predicate).
, b o o l ,
. , ,
(adaptive function object).

1

,
.
,
, C++!


.
, .
:
//
template <typename elementType>
void FuncDisplayElement (const elementType & element)

{
cout << element << ' ';

};

F u n c D i s p l a y E l e m e n t () e l e
m e n tT y p e , s t d : : c o u t .
,
o p e r a t o r () :

487

// ,
template <typename elementType>
struct DisplayElement

{
void operator

() (const elementType& element) const

{
cout << element << ' ';

}
};
, DisplayElement - .
, operator ()
public. ,
.

STL f o r _
each, , ,
21.1.
2 1 .1 .
_____________________________

0
1
3

#include
#include
#include
#include

4
5

using namespace std;

<algorithm>
<iostream>
<vector>
<list>

6
7

8
9
10

// ,
template <typename elementType>
struct DisplayElement

11

void operator

12

13
14
15
16
17
18
19

cout

() (const elementType& element) const

element

' ';

}
};
int main

()

{
vector <int> veclntegers;

20

21
22
23
24
25
26
27
28
29
30
31

for (int nCount = 0; nCount < 10; ++ nCount)


veclntegers.push_back (nCount);
list <char> listChars;
for (char nChar = 'a'; nChar < 'k'; ++nChar)
listChars.push_back (nChar);
cout << "Displaying the vector of integers: " << endl;
//

488
32
33
34
35
36
37
38
39
40
41
42
43
44
45

21.
for_each ( veclntegers.begin () //
, veclntegers.end ()
//
, DisplayElement <int> () ); //
cout << endl << endl;
cout << "Displaying the list of characters:

" << endl;

//
for_each ( listChars.begin () //
, listChars.end ()
//
, DisplayElement <char> () ); //
return 0;

Displaying the vector of integers:


0 1 2 3 4 5 6 7 8 9
Displaying the list of characters:
a b c d e f g h i j

8 -1 5 D i s p l a y E l e m e n t ,
o p e r a t o r ( ) . s t d : : f o r _ e a c h ()
STL 3 2 -3 4 . f o r _ e a c h ( ) :
, , ,
. ,
D i s p l a y E l e m e n t : : o p e r a t o r () v e c l n t e g e r s .
, D is p la y E le m e n t
F u n c D is p la y E le m e n t ( ). 40-^42
.

C++11 -,
.
- DisplayElement<T> 21.1
,
main (), 32-34:

// , -
for_each ( veclntegers.begin () //
, veclntegers.end ()
//
, [] (int& Element) {cout element '
} );
// -
, - - C++
22, "-
++1. 22.1 -
for_each ()
, 21.1.

489

, ,
,
. , F u n c D is p la y E le m e n t ()
, ,
o p e r a t o r ( ). , :
template <typename elementType>
struct DisplayElementKeepCount
{
int Count;
DisplayElementKeepCount

() //

{
Count = 0;

}
void operator

() (const elementType& element)

{
++ Count;
cout << element

' ;

D is p la y E le m e n tK e e p C o u n t
. o p e r a t o r ()
- , (
, ) - C o u n t,
.
C o u n t. ,
, 21.2.

21.2. ________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
template<typename elementType>
struct DisplayElementKeepCount
{
int Count;

10:
11:
12:

//
DisplayElementKeepCount() : Count(0) {}

13:
14:
15:
16:
17:
18:
19:
20:

// , !
void operator()(const elementType& element)
++ Count;
cout e l e m e n t

490

21.

21: int main()


22: {
23:
vector<int> veclntegers;
24:
for(int nCount = 0; nCount< 10; ++ nCount)
25:
veclntegers.push_back(nCount) ;
26:
27:
cout << "Displaying the vector of integers: "<< endl;
28:
29:
//
30:
DisplayElementKeepCount<int> Result;
31:
Result = for_each( veclntegers.begin() //
32:
, veclntegers.e n d ()
//
33:
, DisplayElementKeepCount<int>() ); //
34:
35:
cout << endl<< endl;
36:
37:
// !
38:
cout << " '" << Result.Count << "' elements were displayed!"
<< endl;
39:
40:
return 0;
41: }

Displaying the vector of integers:


0 1 2 3 4 5 6 7 8 9
'10' elements were displayed!

21.1 D is p la y E le m e n tK e e p C o u n t
f o r _ e a c h ( ). o p e r a t o r ( ) , D is p la y E le m e n tK e e c
C o u n t, f o r _ e a c h () .
, C o u n i.
f o r _ e a c h () 38
. ,
, ,
.


, b o o l, .
STL . 21.3
, ,
2 1 .3 . , ,

0: //
1: template ctypename numberType>
2: struct IsMultiple


3:

491

4:
5:
6:
7:
8:
9:

numberType Divisor;
IsMultiple (const numberType& divisor)
{
Divisor = divisor;
}

10:

11:
12:
13:
14:
15:
16: };

bool operator

() (const numberType& element) const

// ,
return ((element % Divisor) == 0);
}

o p e r a t o r () b o o l
. .
, ,
. , o p e r a t o r ()
%,
. , .
21.4 , 21.3,
, , .
21.4. IsMultiple std: : find_
if , _______
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
// IsMultiple 21.3
int main ()
{

vector <int> veclntegers;


cout << "The vector contains the following sample values: ";
// : 25 - 31
for (int nCount = 25; nCount < 32; ++ nCount)
{

veclntegers.push_back (nCount);
cout << nCount << ' ';
}
cout << endl << "Enter divisor
int Divisor = 2 ;
cin >> Divisor;

(> 0): ";


,

// , 4
auto iElement = find_if (veclntegers.begin ()
, veclntegers.end ()
, IsMultiple<int>(Divisor) );

492
24:
25:
26:
27:
28:
29:
30:
31:
32: }

21.

if(iElement != veclntegers.end ())


{
cout << "First element in vector divisible by " << Divisor;
cout << ": " << *iElement << endl;
}
return

0;

The vector contains the following sample values: 25 26 27 28 29 30 31


The first element in the vector that is divisible by 4 is: 28

. 11-15
.
f i n d _ i f ( ) , 23. I s M u lt i p l e ( ) ,
D i v i s o r . f i n d _ i f ()
I s M u l t i p l e : : o p e r a t o r ()
. o p e r a t o r () t r u e (
, 4 ), f i n d i f ()
i E l e m e n t . f i n d _ i f ()
e n d () , (
25). iE l e m e n t ,
28.

, -
, 21.4,
22.3 22.

S T L ,
s t d : : p a r t i t i o n ( ) , ,
s t a b l e _ p a r t i t i o n ,
, , s t d : : f i n d i f ( ),
, s t d : : r e m o v e _ i f ( ),
.


f ( , ) ,
.
, , , ..
, ,
:

493

template <typename elementType>


class Multiply
{
public:
elementType operator () (const elementType& eleml,
const elementType& elem2)

{
return (eleml * elem2);

}
};
o p e r a t o r ( ) ,
.
, s t d : : t r a n s f o r m ( ),
. 21.5
s t d : : t r a n s f o r m ().

21,8,
0
1
2

#include <vector>
#include <iostream>
#include <algorithm>

3
4
5
6
7
8

template <typename elementType>


class Multiply
{
public:
elementType operator () (const elementType& eleml,
const elementType& elem2)

10

11
12

13
14
15
16
17
18
19
20

return

(eleml * elem2);

};
int main

()

{
using namespace std;
// 10
vector <int> vecMultiplicand, vecMultiplier;

21
22
23
24
25
26
27
28
29
30
31
32
33
34

// 0 9
for (int nCountl = 0; nCountl < 10; ++ nCountl)
vecMultiplicand.push_back (nCountl);
// 100 109
for (int nCount2 = 100; nCount2 < 110; ++ nCount2)
vecMultiplier.push_back (nCount2);
//
vector <int> vecResult;
//
vecResult.resize (10);

494
35
36
37
38
39
40
41
42

21.
transform ( vecMultiplicand.begin (), //
vecMultiplicand.end (),
//
vecMultiplier.begin (),
//
vecResult.begin (), // ,
Multiply <int> () ); //
cout "The contents of the first vector are: " endl;
for (size_t nlndexl = 0; nlndexl < vecMultiplicand.size ();
++ nlndexl)
cout vecMultiplicand [nlndexl]
cout << endl;

43
44
45
46
47

cout "The contents of the second vector are: " endl;


for (size_t nlndex2 = 0; nlndex2 < vecMultiplier.size ();
++nlndex2)
cout << vecMultiplier [nlndex2]
' ';
cout << endl << endl;

48
49
50
51
52
53
54
55
56

cout << "The result of the multiplication is: " << endl;
for (size_t nlndex = 0; nlndex < vecResult.size (); ++ nlndex)
cout << vecResult [nlndex] << ' ';
return 0;

The
0 1
The
100

contents of the first vector are:


2 3 4 5 6 7 8 9
contents of the second vector are:
101 102 103 104 105 106 107 108 109

i
The result of the multiplication held in the third vector is:
0 101 204 309 416 525 636 749 864 981

5 - 1 3 M u l t i p l y .
s t d : : t r a n s f o r m ()
.
v e c M u l t i p l i c a n d , v e c M u l t i p l i e r v e c R e s u l t s t d : : v e c t o r .
, s t d : : t r a n s f o r m () 3 5 -3 9
v e c M u l t i p l i c a n d
v e c M u l t i p l i e r v e c R e s u l t .
C M u l t i p l e : : o p e r a t o r ( ) ,
.
o p e r a t o r () v e c R e s u l t .
,
STL.

495


, b o o l,
.
STL, s t d : : s o r t (). 21.6 ,
.
, .
21.6. , _______
0:
1:
2:
3:
4:
5:
6:
7:

#include <algorithm>
#include <string>
using namespace std;
class CompareStringNoCase
{
public:
bool operator () (const strings strl, const strings str2) const

8:

9:

string strlLowerCase;

10:

11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25: };

//
strlLowerCase.resize (strl.size

());

//
transform (strl.begin (), strl.end ,
strlLowerCase.begin (), tolower);
string str2LowerCase;
str2LowerCase.resize (str2.size ());
transform (str2.begin (), str2.end (),
str2LowerCase.begin (), tolower);
return

(strlLowerCase < str2LowerCase);

, o p e r a t o r ( ) , , s t d : : t r a n s f o r m ( ) ,
15 20, o p e r a t o r <
.
s t d : : s o r t ()
, ,
21.7.
21.7. CompareStringNoCase

_______________________________
0: // CompareStringNoCase 21.6
1: #include <vector>

496
2

21.
#include <iostream>

3
4
5
6
7
8
9
10
11

template <typename T>


void DisplayContents (const T& Input)

{
for(auto
;
;
cout

iElement = Input.cbegin() // auto, cbegin cend: C++11


iElement != Input.cend ()
++ iElement )
*iElement endl;

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

int main

//
vector <string> vecNames;
//
vecNames.push_back ("jim");
vecNames,push_back ("Jack");
vecNames.push_back ("Sam");
vecNames.push_back ("Anna");
cout "The names in vector in order of insertion: " << endl;
DisplayContents(vecNames);
cout << "Names after sorting using default std::less<>:
endl;
sort(vecNames.begin(), vecNames.e n d ());
DisplayContents(vecNames);

28
29
30
31
32
33
34
35
36

()

"

cout "Names after sorting using predicate that ignores case:"


<< endl;
sort(vecNames.begin(), vecNames.e n d (), CompareStringNoCase());
DisplayContents(vecNames);
return 0;

The names in vector in order of insertion:


jim
Jack
Sam
Anna
Names after sorting using default std::less<>:
Anna
Jack
Sam
jim
Names after sorting using predicate that ignores case:
Anna
Jack
jim
Sam

497

.
. , 28
le s s < T > , ,
j im J a c k ,
s t r i n g : : o p e r a t o r s
C o m p a r e s t in g N o C a s e o 32 ( 21.6),
, j im J a c k , .
STL. ,
s t d : : u n i q u e ( ) , ,
s t d : : s o r t ( ) , , s t d : : s t a b l e s o r t ( ) ,
, s t d : : t r a n s f o r m ( ) ,
,
STL, .

( ).
, , ,
, .
,
, ,
.


.
?
.

, rem ove_if () ?
,
.

?
.


?
. .
, .


, ,
. ,

498

21.

, .
,
.


1. , b o o l?
2. ,
b o o l? ?
3. (function object)?

1. , s t d : : f o r _ e a c h ()
d o u b le .
2. , .
3. , .

22

-
++11
- (lambda expressions)
.
++11.
.

-.

- .

-,
.

500

22. - ++11

-
- ( )
( ) o p e r a t o r ( ) . , 21,
. - ,
, , 21.1:
// ,
template <typename elementType>
struct DisplayElement
{
void operator () (const elementType& element) const
{
cout element ' ';


, s t d : : f o r ^ e a c h ():
//
for_each ( veclntegers.begin ()
//
, veclntegers.end ()
//
, DisplayElement <int> () ); //

- , ,
:
// , -
for_each ( veclntegers.begin () //
, veclntegers.end ()
//
, [](int& Element) {cout element '
} );
// -

- , :
[](int Element)

{cout

element

'

,
D is p l a y E l e m e n t < i n t > :
struct NoName
{
void operator () (const int& element) const
{
cout << element ' ';

-
- ( [ ]).
, , , - .

501

, ,
o p e r a t o r ( ) ,
- .

-

- o p e r a t o r ( ) , ,
:
[](Type paramName)

{ // -;

, :
[](Types paramName)

{ // -;

22.1 -
(STL)
f o r _ e a c h ().

22.1. for_each () ,
-, ______________________
0:
1:
2:
3:
4:
5:
6:
7:

#include
#include
#include
#include

using namespace std;


int main ()

8: {
9:

<algorithm>
<iostream>
<vector>
<list>

vector <int> veclntegers;

10:

11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27
28

for (int nCount = 0; nCount < 10; ++ nCount)


veclntegers.push_back (nCount);
list <char> listChars;
for (char nChar = 'a'; nChar < 'k'; ++nChar)
listChars.push_back (nChar);
cout

"Displaying vector of integers using a lambda: "

endl;

//
for_each ( veclntegers.begin () //
, veclntegers.end ()
//
, [](int& element) {cout element ' '; } );
//
cout endl endl;
cout "Displaying list of characters using a lambda: "
//

endl;

502

22. - ++11
for each { listChars.begin () / /
, listChars.end ()
/ /
, [ ] (char& element) {cout element
/ /

29
30
31
32
33
34
35
36

cout

endl;

return 0;

Displaying vector of integers using a lambda:


0 1 2 3 4 5 6 7 8 9
Displaying list of characters using a lambda:
a b c d e f g h i j

- 23 31. ,
,
. i n t ,
,
c h a r ,
c h a r , s t d : : l i s t .

22.1 21.1.
- - 21.1,
DisplayElement<T>.
, , -
, C++ .

-

.
, b o o l ( t r u e f a l s e ) . -
. , -
t r u e :
[](int& Num) {return {(Num % 2) == 0); }

, b o o l.

503

- , ,
, s t d : : f i n d _ i f ( ) , .
22.2.
2 2 .2 . , std:;find if ()___________________________

0:
1:
2:
3:
4:
5
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:

#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
: int main ()
{

19:
20:
21: }

vector<int> vecNums;
vecNums.push_back(25);
vecNums.push_back(101);
vecNums.push_back(2011);
vecNums.push_back(-50);
auto iEvenNum = find_if(vecNums.cbegin()
, vecNums.cend()
//
, [](const int& Num){return ((Num % 2) == 0); } );
if (iEvenNum != vecNums.cend())
cout "Even number in collection is: "
endl;

*iEvenNum

return 0;

Even number in collection is: -50

- , , 15.
f i n d _ i f () .
t r u e , f i n d _ i f ()
. (- )
t r u e , f i n d _ i f () (..
2 ).

22.2 -
, const .
,
.

504

22. - ++11

-
[. . . ]
22.2 , t r u e ,
2, .. .
, t r u e ,
?
:
i n t D iv is o r = 2 ;

/ /

auto iElement = f i n d _ i f ( begin o f a range


, end o f a range
, [ D i v i s o r ] ( i n t d i v i d e n d ) {return (dividend % D iv iso r ) == 0; } );
(state variable)
( [ . . . ] ) (capture list) - .

- - 16
21.3, i s M u l t i p l e o .
,
++11!

22.3
,
.
22.3. - ,
_____________________________________

0:
1:
2:
3:
4:
5:

# in clu d e <algorithm>
# in clu d e <vector>
# in clu d e <iostream>
u sin g namespace std ;

6:

i n t main ()

7:
8:
9:
10:
11:

/ / 25 31
fo r ( in t nCount = 25; nCount < 32; ++ nCount)

12:

13:
14:
15:
16:
17:
18:
19
20

v e c t o r < in t> v e c l n t e g e r s ;
cout "The v e c t o r c o n t a in s the f o llo w in g sample v a lu e s : ";

v e c ln te g e r s.p u s h _ b a c k (nCount);
cout nCount ';
}
cout endl "Enter d i v i s o r
i n t D iv is o r = 2;
c in >> D iv iso r ;

(> 0): ";

/ / ,

-
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33: }

505

vector <int>::iterator iElement;


iElement = find_if ( veclntegers.begin ()
, veclntegers.end ()
, [Divisor](int dividend){return (dividend % Divisor) == 0; } );
if(iElement != veclntegers.end ())
{
cout "First element in vector divisible by " << Divisor;
cout << ": " *iElement << endl;
}
return

0;

The vector contains the following sample values: 25 26 27 28 29 30 31


Enter divisor (> 0): 4
First element in vector divisible by 4: 28

- , ,
24. D i v i s o r
I s M u l t i p l e : : D i v i s o r , 21.3. ,
, ++11.
, -
.

22.3 - 21.4,
. C++11 16 !


-
-
, ,
[ . . . ] :
[StateVarl, StateVar2](& param)

{ // ; }

,
m u ta b le :
[StateVarl, StateVar2](& param) mutable { // ; }

, [ ]
, .

506

22. - ++11

,
, :
[ S S ta t e V a r l,

& S ta t e V a r 2 ] (& param)

{ / / ; }

- ,
:
[S tateV arl,

S tate V ar2 ](T y p el& v a r l ,

Type2& v ar2 )

{ //


, - > :
[ S t a t e l , S t a t e 2 ] ( T y p e l v a r l , Type2 var2) -> ReturnType
{ r e t u r n ( / / ); }
, {} ,
( ;) , :
[ S t a t e l , S t a t e 2 ] ( T y p e l v a r l , Type2 var2) -> ReturnType
{ S ta te m e n t 1; S ta te m e n t 2; r e t u r n ( / / );

, - ,
.
22.5 -,
.

, - ,
, :
te m p la te c ty p e n a m e T ypel, typename 2>
s t r u c t IsNowTooLong
{
/ /
Typel v a r l ;
Type2 v a r 2 ;
/ /
IsNowTooLong(const Typel& i n i , Type2& i n 2 ) : v a r l ( i n l ) , v a r 2 ( i n 2 )
/ /
ReturnType o p e r a t o r ()
{
S ta te m e n t 1;
S ta te m e n t 2;
r e t u r n (v a lu e o r e x p r e s s i o n ) ;
}

{};

507

-

( ) .
- :
[...](Typel& paramlName, 2& param2Name)

{ // ; }

22.4 -,
. s t d : : t r a n s f o r m ()
.
22.4. - ,
_____________

0
1
2

#include <vector>
#include <iostream>
#include <algorithm>

3
4
5

int main ()

{
using namespace std;

7
8

9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36

// 10
vector <int> vecMultiplicand, vecMultiplier;
// 0 9
for (int nCountl = 0; nCountl < 10; ++ nCountl)
vecMultiplicand.push_back (nCountl);
// 100 109
for (int nCount2 = 100; nCount2 < 110; ++ nCount2)
vecMultiplier,push_back (nCount2);
//
vector <int> vecResult;
//
vecResult.resize (10);
transform ( vecMultiplicand.begin (), //
vecMultiplicand.end (),
//
vecMultiplier.begin (),
//
vecResult.begin (), // ,
[](int a, int b) {return a * b; } ); //
cout "The contents of the first vector are: " endl;
for (size_t nlndexl = 0; nlndexl < vecMultiplicand.size ();
++ nlndexl)
cout vecMultiplicand [nlndexl] ' ';
cout endl;
cout

"The contents of the second vector are: "

endl;

508
37:
38
39
40
41
42
43
44
45
46
47: }

22. - ++11
for (size_t nlndex2 = 0; nlndex2 < vecMultiplier.size ();
++nlndex5)
cout vecMultiplier [nlndex2] '
cout endl endl;
cout "The result of the multiplication is: " endl;
for (size_t nlndex = 0; nlndex < vecResult.size (); ++ nlndex)
cout vecResult [nlndex] ' ';
cout endl;
return 0;

The
0 1
The
100

contents of the first vector are:


2 3 4 5 6 7 8 9
contents of the second vector are:
101 102 103 104 105 106 107 108 109

The result of the multiplication is:


0 101 204 309 416 525 636 749 864 981

- 29
s t d : : t r a n s f o r m ().
, .
. - ,

. s t d : : t r a n s f o r m ()
v e c R e s u l t .
.
22.4 - Mult i p l y o 21.5.

-

, t r u e f a l s e ,
.
, s t d : : s o r t ( ) ,
, , .
:
[...](1& paramlName, 2& param2Name)
; }

{ // ,

-
22.5 - , .

22.5. -
std::sort (),

0: #include <algorithm>
1: #include <string>
2 : #include <vector>
3: linclude <iostream>
4: using namespace std;
5:
6: template <typename T>
7: void DisplayContents (const T& Input)
8: {

9:
10:

11:

12:
13: }
14:
15: int
16: {
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:

for(auto
;
;
cout

iElement = Input.cbegin() // auto, cbegin cend: C++11


iElement != Input.cend ()
++ iElement )
*iElement endl;

main ()
// ^
vector <string> vecNames;
//
vecNames.push_back ("jim");
vecNames.push_back ("Jack");
vecNames.push_back ("Sam");
vecNames.push_back ("Anna");
cout "The names in vector in order of insertion: "
DisplayContents(vecNames);

endl;

cout "Names after sorting using default std::less<>: "


endl;
sort(vecNames.begin(), vecNames.end());
DisplayContents(vecNames);
cout "Names after sorting using predicate that ignores case:"
endl;
sort(vecNames.begin(), vecNames.end(),
[](const strings strl, const strings str2) -> bool
//

{
string strlLowerCase;
//
strlLowerCase.resize (strl.size ());
//
transform(strl.begin(), strl.end(),
strlLowerCase.begin(), tolower);
string str2LowerCase;
str2LowerCase.resize (str2.size ());
transform (str2.begin (), str2.end (),
str2LowerCase.begin (),
tolower);

509

510
49:
50:
51:
52:
53:
54:
55:
56: }

22. - ++11

return (strlLowerCase < str2LowerCase);


} //
); //
DisplayContents(vecNames);
return 0;

The names in vector in order of insertion:


jim
Jack
Sam
Anna
Names after sorting using default std::less<>:
Anna
Jack
Sam
jim
Names after sorting using predicate that ignores case:
Anna
Jack
jim
Sam

- , 3 5 -5 1 ,
s t d : : s o r t ( ) , 34
52! , -
( b o o l) ,
35. , j im
J a c k ,
( 30), j im Sam
s t r i n g : : o p e r a t o r ^ , ,
- ( 3 4 -5 2 ), j im J a c k ,
. ,
- , .

- 22.5 -
CompareStringNoCase 21.6,
21.7.
, ,

std::sort (), , ,
.
, ,
.

511

, -
( [ ] )

, - -

operator ()

([statel, state2*,.])


-
[] (const & value) { II ; }

, ,
,
[], .

mutable

'
.......
: . :! '

:'

'
'

<
:

"

." .

' '


, -

{)
-
,
,


C++11
-. , ,
, , .
STL,
f i n d (), s o r t () tr a n s f o r m (). C++
, .

, ( 22.5),
,
.

, ?

:
[Varl, Var2, ... N] (& Paraml, ... ) { ...expression ;}

V a r l V a r2 ( ).
, :
[&Varl, &V2, ... &N](& Paraml, ... ) { ...expression ;}

, ,
, .

512

22. - ++11

:
[Varl, Var2, ... N] (& Paraml, ... ) { ...expression ;}

, :
[=](& Paraml, ... ) { ...expression ;}


, ,
. ,
, .
,
.


1. - ?
2. - ?
3. , ?

1. ,
.
2. - , , f o r _
e a c h ( ) ,
, .

23

STL
(STL)
,
<algorithm> .
.

STL
.

, , ,
STL.

514

23. STL

STL
, ,
, .
STL ,
.
STL, < a l g o r it h m > .

,
, ,
. , swap (),
. swap (),
() .

STL
STL : .


, , ,
(non-m utating algorithm ).
. 23.1.
23.1.

count

count if

search


(.. ==)

search n

find

find if

find end

STL

515

. 23.1

find first_of


( )
,

adjacent_find

equal

mismatch

lexicographical
compare

, ,


(m utating algorithm )
, .
, STL, . 23.2.

23.2.

fill

fill_n

generate

generate n

for each

.
,
for_each ()

transform

copy

copy backward

remove

516

23. STL
. 23.2

remove if

remove copy

remove copy if

unique

unique copy

replace

,
,

replace if

,
,

sort

,
, .

stable sort

sort (),

partial sort

partial sort copy

partition

:
,
.

stable partition

,
partition (),

binary_search

lower bound

, ,


upper bound

,
,

STL

517

STL
STL, . 23.1 23.2,
.
.


, , f i n d () f i n d i f ()
STL ,
. f i n d ()
:
auto iElementFound = find ( veclntegers.cbegin () //
, veclntegers.cend ()
//
, NumToFind );
//
//
if ( iElementFound != veclntegers.cend ())
cout "Result: Value found!" endl;

f i n d _ i f () f i n d (),
( , t r u e f a l s e ) .
auto iEvenNumber = find_if ( veclntegers.cbegin () //
, veclntegers.cend ()
//
, [](int element) { return (element % 2) == 0; } );
if (iEvenNumber != veclntegers.cend ())
cout "Result: Value found!" endl;

, ,
e n d () c e n d () ,
. , .
23.1 f i n d ( )
f i n d i f () .
2 3 .1 . find()
find_if ()
- ______________________________________

0:
1:
2:
3:
4
5:
6:
7:

#include <iostream>
#include <algorithm>
#include <vector>
: int main ()
{
using namespace std;
vector<int> veclntegers;

8:

9:
10:
11:
12:

// -9 9
for (int SampleValue = -9;SampleValue
< 10; ++ SampleValue)
veclntegers.push_back (SampleValue);

518
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:

23. STL
cout "Enter number to find in collection: ";
int NumToFind = 0;
cin NumToFind;
auto iElementFound = find ( veclntegers.cbegin () //
//
, veclntegers.cend ()
//
//
, NumToFind );
//
//
if ( iElementFound != veclntegers.cend ())
cout "Result: Value " *iElementFound " found!"
endl;
else
cout "Result: No element contains value " NumToFind
endl;
cout

"Finding the first even number using find_if: "

endl;

auto iEvenNumber = find_if ( veclntegers.cbegin () //


//
, veclntegers.cend ()
//
//
, [](int element) { return (element % 2) == 0; } );

30:
31:
32:
33:
34:
35:

if
{

36:
37:
38:
39:
40:
41: }

(iEvenNumber != veclntegers.cend ())


cout

cout
cout

"Number '" *iEvenNumber


"' found at position [";
distance (veclntegers.cbegin (), iEvenNumber);
"]" endl;

}
return 0;

Enter number to find in collection: 7


Result: Value 7 found!
Finding the first even number using find_if:
Number '-8' found at position [1]
:
Enter number to find in collection: 2011
Result: No element contains value 2011
Finding the first even number using find_if:
Number '-8' found at position [1]

m a in () ,
- 9 9. f i n d () 17 -1 9

STL

519

. f i n d _ i f ()
2 9 -3 1 . 31
, - . -
t r u e , 2.

23.1 ,
find() find_if ().
, find()
.

17.5 (. 17,
STL) std::distance ()
( 21).


s t d : : c o u n t () c o u n t _ i f ()
. s t d : : f i n d () ,
(
o p e r a to r = = ) :
size_t nNumZeroes = count (veclntegers.begin (),veclntegers.end 0,0);
cout "Number of instances of 'O': " nNumZeroes endl endl;

s t d : : c o u n t _ i f () ,
, (
- ):
// :
template <typename elementType>
bool IsEven (const elementType& number)

{
return ((number % 2) == 0); // true,

}
// count_if IsEven:
size_t nNumEvenElements = count_if (veclntegers.begin (),
veclntegers.end (), IsEven <int> );
cout "Number of even elements: " nNumEvenElements endl;

23.2.
2 3 .2 . std: : count ()
count_if ()
, ______________________________

0: #include <algorithm>
1: #include <vector>
2: #include <iostream>
3:

520
4:
5:
6
7
8
Q
10
11
12
13
14
15
16

23. STL
// *_if
template <typename elementType>
bool IsEven (const elementType& number)
/
return ((number % 2) == 0); // true,
s\
int main ()
{
using namespace std;
vector <int> veclntegers;
cout "Populating a vector<int> with values from -9 to 9"
endl;
for (int nNum = -9; nNum < 10; ++ nNum)
veclntegers.push_back (nNum);

17
18
19
20
21

// count 'O'
size t nNumZeroes = count (veclntegers.begin (),
veclntegers.end 0,0);
cout "Number of instances of 'O': " nNumZeroes endl
endl;

22:
23
24
25
26
27
28
29
30
31
32
33

// count if IsEven:
size_t nNumEvenElements = count_if (veclntegers.begin () /.
veclntegers.end (),
IsEven <int> );
cout
cout
cout

"Number of even elements: " nNumEvenElements


"Number of odd elements: ";
veclntegers.size () - nNumEvenElements endl;

endl;

return 0;
}

Populating a vector<int> with values from -9 to 9


Number of instances of 'O': 1
Number of even elements: 9
Number of odd elements: 10

21 c o u n t () 0
v e c t o r < i n t > . 25 c o u n t i f ()
. ,
I s E v e n ( ) , 6 -9 .

c o u n t _ i f ()
, s i z e ().

STL

521

23.2 count_if () IsEv


en (), 23.1 -,
isEven () find_if ( ) .
- , ,
, IsEven ()
find_if (), count_if ,
.


23.1 .
.
s e a r c h () s e a r c h _ n ( ). s e a r c h ()
:
auto iRange = search ( veclntegers.begin ()
, veclntegers.end ()

//
//
//
, listlntegers.begin () //
//
, listlntegers.end () ); //
//

s e a r c h _ n ()
, :
auto iPartialRange = search_n ( veclntegers.begin () //
, veclntegers.end ()
//
,3
//
, 9 ); //


, e n d ( ).
23.3 s e a r c h () s e a r c h n ().
2 3 .3 .
search () search n ()_________________________________________________

0:
1:
2:
3:
4:
5:
6:
7:

template ctypename T>


void DisplayContents (const T& Input)

8:

9:
10:
11:
12:
13:

#include <algorithm>
#include <vector>
#include <list>
#include <iostream>
using namespace std;

for(auto iElement = Input.cbegin() // auto, cbegin cend: C++11


; iElement != Input.cend()
; ++ iElement )
cout *iElement '

522

23. STL

14:
cout endl;
15:
16:
17: int main ()
18: {
19:
// ( ,
// -9 9)
20:
vector <int> veclntegers;
21:
for (int nNum = -9; nNum < 10; ++ nNum)
22:
veclntegers.push_back (nNum);
23:
24:
//
veclntegers.push_back (9);
25:
26:
veclntegers.push_back (9);
27:
28:
// ( -4 4)
29:
list <int> listlntegers;
for (int nNum = -4; nNum < 5 ; ++ nNum)
30:
31:
listlntegers.push_back (nNum);
32:
33:
cout "The contents of the sample vector are: " endl;
34:
DisplayContents (veclntegers);
35:
36:
cout "The contents of the sample list are: " endl;
37:
DisplayContents (listlntegers);
38:
39:
cout "search() for the contents of list in vector:" endl;
40:
auto iRange = search ( veclntegers.begin ()
//
41:
, veclntegers.end ()
//
//
42:
, listlntegers.begin () //
//
43:
, listlntegers.end () ); //
//
44:
45:
//
46:
if (iRange != veclntegers.end )
47:
{
48:
cout "Sequence in list found in vector at position: ";
cout distance (veclntegers.begin (), iRange) endl;
49:
50:
}
51:
cout "Searching {9, 9, 9} in vector using search_n(): "
52:
endl;
auto iPartialRange = search_n ( veclntegers.begin () //
53:
//
, veclntegers.end () //
54:
,3
//
55:
, 9 ); //
56:
57:
if (iPartialRange != veclntegers.end ())
58:
59:
{
60:
cout "Sequence {9, 9, 9} found in vector at position: ";
cout distance (veclntegers.begin (), iPartialRange)
61:

STL

62:
63:
64:
65: }

523

endl;

}
return 0;

The contents of the sample vector are:


- 9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 0 1 2 3 4 5 6 7 8 9 9 9
The contents of the sample list are:
- 4 - 3 - 2 - 1 0 1 2 3 4
search() for the contents of list in vector:
Sequence in list found irt vector at position: 5
Searching {9, 9, 9} in vector using search_n():

, ,
. s e a r c h ()
, 40.
,
, b e g i n () e n d () .
,
. , ,
,
, . s e a r c h _ n ()
53 {9, 9, 9} .



f i l l () f i l l _ n () STL
. f i l l ()
, , :
vector <int> veclntegers (3) ;
// 9
fill (veclntegers.begin (), veclntegers.end (), 9);

, f i l l _ n ()
. , :
fill_n (veclntegers.begin () + 3, /**/ 3, /**/ -9);

23.4 ,
v e c t o r < i n t > .

524

23. STL

23.4. f i l l f i l l _ n ( )
________________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include <algorithm>
#include <vector>
#include <iostream>
int main ()
{
using namespace std;
// 3
vector <int> veclntegers (3);

10:

11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:

// 9
fill (veclntegers.begin (), veclntegers.end (), 9);
// 6
veclntegers.resize (6);
// -9, 3
fill_n (veclntegers.begin () + 3, 3, -9);
cout "Contents of the vector are: " endl;
for(size_t nlndex = 0; nlndex < veclntegers.size (); ++ nlndex)

22:

23:
24:
25:
26:
27:
28: }

cout
cout

"Element [" nlndex "] = ";


veclntegers [nlndex] endl;

}
return

0;

Contents of
Element [0]
Element [1]
Element [2]
Element [3]
Element [4]
Element [5]

the vector are:


=9
=9
=9
= -9
= -9
= -9

23.4 f i l l () f i l l _ n ()
, 12 18.
r e s i z e ()
. , ,
. f i l l () , f i l l _ n ()
.

STL

525

s t d : :generate ()
,

, f i l l () f i l l n ()
, STL, g e n e r a t e () g e n e r a t e _ n ( ),
, .
g e n e r a t e ()
-:
generate ( veclntegers.begin (), veclntegers.end () //
, rand ); // -

g e n e r a t e _ n () g e n e r a t e () ,
, ,
:
generate_n (listlntegers.begin (), 5, rand);

,
, , ,
23.5.
2 3 .5 . generate () generate_n ()
______________________________________

0:
1:
2:
3:
4:
5:
6:
7:

#include
#include
#include
#include

<algorithm>
<vector>
<list>
<iostream>

int main ()
{

using namespace std;

8:

9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:

vector <int> veclntegers (10);


generate ( veclntegers.begin (),veclntegers.end () //
, rand ); // -
cout "Elements in the vector of size " veclntegers.size ();
cout " assigned by 'generate' are: " endl "{";
for (size_t nCount = 0; nCount < veclntegers.size (); ++ nCount)
cout veclntegers [nCount] " ";
cout

"}"

endl

endl;

list <int> listlntegers (10);


generate_n (listlntegers.begin (),

5, rand);

cout "Elements in the list of size: " listlntegers.size ();


cout " assigned by 'generate_n' are: " endl "{";
list <int>::const_iterator iElementLocator;
for ( iElementLocator = listlntegers.begin ()

526
27:
28:
29:
30:
31:
32:
33:
34: }

23. STL
; iElementLocator != listlntegers.end ()
; ++ iElementLocator )
cout *iElementLocator ' ';
cout

"}"

endl;

return 0;

Elements in the vector of size 10 assigned by 'generate' are:


{41 18467 6334 26500 19169 15724 11478 29358 26962 24464 }
Elements in the list of size: 10 assigned by 'generate_n' are:
{5705 28145 23281 16827 9961 0 0 0 0 0 }

23.5 g e n e r a t e ()
, r a n d ( ). ,
g e n e r a t e () , ,
r a n d () . g e n e r a t e _ n ( ) , ,
. r a n d ()
, c o u n t .
.
.


for_each()
f o r _ e a c h ()
. :
unaryFunctionObjectType mReturn = for_each ( start_of_range
, end_of_range
, unaryFunctionObject );

- ,
. , f o r e a c h ()
( ),
. ,

, ,
f o r _ e a c h (). 23.6,
,
.

STL
23.6.
for each ()______________________________________
:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:

#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
// , for_each
template ctypename elementType>
struct DisplayElementKeepCount
{
int Count;
//
DisplayElementKeepCount (): Count (0) {}
void operator () (const elementType& element)
{
++ Count;
cout element ' ';
}
};

int main ()
{

vector <int> veclntegers;


for (int nCount = 0; nCount < 10; ++ nCount)
veclntegers.push_back (nCount);
cout

"Displaying the vector of integers: "

endl;

//
DisplayElementKeepCount<int> Functor =
for_each ( veclntegers.begin () //
, veclntegers.end ()
//
, DisplayElementKeepCount<int> () );//
cout

endl;

// ,
// for_each!
cout "'" Functor.Count "' elements were displayed"
endl;
string Sample ("for_each and strings!");
cout "String: " Sample ", length: "
endl;
cout "String displayed using lambda:"
int NumChars = 0;
for_each ( Sample.begin()
, Sample.end ()
, [&NumChars](char c) { cout c

Sample.length()

endl;

' '; ++NumChars; } );

527

528
48:
49:
50:
51:
52:
53: }

23. STL

cout endl;
cout
"

NumChars

characters were displayed"

endl;

return 0;

Displaying the vector of integers:


0 1 2 3 4 5 6 7 8 9
'10' elements were displayed
String: for_each and strings!, length: 21
String displayed using lambda:
f o r _ e a c h a n d s t r i n g s !
'21' characters were displayed

f o r _ e a c h ( ),
R e s u l t , ,
, . : ,
v e c l n t e g e r s , , S a m p le ,
s t d : : s t r i n g . f o r _ e a c h () 32
45 . D i s p l a y E l e m e n tK e e p C o u n t, - .
f o r e a c h () o p e r a t o r ( ) ,
.
f o r e a c h () , , C o u n t
. ( )
, ,
. f o r _ e a c h () 45 s t d : : s t r i n g
, 32, -
.


s t d : : transform()
s t d : : f o r _ e a c h () s t d : : t r a n s f o r m () ,
.
s t d : : t r a n s f o r m () .

t o u p p e r () t o l o w e r ():
string Sample ("THIS is a TEst string!");
transform ( Sample.begin ()
//
, Sample.end ()
//
, strLowerCaseCopy.begin () //
, tolower );
//

STL

529

, t r a n s f o r m ()
, :
//
//
transform ( veclntegersl.begin ()
//
, veclntegersl.end ()
//
, veclntegers2.begin ()
//
, dqResultAddition.begin
//
//
, plus <int> () );


1
1
2


plus

t r a n s f o r m ()
,
f o r e a c h ( ), .
s t d : : t r a n s f o r m () 23.7.
23.7. std: : transform ()

______________________________________
0:
1:
2:
3:
4:
5:
6:
7:

#include
#include
#include
#include
#include
#include

8:

9:

<algorithm>
<string>
<vector>
<deque>
<iostream>
<functional>

int main ()
using namespace std;

10:

11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

string Sample ("THIS is a TEststring!");


cout "The sample string is: " Sample
string strLowerCaseCopy;
strLowerCaseCopy.resize (Sample.size

endl;

());

transform ( Sample.begin ()
//
, Sample.end ()
//
, strLowerCaseCopy.begin () //
//
, tolower );
//

21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:

cout

cout

"Result of 'transform' on the string with 'tolower':"


endl;
"\"" strLowerCaseCopy
endl endl;

// ...
vector <int>veclntegersl,
veclntegers2;
for (int nNum = 0; nNum < 10; ++ nNum)
{
veclntegersl.push_back (nNum);
veclntegers2.push_back (10 - nNum);
}
//

530
34:
35:
36:
37:
38:
39:

23. STL
deque <int> dqResultAddition (veclntegersl.size ());
transform ( veclntegersl.begin () // 1
, veclntegersl.end ()
// 1
, veclntegers2.begin () // 2
, dqResultAddition.begin () //
//
, plus <int> () );
//

40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53: }

cout "Result of 'transform' using binary function 'plus': "


endl;
cout e n d l "Index Vectorl + Vector2 = Result (in Deque)"
endl;
for(size_t nlndex = 0; nlndex < veclntegersl.size (); ++ nlndex)
{
cout nlndex " \t " veclntegersl [nlndex] "\t+
cout veclntegers2 [nlndex] " \t =
cout

dqResultAddition [nlndex]

endl;

}
return

0;

The sample string is: THIS is a TEst string!


Result of using 'transform' with unary function 'tolower' on the string:
"this is a test string!"
Result of 'transform' using binary function 'plus':
Index Vectorl + Vector2> _ Resi
= 10
+ 10
0
0
+ 9
= 10
1
1
+ 8
= 10
2
2
= 10
+ 7
3
3
= 10
+ 6
4
4
+ 5
= 10
5
5
+ 4
= 10
6
6
= 10
+ 3
7
7
= 10
+ 2
8
8
= 10
+ 1
9
9

s t d : : t r a n s f o r m (): ,
t o l o w e r ( ) ,
20, ,
p l u s ( ) , 40.
. t o l o w e r ()
t o u p p e r ( ) , .
s t d : : t r a n s f o r m ( ) , 3 6 -4 0 , ,

STL

531

( ),
p l u s () STL ( < f u n c t i o n a l > )
. s t d : : t r a n s f o r m () ,
p l u s ( ),
, s t d : d e q u e .
, .
,
STL; t r a n s f o r m ( ) , ,
,
. , ,
, ,
( t r a n s f o r m ()).


STL : ( ) , _
i f () c o p y _ b a c k w a rd (). ()
:
auto iLastPos = copy ( listlntegers.begin ()

//
//
, listlntegers.end ()
//
//
, veclntegers.begin () ); //
//

c o p y _ i f () ,
t r u e :
//
copy_if ( listlntegers.begin(), listlntegers.end()
, iLastPos
, [](int element){return ((element % 2) == 1);});

C++11 copy_if ()
std.
C++ , .

c o p y b a c k w a r d ()
:
copy_backward ( listlntegers.begin ()
, listlntegers.end ()
, veclntegers.end () );

re m o v e ( ) , , ,
:
// '0' ,
// erase ()
auto iNewEnd = remove (veclntegers.begin (), veclntegers.end (), 0);
veclntegers.erase (iNewEnd, veclntegers.end ());

532

23- STL

re m o v e i f ()
, t r u e :
// , remove_if()
iNewEnd = remove_if (veclntegers.begin (), veclntegers.end (),
[](int element) {return ((element % 2) == 1);} ); //
veclntegers.erase (iNewEnd , veclntegers.end );

//
//

23.8.

23.8. (), copy_if (), remove () remove_if ()


,
0: #include <algorithm>
1: #include <vector>
2 : #include <list>
3: #include <iostream>
4: using namespace std;
5:
6 : template ctypename T>
7: void DisplayContents(const T& Input)
8:

9:
10:

11:
12:
13:
14:
15: }
16: int
17: {
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:

for ( auto iElement = Input.cbegin() // auto, cbegin: C++11


; iElement != Input.cend()
// cend(): C++11
; ++ iElement)
cout *iElement *
cout

Input.size()

endl;

main ()
list <int> listlntegers;
for (int nCount = 0; nCount < 10; ++ nCount)
listlntegers.push_back (nCount);
cout "Source (list) contains:"
DisplayContents(listlntegers);

endl;

// ,
// ,
vector <int> veclntegers (listlntegers.size () * 2);
auto iLastPos = copy ( listlntegers.begin ()

//
//
, listlntegers.end ()
//
//
, veclntegers.begin () ); //
//

29:
30:
31:
32:
33:
34:
35:
36:
37:

"| .Number of elements: "

//
copy_if ( listlntegers.begin(), listlntegers.end()
, iLastPos
, [](int element){return ((element % 2) == 1);});
cout

"Destination (vector) after copy and copy_if:"

endl;

STL
38:
39:
40:

533

DisplayContents(veclntegers);
// '0' ,
// erase ()
auto iNewEnd = remove (veclntegers.begin (),
veclntegers.end (), 0);
veclntegers.erase (iNewEnd, veclntegers.end ());

41:
42:
43:
44:
45:
46:

// , remove_if
iNewEnd = remove_if (veclntegers.begin (), veclntegers.end (),
[](int element) {return ((element % 2) == 1);} );
//

47:
48:

veclntegers.erase (iNewEnd , veclntegers.end ()); //


//

49:
50:
51:
52:
53:
54: }

cout "Destination (vector) after remove, remove_if, erase:"


endl;
DisplayContents(veclntegers);
return 0;

Source (list) contains:


0 1 2 3 4 5 6 7 8 9 | Number of elements: 10
Destination (vector) after copy and copy_if:
0 1 2 3 4 5 6 7 8 9 1 3 5 7 9 0 0 0 0 0 | Number of elements: 20
Destination (vector) after remove, remove_if, erase:
2 4 6 8 1 Number of elements: 4

c o p y () 28,
. c o p y i f () 33,
l i s t l n t e g e r s
v e c l n t e g e r s , , i L a s t P o s ,
( ) . re m o v e () 41.
v e c l n t e g e r s 0. re m o v e _
i f () 45 .

23.8 , remove () remove_if ()


, .
veclntegers .
, ,
, .. .
( ,
), , remove ()
remove_if () erase (),
42 48.

534

23. STL


r e p l a c e () r e p l a c e _ i f () STL
,
. r e p l a c e ()
, (==):
cout "Using 'std::replace' to replace value 5 by 8" endl;
replace (veclntegers.begin (), veclntegers.end (), 5, 8);

r e p l a c e _ i f () ,
t r u e , :
cout "Using 'std::replace_if' to replace even values by -1" endl;
replace_if (veclntegers.begin (), veclntegers.end ()
, [](int element) {return ((element % 2) == 0); }, -1);

23.9.
23.9. replace () replace_if ()
____________________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
template ctypename T>
void DisplayContents(const T& Input)
{
for ( auto iElement = Input.cbegin() // auto, cbegin: ++11
; iElement != Input.cend()
// cend(): C++11
; ++ iElement)
cout *iElement ' ';
cout "| Number of elements: "
}
int main ()
{
vector <int> veclntegers (6);

Input.size()

endl;

// 3 8,
// 3 5
fill (veclntegers.begin (), veclntegers.begin () + 3, 8);
fill_n (veclntegers.begin () + 3, 3, 5);
//
random_shuffle (veclntegers.begin (), veclntegers.end ());
cout "The initial contents of the vector are: "
DisplayContents(veclntegers);

endl;

cout endl "Using 'std::replace' to replace value 5 by 8"


endl;
replace (veclntegers.begin (), veclntegers.end (), 5, 8);

STL

535

31:

32:

cout "Using 'std::replace_if' to replace even values by -I


endl;
replace_if (veclntegers.begin (), veclntegers.end ()
, [](int element) {return ((element % 2) == 0); }, -1);

33:
34:
35:
36:
37:
38:
39:
40: }

cout endl "Contents of the vector aftef replacements:"


endl;
DisplayContents(veclntegers);
return 0;

The initial contents of the vector are:


5 8 5 8 8 5 | Number of elements: 6
Using 'std::replace' to replace value 5 by 8
Using 'std::replace_if' to replace even values by -1
Contents of the vector after replacements:
-1 -1 -1 -1 -1 -1 | Number of elements: 6

v e c l n t e g e r s v e c t o r < i n t > ,
, s t d : : r a n d o m _ s h u f f l e () STL,
24. 30 r e p l a c e ()
5 8. 33 r e p l a c e _ i f ()
- 1 . , ,
- 1 , .

,

(
) . ,
, , , .
s o r t () STL:
sort (veclntegers.begin (), veclntegers.end ()); //

s o r t () s t d : : l e s s o ,
o p e r a t o r c , .
, ,
:
sort (veclntegers.begin (), veclntegers.end (),
[](int lhs, int rsh) {return (lhs > rhs);} ); //

536

23. STL

.
u n i q u e ( ) :
auto iNewEnd = unique (veclntegers.begin (), veclntegers.end ());
veclntegers.erase (iNewEnd, veclntegers.end ()); //

STL b i n a r y _ s e a r c h ( ) ,
:
bool bElementFound = binary_search (veclntegers.begin (),
veclntegers.end (), 2011);
if (bElementFound)
cout "Element found in the vector!"

endl;

23.10 STL, s t d : : s o r t ( ) ,
s t d : : b i n a r y _ s e a r c h ( ) ,
, s t d : : u n i q u e ( ) ,
( ).

23.10. sort (), binary search () unique ()


0
1
2

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;

4
5
6
7

template ctypename T>


void DisplayContents(const T& Input)

{
for ( auto iElement = Input.cbegin() // auto, cbegin: C++11
; iElement != Input.cend()
// cend(): C++11
; ++ iElement)
cout *iElement endl;

9
10
11
12

13
14
15
16
17
18
19
20

}
int main ()

{
vector<string> vecNames;
vecNames.push_back ("John
vecNames.push_back ("Jack
vecNames.push_back ("Sean
vecNames.push_back ("Anna

Doe");
Nicholson");
Penn");
Hoover");

21

22
23
24
25
26
27
28
29
30
31
32

//
vecNames.push_back ("Jack Nicholson");
cout "The initial contents of the vector are:"
DisplayContents(vecNames);

endl;

cout "The sorted vector contains names in the order:"


sort (vecNames.begin (), vecNames.end ());
DisplayContents(vecNames);
cout

"Searching for V'John Doe\" using 'binary_search':"

endl;

STL

537

endl;
bool bElementFound = binary_search (vecNames.begin (),
vecNames.end (),
"John Doe");

33:
34:
35:
36:
37:

if (bElementFound)
cout "Result: \"John Doe\" was found in the vector!"
endl;
else
cout "Element not found " endl;

38:
39:
40:
41:
42:
43:
44:
45:

//
auto iNewEnd = unique (vecNames.begin (), vecNames.end ());
vecNames.erase (iNewEnd, vecNames.end ());

46:
47:
48:
49: }

cout "The contents of the vector after using 'unique':"


endl;
DisplayContents(vecNames);
return 0;

The initial contents of the vector are:


John Doe
Jack Nicholson
Sean Penn
Anna Hoover
Jack Nicholson
The sorted vector contains names in the order:
Anna Hoover
Jack Nicholson
Jack Nicholson
John Doe
Sean Penn
Searching for "John Doe" using 'binary_search':
Result: "John Doe" was found in the vector!
The contents of the vector after using 'unique':
Anna Hoover
Jack Nicholson
John Doe
Sean Penn

vecN am es ( 29), (
33) b i n a r y _ s e a r c h () J o h n Doe.
42 s t d : : u n i q u e ( )
. , u n i q u e ( ) , r e m o v e ( ) ,
. ,
.

538

23. STL

, u n i q u e ()
v e c t o r : : e r a s e ( ), , u n iq u e ( ),
42 43.

, binary_search (),
.
.

stable_sort () , sort ,
. stable_sort ()
.
, ,
.


s t d : : p a r t i t i o n () :
, , , :
bool IsEven (const int& nNumber) //
{
return ((nNumber % 2) == 0);

}
partition (veclntegers.begin(), veclntegers.end(), IsEven);

s t d : : p a r t i t i o n ()
. ,
s t d : : s t a b l e _ p a r t i t i o n ():
stable_partition (veclntegers.begin() , veclntegers.end(), IsEven);

23.11 .
23.11. partition () stablejpartition ()
______________________

0:
1:
2:
3:
4:
5:
6:
7:

#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
bool IsEven (const int& nNumber)
{

return ((nNumber % 2) == 0);

8: }

9:
10: template <typename T>
11: void DisplayContents(const T& Input)
12: {
13:
for ( auto iElement = Input.cbegin() // auto, cbegin: C++11

STL
14:
; iE le m e n t != I n p u t . c e n d ( )
15:
; ++ iE lem ent)
16:
c o u t *iE le m en t '
17:
18:
c o u t "| Number o f e l e m e n ts : "
19: }
20: i n t main ()

21:

539

/ / c e n d ( ) : C++11

I n p u t . s i z e ()

endl;

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41: }

v e c t o r < in t> v e c l n t e g e r s ;
f o r ( i n t nNum = 0; nNum < 10; ++ nNum)
v e c l n t e g e r s . p u s h _ b a c k (nNum);
c o u t "The i n i t i a l c o n t e n t s : "
D isp la y C o n te n ts(v ec ln te g ers);

endl;

v e c t o r < in t> vecCopy ( v e c l n t e g e r s ) ;


c o u t "The e f f e c t o f u s i n g p a r t i t i o n ( ) : " e n d l ;
p a r t i t i o n ( v e c l n t e g e r s . b e g i n ( ), v e c l n t e g e r s . e n d ( ) , I s E v e n ) ;
D isp la y C o n te n ts(v ec ln te g ers);
c o u t "The e f f e c t o f u s i n g s t a b l e _ p a r t i t i o n ( ) : " e n d l ;
s t a b l e _ p a r t i t i o n (vecC opy.begin ( ), vecC opy.end ( ), I s E v e n ) ;
D is p la y C o n te n ts ( v e c C o p y ) ;
r e t u r n 0;

The
0 1
The
0 8
The
0 2

i n i t i a l c o n t e n ts :
2 3 4 5 6 7 8 9 I Number of elem ents: 10
e f f e c t of u sin g p a r t i t i o n ():
2 6 4 5 3 7 1 9 I Number of elem ents: 10
e f f e c t of u sin g s t a b l e _ p a r t i t i o n ():
4 6 8 1 3 5 7 9 | Number of elem ents: 10

, v e c l n t e g e r s ,
.
s t d : : p a r t i t i o n ( ) , 33, s t a b l e _ p a r t i t i o n () 37. v e c l n t e g e r s
v e c C o p y , p a r t i t i o n ( ) ,
s t a b l e j p a r t i t i o n ().
s t a b l e j p a r t i t i o n () p a r t i t i o n () .
s t a b l e j p a r t i t i o n ()
. ,
, , , ,
.

540

23. STL

stable_partition() , partition(),
,
.


,
. STL , lo w e r _ b o u n d () u p p e r _
b o u n d ( ) , :
auto iMinlnsertPos = lower_bound ( listNames.begin(), listNames.endO
, "Brad Pitt" );
// :
auto iMaxInsertPos = upper_bound ( listNames.begin(), listNames.endO
, "Brad Pitt" );

, lo w e r _ b o u n d ( ) u p p e r _ b o u n d ( ) ,
,
.
23.12 lo w e r _ b o u n d ()
.
2 3 .1 2 . lower_bound () upper_bound ()
__________________________________________________

0:
1:
2:
3:
4:
5:
6:
7:

8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:

#include <algorithm>
#include <list>
#include <string>
#include <iostream>
using namespace std;
template ctypename T>
void DisplayContents(const T& Input)
{

for ( auto iElement = Input.cbegin() // auto, cbegin: C++11


; iElement != Input.cend()
// cend(): C++11
; ++ iElement)
cout *iElement endl;
}
int main ()
{
list<string> listNames;
//
listNames.push_back ("John Doe");
listNames.push_back ("Brad Pitt");
listNames.push_back ("Jack Nicholson");
listNames.push_back ("Sean Penn");
listNames.push_back ("Anna Hoover");
cout "The sorted contents of the list are: "
listNames.sort ();

endl;

STL
27:
28:
29:

541

DisplayContents(listNames);
cout
"The lowest index where V'Brad Pitt\" can be inserted is: ";
auto iMinlnsertPos = lower_bound ( listNames.begin (),
listNames.end ()
, "Brad Pitt" );
cout
distance (listNames.begin (), iMinlnsertPos) endl;

30:
31:
32:
33:
34:

cout
"The highest index where V'Brad Pitt\" can be inserted is: ";
auto iMaxInsertPos = upper_bound ( listNames.begin (),
listNames.end (),
"Brad Pitt" );
cout
distance (listNames.begin (), iMaxInsertPos) endl;

35:
36:
37:
38:
39:
40:
41:

cout

42:
43:
44:
45:
46: }

endl;

cout "List after inserting Brad Pitt in sorted order: "


endl;
listNames.insert (iMinlnsertPos, "Brad Pitt");
DisplayContents(listNames);
return 0;

The sorted contents of the list are:


Anna Hoover
Brad Pitt
Jack Nicholson
John Doe
Sean Penn
The lowest index where "Brad Pitt" can be inserted is: 1
The highest index where "Brad Pitt" can be inserted is: 2
List
Anna
Brad
Brad
Jack
John
Sean

after inserting Brad Pitt in sorted order:


Hoover
Pitt
Pitt
Nicholson
Doe
Penn


: (, lo w e r _ b o u n d ( ))
(, u p p e r b o u n d ()).
23.12, " B ra d P i t t " ,
( 20),

542

23. STL

( ).
30 35 . ,
, low er_bound () ( 42),
. ,
, .
, upper_bound (), .

erase ()
re
move , remove_if() unique ()


sort ,
unique ()
.
sort ,

,
unique {)

,
find(), findJLf (),
search() searchjnO,

end ()
sta
blejpartition{), parti
tion () stable_sort(),
sort () ,

, binaryjsearch ()


, stablej*


STL: . ,
.

, s t d : : t r a n s f o r m ( ) ,
, s t d : : s e t ?

, .
. ,
,
, f i n d (),
. , s t d : : tra n s f o rm (),
STL.

543


. s t d : : transform () ?
s t d : : t r a n s f o r m () ,
f i l l () f i l l _ n ( ) .

copy_bac]cward()
?
, . c o p y b a c k w a r d () STL
, ,
.. .
, s t d : : r e v e r s e ().

s t d : : so rt () ?
s t d : : s o r t () ,
. :
,
s t d : : s o r t () . STL
s o r t () - l i s t : : s o r t ( ),
, ,
, .

, lower_bound() upper_
bound(), ?

,
.


, ,
. ,
, .
,
.


1. , .
s t d : : r e m o v e _ if () l i s t : : r e m o v e _ if () ?
2. C o n t a c t l t e m . l i s t : : s o r t ()
?
3. g e n e r a t e () STL g e n e r a t o r () ?
4. s t d : : t r a n s f o r m () s t d : : f o r _ e a c h () ?

544

23. STL

1. ,
.
2. , STL, s t d : : c o p y ( ) ,
,
,
.
3. , ,
. ,
.
, s t d : : s o r t ()
s t d : : s t a b l e s o r t ( ) ?

24

:

(STL)
,
. ,
,
(adaptive container).
.

s t a c k STL.

q u e u e STL.

p r i o r i t y q u eu e STL.

546

24. :



,
, .
,
.

(stack) , ,
(L ast-In-F irst-O ut L IFO ),
. .
.
. ,
, . 24.1.

. 24.1.
s t d : : s t a c k
STL.

s t d : : stack,

# in c lu d e <stack>

(queue) , ,
(F irst-In-F irst-O ut FIF O ),
.
, , .
,
, . 24.2.
s t d : : q u e u e
STL.

stack STL

.
( )

547

( )

. 24.2.

std::queue,

#include <queue>

stack
STL
STL s t a c k ,
< s ta c k > . ,

. s t d : : s t a c k
.


STL s t a c k :
template <
class ,
class = deque<Tnn>
> class stack;

, .
, , ,
.
s t d : id e q u e , s t d : : v e c t o r s t d : : l i s t .
, :
std::stack <int> stacklnts;

- ,
T una, :
std::stack <Tuna> stackTunas;

:
std::stack <double, vector <double> > stackDoublesInVector;

24.1 .
24.1. STL_________________________________
#include <stack>
#include <vector>
int main ()

548
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20: }

24. :
using namespace std;
//
stack <int> stacklnts;
// double
stack <double> stackDoubles;
// double,
stack <double, vector <double> > stackDoublesInVector;
//
stack <int> stacklntsCopy(stacklnts);
return 0;

,
STL. 8 11 s t a c k
i n t d o u b le . 14
, ( v e c t o r ) ,
.
, s t d : : d e q u e . ,
17 , .

- stack
, , d e q u e , l i s t v e c t o r ,
, ,
,
, . . 24.1 - s t a c k
.

24.1. - stack

push

stacklnts.push (25);
pop

stacklnts.pop ();
empty

, ; bool

if (stacklnts.empty ())
DoSomething ();
size

size_t nNumElements = stacklnts.size ();


top

cout

"Element at the top = "

stacklnts.top ();

stack STL

549

, -
, ,
. , ,
, ,
, .


push () pop ()
s t a c k < T > : : p u s h ():
stacklnts.push (25); // 25

to p ():
cout

stacklnts.top()

endl;

, p o p ():
stacklnts.pop (); // pop:

24.2 p u s h ()
p o p ().
2 4 .2 .

0
1

#include <stack>
#include <iostream>

int main ()

4
5
6
7
8
9

{
using namespace std;
stack <int> stacklnts;
// push:
cout "Pushing {25, 10, -1, 5} on stack in that order:"
endl;
stacklnts.push (25);
stacklnts.push (10);
stacklnts.push (-1);
stacklnts.push (5);

10
11
12
13
14
15

cout "Stack contains " stacklnts.size ()


endl;
while (stacklnts.size () != 0)

16
17
18

{
cout "Popping topmost element: " stacklnts.top()
endl;
stacklnts.pop (); // pop:

19
20

21
22
23
24
25
26

" elements"

}
if (stacklnts.empty ()) // true: pop()
cout "Popping all elements empties stack!" endl;
return 0;

550

24. :

Pushing {25, 10, -1, 5} on stack in that order:


Stack contains 4 elements
Popping topmost element: 5
Popping topmost element: -1
Popping topmost element: 10
Popping topmost element: 25
Popping all elements empties stack!

s t a c k l n t s
s t a c k : : p u s h ( ) , 9 -1 3 ,
s t a c k : : ( ). ,
, s t a c k : : t o p ( ) , 18.
s t a c k : : p o p ( ),
19. w h i l e , , p o p ()
, .
, , , ,
.
24.2 - . ,
p u s h _ b a c k () i n s e r t ( ) ,
STL, s t a c k ,
- s t a c k . ,
, . ,
, , .

queue
STL
q u e u e STL
< q u e u e > . ,

. s t d : : q u e u e
!


s t d : : q u e u e :
template <
class ,
class = deque<>
> class queue;

, .
, , ,

queue STL

551

s t d : : q u e u e .
s t d : : l i s t , v e c t o r d e q u e . d e q u e .
:
std::queue <int> qlntegers;

, d o u b l e
s t d : : l i s t ( ),
:
std::queue <double, list <double> > qDoublesInList;

, :
std::queue<int> qCopy(qlntegers);

24.3
s t d : : queue.
2 4 .3 . STL______________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:

#include <queue>
#include <list>
int main ()
{
using namespace std;
//
queue <int> qlntegers;
// double
queue <double> qDoubles;
// double,
queue <double, list <double> > qDoublesInList;
//
queue<int> qCopy(qlntegers);
return 0;
}

, q u e u e
STL, ( 8) d o u b l e
( 11). q D o u b l e s I n L i s t 14
, ,
, s t d : : l i s t .
, ,
s t d : : d e q u e .

552

24. :

- queue
s t d : : q u e u e , s t d : : s t a c k ,
STL, v e c t o r , l i s t d e q u e . q u e u e
- , . . 24.2
- q u e u e , q l n t e g e r s 24.3.

24.2. - std: :queue

push

, ..

qlntegers.push (10);
pop

, ..

qlntegers.pop ();
front

cout
back

cout
empty

"Element at front: "

qlntegers.front ();

, ..

"Element at back: "

qlntegers.back ();

, ; bool

if (qlntegers.empty ())
cout "The queue is empty!";
size

size_t nNumElements = qlntegers.size ();

q u e u e STL , b e g i n () e n d (),
STL,
d e q u e , v e c t o r l i s t , . ,
,
.


push () pop ()
p u s h ():
qlntegers.push (5); //

, , p o p ():
qlntegers.pop (); //

,
f r o n t () b a c k ():
cout
cout

"Element at front: " qlntegers.front() endl;


"Element at back: " qlntegers.back() endl;

, 24.4.

queue STL

553

24.4. ,
0:
#include <queue>
1:
#include <iostream>
2:
3: int main ()
4: {
5:
using namespace std;
6:
queue <int> qlntegers;
7:
8:
cout "Inserting {10, 5, -1, 20} into queue" endl;
9:
qlntegers.push (10);
10:
qlntegers.push (5); //
11:
qlntegers.push (-1);
12:
qlntegers.push (20);
13:
14:
cout "Queue contains " << qlntegers.size () " elements"
endl;
15:'
cout "Element at front: " qlntegers.front () endl;
16:
cout "Element at back: " qlntegers.back() endl;
17:
18:
while (qlntegers.size () != 0)
19:
{
20:
cout "Deleting element: " qlntegers.front () endl;
21:
qlntegers.pop (); //
22:
}
23:
24:
if (qlntegers.empty ()) // true,
//
25:
cout "The queue is now empty!" endl;
26:
27:
return 0;
28: }

Inserting {10, 5, -1, 20} into queue


Queue contains 4 elements
Element at front: 10
Element at back: 20
Deleting element: 10
Deleting element: 5
Deleting element: -1
Deleting element: 20

9 -1 2 q l n t e g e r s
p u s h (). f r o n t () b a c k ()
, 15 16. w h i l e
18-22 ,
p o p () 21. , .
, ,
, , .

554

24. :

p rio rity_ q u eu e
STL
p r i o r i t y _ q u e u e STL
< q u eu e> . (priority queue) ,
( ,
) ,
.


s t d : : p r i o r i t y _ q u e u e :
template <
class ,
class = vector<>,
class = lessctypename ::value_type>
> class priority_queue

,
. , , ,
s t d : : p r i o r i t y _ q u e u e ,

. , p r i o r i t y _ q u e u e
s t d : : l e s s < > , ,
o p e r a t o r s

:
std::priority_queue <int> pqlntegers;

, d o u b le
s t d : : d e q u e , :
priority_queue <int, deque <int>, greater <int> > pqlntegers_lnverse;

, :
std::priority_queue <int> pqCopy(pqlntegers) ;

p r i o r i t y _ q u e u e 24.5.
2 4 .S . priority queue__________________________

0: #include <queue>

1:
2: int main ()
3: {
4:
using namespace std;
5:
6:
// ,
// std::less<> ( )
7:
priority_queue <int> pqlntegers;

priority_queue STL

555

8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

// double
priority_queue <double> pqDoubles;
// ,
// std::greater<>
priority_queue <int, deque <int>,
greater <int> > pqlntegers_lnverse;
//
priority_queue <int> pqCopy(pqlntegers);
return 0;

7 10 p r i o r i t y _ q u e u e
i n t d o u b l e .
s t d : : v e c t o r
s t d : : l e s s o .
,
. p q l n t e g e r s _ l n v e r s e , ,
s t d : : g r e a t e r < > .
, .
s t d : : g r e a t e r < T > 24.7
.

- priority_queue
- f r o n t () b a c k ( ) , q u e u e ,
p r i o r i t y _ q u e u e . - p r i o r i t y _ q u e u e . 24.3.

24 .3. - std: :priority_queue

push

pqlntegers.push (10);
pop

, ..

pqlntegers.pop ();
top

cout

empty

"The largest element in the priority queue is: "


pqlntegers.top ();

, ; bool

if (pqlntegers.empty ())
cout "The queue is empty!";
size

size_t nNumElements = pqlntegers.size ();

556

24. :

, ,
t o p ( ) , ,
s t d : : l e s s < > .


push () pop ()
p u s h ():
pqlntegers.push (5); //

, , p o p ():
pqlntegers.pop (); //

p r i o r i t y _ q u e u e 24.6.
2 4 .6 . push ( ) ,top () pop ()

0:
1:
2:
3:
4:
5:
6:
7:
8:

#include <queue>
#include <iostream>
int main ()
{
using namespace std;
priority_queue <int> pqlntegers;
cout "Inserting {10, 5, -1, 20} into the priority_queue"
endl;
pqlntegers.push (10);
pqlntegers.push (5); //
pqlntegers.push (-1);
pqlntegers.push (20);

9:
10:
11:
12:
13:
14:

cout "Deleting the " pqlntegers.size () " elements"


endl;
while (!pqlntegers.empty ())
{
cout "Deleting topmost element: " pqlntegers.top ()
endl;
pqlntegers.pop ();
}

15:
16:
17:
18:
19:
20:
21:
22:

return 0;
}

Inserting {10, 5, -1, 20}


Deleting the 4 elements
Deleting topmost element:
Deleting topmost element:
Deleting topmost element:
Deleting topmost element:

into the priority_queue


20
10
5
-1

priority_queue STL

557

24.6
( 9 -1 2 ), , p o p ( ) ,
18. ,
. p r i o r i t y q u e u e : : ()
,
. t o p () ,
( 17). ,
( ).
24.7 p r i o r i t y _ q u e u e s t d : : g r e a t e r < i n t > .
, ,
f r o n t ().
2 4 -7 . ,
______________________________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <queue>
#include <iostream>
int main ()
{
using namespace std;

11:
12:
13:
14:
15:
16:
17:
18:
19:

// priority_queue greater<int>
priority_queue <int, vector <int>, greater <int> > pqlntegers;
cout "Inserting {10, 5, -1, 20} into the priority queue"
endl;
pqlntegers.push (10);
pqlntegers.push (5);
pqlntegers.push (-1);
pqlntegers.push (20);

20:

cout "Deleting " pqlntegers.size () " elements" endl;


while (!pqlntegers.empty ())
{
cout "Deleting topmost element " pqlntegers.top ()
endl;
pqlntegers.pop ();

21:

22:
23:
24: }

return 0;

Inserting {10, 5, -1, 20} into the priority queue


Deleting 4 elements
Deleting topmost element -1
Deleting topmost element 5
Deleting topmost element 10
Deleting topmost element 20

558

24. :

, p r i o r i t y _ q u e u e
, , 24.6.
, -.
g r e a t e r < i n t > ,
8. ,
. , t o p (), 19,
,
p o p () 20.
, ,
.


STL: , .
, , ,
- ,
.


?
, .

?
,
.

STL ?
STL . s t a c k , q u e u e
, ,
STL .


, ,
. ,
, .
,
.

559


1. p r i o r i t y _ q u e u e ,
?
2. C o i n s . -
,
?
3. C C o in s , .
?

1. ( C P e r s o n ) .
C P e r s o n , . :
class CPerson

{
public:
int Age;
bool IsFemale;

};
p r i o r i t y _ q u e u e ,
.
2. , , s t a c k ,
.

25

STL

. (STL)
,
.
.

bitset.

vector<bool>.

562

25.81-

b its e t
s t d : : b i t s e t ( ) STL
. s t d : : b i t s e t
STL, .
, ,
.

std::bitset,

#include <bitset>

s t d : :b it s e t
, ,
:
bitset <4> fourBits; // 4 , 0000


:
bitset <5> fiveBits ("10101"); // 5 10101

:
bitset <8> eightBitsCopy(eightbits);

25.1
b its e t.
25,1. std::bitset_____________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:

#include <bitset>
#include <iostream>
#include <string>
int main ()
{
using namespace std;
// bitset
bitset <4> fourBits; // 4 , 0000
cout "Initial contents of fourBits: " fourBits endl;
bitset <5> fiveBits ("10101"); // 5 10101
cout "Initial contents of fiveBits: " fiveBits

endl;

bitset <8> eightbits (255); // 8 ,


// 255 long int

std::bitset
16:
17:
18:
19:
20:
21:
22: }

cout

"Initial contents of eightBits: "

eightbits

563

endl;

//
bitset <8> eightBitsCopy(eightbits);
return 0;

Initial contents of fourBits: 0000


Initial contents of fiveBits: 10101
Initial contents of eightBits: 11111111

b i t s e t .
,
9. ,
, 12. u n s i g n e d l o n g ,
, 15,
19. ,
,
. ;
. , ,
.


s t d ::b its e t
b i t s e t - , ,
, .
, ,
.

,
s t d

: :b i t s e t

12, ,
,
. s t d : : b i t s e t
, . 25.1, .
, , f o u r
B i t s 25.1.

564

25.51_

2 5 .1 . , std: :bitset

operator

Cout

fourBits;

operator

bitset

operators

AND

"0101"

fourBits;

bitset <4> result (fourBitsl & fourBits2);


operator|

OR

bitwise <4> result (fourBitsl | fourBits2);


operatorA

XOR

bitwise <4> result (fourBitsl fourBits2);


operator^

NOT

bitwise <4> result (^fourBitsl);


operator=

operator=

operator [N]

fourBits =
fourBits =

(2); //
(2) ; //

fourBits [2] =0; // 0


bool bNum = fourBits [2]; //

s t d : : b i t s e t , | =, &=,
= ~=, .

std: :b its e t
: (1), (0).
b i t s e t (. 25.2),
.
2 5 .2 . std::bitset

Set

fourBits.set (); // : '1111'


set(N,

val=l)

val ( 1)

fourBits.set (2, 0); // 0


Reset

reset (N)

fourBits.reset (); // : '0000'


fourBits.reset (2); // 0

std::bitset

565

. 25.2

Flip

Size

Count

fourBits.flip (); // 0101 1010


size_t NumBits = fourBits.size ; // 4
size_t NumBitsSet = fourBits.count ();
size t NumBitsReset = fourBits.size () - fourBits.count ()

25.2.
25.2.
0: #include <bitset>
1: #include <string>
2 : #include <iostream>

3:
4: int main ()
5: {
6:
using namespace std;
7:
bitset <8> inputBits;
8:
cout "Enter a 8-bit sequence: ";
9:
10:
cin inputBits; //
//
11:

12:
13:
14:
15:
16:
17:
18:
19:
20:

21:

22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32: }

cout

cout
cout

"Number of Is you supplied: " inputBits.count ()


endl;
"Number of Os you supplied: ";
inputBits.size () - inputBits.count () endl;

bitset <8> inputFlipped (inputBits); //


inputFlipped.flip ();
//
cout

"Flipped version is: "

cout
cout
cout

"Result of AND, OR and XOR between the two:" endl;


inputBits " & " inputFlipped " = ";
(inputBits & inputFlipped) endl; // AND

cout
cout

inputBits " | " inputFlipped " = ";


(inputBits | inputFlipped) endl; // OR

cout
cout

inputBits " " inputFlipped " = ";


(inputBits inputFlipped) endl; // XOR

return 0;

inputFlipped

endl;

566

25.51-

Enter a 8-bit sequence: 10110101


Number of Is you supplied: 5
Number of Os you supplied: 3
Flipped version is: 01001010
Result of AND, OR and XOR between the two:

10110101 & 01001010 = 00000000


10110101 | 01001010 = 11111111
10110101 A 01001010 = 11111111


s t d : i b i t s e t ,
. ( ) ,
s t d : : b i t s e t ,
, .
i n p u t B i t s ( 10).
12 c o u n t ()
,
s i z e ( ), , c o u n t ( ),
14. i n p u t F l i p p e d , i n p u t B i t s ,
f l i p () 17.
, .. ,
.
A N D , O R X O R .
bitseto STL
.
bitset ,
.
STL vector<bool> (
bit_vector STL),
.

vector<bool>
v e c t o r < b o o l > s t d : : v e c t o r ,
.
.
.

std::vector<bool>, :

#include <vector>

vector<bool>

567

vector<bool>
v e c t o r < b o o l > :
vector <bool> vecBooll;

, 10 ,
1 (.. t r u e ) :
vector <bool> vecBool2 (10, true);

:
vector <bool> vecBool2Copy (vecBool2);

v e c t o r < b o o l >
25.3.
2S.3. v e c to r< b o o l> ________________________________
0: #include <vector>

1:
2: int main ()

3: {
4:
5:
6:
7:

using namespace std;


// ,
vector <bool> vecBooll;

8:

9:
10:
11:
12:
13:
14:
15:
16: }

// 10 true
vector <bool> vecBool2 (10,
true);
//
vector <bool> vecBool2Copy
(vecBool2);
return 0;


v e c t o r < b o o l > . 7 . 10
, 10 ,
t r u e . 13 , v e c t o r < b o o l >
.

vector<bool>
v e c t o r < b o o l > f l i p ( ) ,
, b i t s e t o : : f l i p ().
s t d : : v e c t o r ,
p u s h _ b a c k () . 25.4
.

568

25.8

25.4. vector<bool>__________________________
0:
1:
2:
3:
4:
5:
6:

#in clu d e <vector>


#in clu d e <iostream>
u sin g namespace std ;

i n t main ()
{
v e c t o r <bool> vecB oolF lags (3); / /
/ / 3
7:
vecB oolF lags [0] = tru e;
8:
vecB oolF lags [1] = tru e;
9:
vecB oolF lags [2] = f a l s e ;
10:

11:

vecB oolFlags.p ush_b ack ( tr u e ); / /

13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27: }

cout "The c o n t e n ts o f the v e c t o r are: " endl;


fo r ( s i z e _ t nlndex = 0; nlndex < v e c B o o l F l a g s . s i z e (); ++ nlndex)
cout vecB oolF lags [nlndex] ' ';

12:

cout endl;
v e c B o o lF la g s . f l i p

();

cout "The c o n t e n ts o f the v e c t o r are: " endl;


for ( s i z e _ t nlndex = 0; nlndex < v e c B o o lF la g s . s i z e (); ++ nlndex)
cout vecB oolF lags [nlndex] ' ';
cout

endl;

return 0;

The contents of the vector are:


1 1 0

The contents of the vector are:


0 0 10



18 ,
0 1, . push_back () 11.
v e c B o o lF la g s ( 6),
11 . ,
,
, vecto r< boo l> s t d : :b it s e t .
o p e r a t o r ! ] ( 7 -9 ), . f l i p ( )

569


: s t d : : b i t s e t .
v e c t o r < b o o l > , ,
, , .


, , s td : i b i t s e t v ec to r< b o o l> ,
?
s t d : : b i t s e t , .

myBitSeq std : : b i t s e t ,
. 0 ( f a l s e ) ?
b i t s e t : : c o u n t () 1.
, b i t s e t : : s i z e ( ) (
), 0 .


vector< bool>?
. v e c t o r < b o o l >
s t d : : v e c t o r , .

,
vector< bool>?
, ,
v e c t o r < b o o l > : : r e s i z e .


, ,
. ,
, .
,
.


1.
?
2. b i t s e t STL?
3. s t d : : v e c t o r
, ?

570

25.1-

1. , . ,
. ( :
: b i t s e t A = b i t s e t X + b i t s e t Y . )
2. , .

C++
26.
27.
28.
29.

26

C++
(
); .
.

std: :auto_ptr.

std: :unique_ptr
++11.

26

C++
(
); .
.

std: :auto_ptr.

std: :unique_ptr
++11.

574

26.


, (sm art pointer) C ++
, , .


.

()
, C ++
, .
, . , C ++
,
, ,
.
:
CData *pData = mObject.GetData ();

/*
: , pData,
new?
: ?
: !

*/
pData->Display ();

,
, p D a ta ,

, ;


,
, ,
.



, C ++
, (
) .
:
smart_pointer<CData> spData = mObject.GetData ();
// !

575

spData->Display ();
(*spData).Display () ;
//
// ( )

, (
(raw pointer)),
(overloaded operator)
(destructor),
.




s p D a ta ? :
,
(*)
(-> ). 12,
.
, ,
,

. ,
.
26.1
.
2 6 .1 .

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:

template <typename >


class smart_pointer
{

private:
T* m_pRawPointer;
public:
smart_pointer (T* pData)

: m_pRawPointer (pData) {}
//
~smart_pointer () {delete pData;};
//

//
smart_pointer (constsmart_pointer & anotherSP);
//
smart_pointer& operator=
(constsmart_pointer& anotherSP);
T& operator* () const //
{
return * (m_pRawPointer) ;
}

576

26.

18
19

* operator-> () const //

20
21

return m_pRawPointer;

22
23


* -> , 1 4-17 19-22.
. ,
T una, :
smart_pointer <Tuna> pSmartTuna (new Tuna);
pSmartTuna->Swim();
// :
(*pSmartDog).Swim ();

s m a r t _ p o i n t e r
,
. ( 7)
,
. ,
.
,
, - , .
,
,
(.. ).

.

1|
(.. )
. ,
.
,
. , ,
,
.

.

(COW ).

577

.
,
s t d : : u n i q u e _ p t r ,
C++.


,
, , . ,
, , (
).
, , (
).
, ,
,
, ,
(slicing):
//
// Fish - Tuna Carp,
// Fish::Swim() -
void MakeFishSwim (Fish aFish) //
{
aFish.Swim(); //

}
// ...
Carp freshWaterFish;
MakeFishSwim (freshWaterFish); // : MakeFishSwim()
// Fish Carp
Tuna marineFish;
MakeFishSwim(marineFish); //

,
, 26.2.
2 .2 .
_____________________

:
1:
2:
3:
4:
5:
6:
7:
8:

template <typename >


class deepcopy_smart_pointer
{

private:
T* mjpObject;
public:
// ...

19 . 3626

//

578
9:
10:

26.
deepcopy_smart_pointer (const deepcopy_smart_pointer& source)

11:

// Clone() :
//
m_pObject = source->Clone ();

12:
13:
14:
15:
16:

}
//
deepcopy_smart_pointer& operator= (const deepcopy_smart_pointer&
source)
{
if (m_pObject)
delete m_pObject;

17:
18:
19:
20:
21:

m_pObject = source->Clone

22:

();

23:
24: };

, d e e p c o p y _ s m a r t _ p o i n t e r
9 -1 3 .
C lo n e ( ) , .
16-22.
, C lo n e () F i s h . ,
, ,
, .
,
F i s h , C a r p :
deepcopy_smart_ptr<Carp> freshWaterFish(new Carp);
MakeFishSwim (freshWaterFish); // Carp ''

, ,
, ,
M a k e F is h S w im () .
.
,

. ,
M a k e F is h S w im ( ), ( F is h * ) .
.


(C opy on W rite C O W )

.

579

COW, ,
, ,
.
C O W .
C O W (*) (-> )
COW.
.
, , COW ,
,
. ,
, .


(reference counting)
. , .

. - M icrosoft
, .
,
.
.

, .

, ,
(intrusive reference counting), .
,
, . ,
. ,
, ,
(
, ),
.
,
.
,
() ,
,
, . ,
, , : ,
, ,
(cyclic dependency)
1.

580

26.


(reference-linked) ,
, , ,
, .
,
.
, .
,
. , , ,
.


(destructive ) ,

, :
destructive_copy_smartptr <SampleClass> pSmartPtr (new SampleClass ());
SomeFunc (pSmartPtr); // SomeFunc
// He pSmartPtr !

,

,
. ,
,
.

C++ ( 26.3).
std: :auto_ptr , , (
, )
. ,
.
std: :auto_ptr C++ .
std: :unique_ptr,

.
.

2 6 .3 .

:
1:
2:
3:
4:

template <typename >


class destructivecopy_pointer
{

private:
T* pObject;

6
7
8
9

public:
destructivecopy_pointer(* plnput):pObject(plnput)
~destructivecopy_pointer() { delete pObject; }

{}

//
destructivecopy_pointer(destructivecopy_pointer& source)

10
11
12

{
//
pObject = source.pObject;

13
14
15
16
17
18
19
20

//
source.pObject = 0;

}
//
destructivecopy_pointer& operator= (destructivecopy_pointer& rhs)

21

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38

581

{
if (pObject != source.pObject)

{
delete pObject;
pObject = source.pObject;
source.pObject = 0;

int main()

{
destructivecopy_pointer<int> pNumber (new int);
destructivecopy_pointer<int> pCopy = pNumber;
// pNumber
return 0;

26.3
. 10-17 2 0 -2 8
.
; ..
, , N U LL,
. . ,
pN um ber 34,
. .

,
,
26.3, .
C++,
,

582

26.

.

,
. ,
.
, ,

STL, s t d : : v e c to r , ,
.
, ,
.

.

C++
a u to _ p tr . , C++11,
,

s t d : :u n iq u e _ p tr.

++11____________________________________________
std: :unique_ptr
s t d : : u n i q u e _ p t r + + 1 1,
a u t o _ p t r , .

s t d : :u n iq u e _ p tr , :

t i n c l u d e <memory>
u n i q u e _ p t r ,
26.1, ,

. 26.4.
2 8 .4 . std: : unique ptr______________________________

0:
1:
2:
3:
4:
5:
6:
7:

#include <iostream>
#include <memory>
// std: :uniquej?tr
using namespace std;
class Fish
{
public:
Fish() {cout

"Fish: Constructed!"

endl;}

~Fish()

{cout

"Fish: Destructed!"

583

endl;}

10

11
12
13
14
15
16
17
18
19
20

void Swim() const {cout

endl;}

void MakeFishSwim(const unique_ptr<Fish>& inFish)

{
inFish->Swim();

}
int main()

{
unique_ptr<Fish> smartFish (new Fish);

21

22
23
24
25
26
27
28
29

"Fish swims in water"

};

smartFish->Swim();
MakeFishSwim(smartFish); // OK, MakeFishSwim
//
unique_ptr<Fish> copySmartFish;
// copySmartFish = smartFish; // : operator=
return 0;

Fish: Constructed!
Fish swims in water
Fish swims in water
Fish: Destructed!

, .
: , , s m a r t
F i s h , m a in ( ) , , (
) d e l e t e . u n i q u e _ p t r ,

. , 23 s m a r t F i s h
M a k e F ish S w im ( ) . ,
M ak eF ish S w im () , 13.
& 13, ,
.
u n i q u e _ p t r , 26,
.
, u n i q u e _ p t r , a u t o _
p t r ( ),
.
, .

584

26.



, ,
C++, .
.
B oost (w w w .b o o s t.o r g )
,
.
B oost h t t p : / / w w w . b o o s t . o r g / l i b s /
s m a r t _ p t r / s m a r t _ p t r . htm .
W indow s

ATL, C C om Ptr C C om Q IPtr,
.

,
,
.
, , . ,
s t d : : a u t o _ p t r ,
.
s t d : : u n i q u e _ p t r , ++11.


. auto_ptr
, ?
, s t d : : a u t o _ p t r .
.
.

,
?
o p e r a t o r * o p e r a t o r - > .
.

, C lassl Class2 ,
.
?
, , - ,
, , ,
.

585

?
, .
,
, Boost.

s t r in g ,
. , s t r in g ?
. o p e r a t o r * o p e r a t o r - > ,
.


, ,
. ,
, .
,
.


1. ,
?
2. ?
3.
?
4.
?

1. : :
std::auto_ptr<SampleClass> pObject (new SampleClass ());
std::auto_ptr<SampleClass> pAnotherObject (pObject);
pObject->DoSomething ();
pAnotherObject->DoSomething();

u n i q u e _ p t r C a rp ,
F i s h . F i s h
, .
2. : :
std::unique_ptr<Tuna> myTuna (new Tuna);
unique_ptr<Tuna> copyTuna;
copyTuna = myTuna;

27




, 1, ",
Hello World", s t d : : c o u t .
C++
.
.

, .

C++.

588

27.


, , ,
, .
,
, ,
? C++!
(stream ) C++ (
, ),
. , ,
, .
, ,
.
C ++
(. 1.1):
std::cout

"Hello World!"

std::endl;

: s t d : : c o u t o s t r e a m
. s t d : : c o u t ,
< i o s t r e a m > , ,
s t d : : in , .
, ,
? H ello W orld
,
fsHW:
fsHW << "Hello World!" << endl; // "Hello World!"

,
H ello W orld .

operatorf ,
(stream insertion operator).

, ..
operator, ,
(stream extraction operator).
, ..

,
.

C++
C ++ ,
. . 27.1
.

C++

589

2 7 .1 . C++ s t d

cout

, ,

cin

, ,

cerr

fstream

;
ofstream ifstream

ofstream

ifstream

stringstream

;
istringstream ostringstream;
( ),

cout, cin cerr


ostream, istream ostream .
, main ().


(m anipulator),
. s t d : : e n d l ,
:
std::cout

"This lines ends here"

std::endl;

. 27.2.
2 7 .2 . std

endl

ends

dec

Hex

oct

590

27.
. 27.2

fixed

scientific <iomanip>

setprecision

setw

setfill

setbase

, dec,
hex oct

setiosflag

resetiosflag

,
std: :ios_base: :fmtflags

std::ios_base::fmtflags

std: :cout


s t d : : c o u t ,
, , , .
c o u t
.


s t d : : c o u t
. 27.1 c o u t
.
2 7 .1 . ,
cout <iomanip>________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
cout << "Enter an integer:
int Input = 0;
cin Input;
cout

"Integer in octal: "

oct

Input

endl;

stdncout...
11

12

cout

"Integer in hexadecimal: "

13
14

cout
cout

15
16
17
18

cout

"Integer in hex using base notation: ";


setiosflags(ios_base::hex|ios_base::showbase|ios_base \
::uppercase);
Input endl;

cout
cout

hex

Input

591

endl;

"Integer after resetting I/O flags: ";


resetiosflags(ios_base::hex|ios_base::showbase|ios_base \
:uppercase) ;
Input endl;

19
20

cout

21

return 0;

22

Enter an integer: 253


Integer in octal: 375
Integer in hexadecimal: fd
Integer in hex using base notation: OXFD
Integer after resetting I/O flags: 253

. 27.2
c o u t .
o c t h e x 10 . 14 s e t
i o s f l a g s ()
. c o u t 253
0XFD. r e s e t i o f l a g s () 18 c o u t
.
:
cout

dec

Input

endl; //

c o u t , P i,
, .. ,
,
( 27.2).
2 7 .2 . cout Pi
________________________

0:
1:
2:
3:
4
5:
6:
7:

8:

9:

#include <iostream>
tinclude <iomanip>
using namespace std;
: int main ()
{
const double Pi = (double)22.0 / 7;
cout "Pi = " Pi endl;
cout

endl

"Setting precision to 7: "

endl;

592
10:
11:
12:
13:
14: '
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27: }

27.
cout
cout
cout
cout

cout
cout
cout
cout
cout

<<

setprecision(7);
"Pi = " Pi endl;
fixed "Fixed Pi = "
scientific "Scientific

Pi endl;
Pi= "
Pi

endl "Setting precision to 10: " endl;


setprecision(10);
"Pi = " Pi endl;
fixed "Fixed Pi = " Pi endl;
scientific "Scientific Pi = " << Pi endl;

cout endl
"Enter a radius: ";
double Radius = 0.0;
cin
Radius;
cout "Area of circle: " 2*Pi*Radius*Radius
return

endl;

endl;

0;

Pi = 3.14286
Setting precision to 7:
Pi = 3.142857
Fixed Pi = 3.1428571
Scientific Pi = 3.1428571e+000
Setting precision to 10:
Pi = 3.1428571429e+000
Fixed Pi = 3.1428571429
Scientific Pi = 3.1428571429e+000
Enter a radius: 9.99
Area of circle: 6.2731491429e+002

, 7 10 10
16 P i . ,
s c i e n t i f i c
6 .2 7 3 1 4 9 1 4 2 9 + 0 0 2 .


std: :cout
,
s e tw ().
. s e t f i l l ()
, ,
27.3.

std::cin

593

2 7 .3 .
setw () setfill ()________

0
1
2

#include <iostream>
#include <iomanip>
using namespace std;

3
4
5

int main()

cout

"Hey - default!"

cout
cout

setw(35); // 25
"Hey - right aligned!" << endl;

cout
cout

setw(35) setfill ('*);


"Hey - right aligned!" endl;

cout

"Hey - back to default!"

{
endl;

7
8

10
11
12

13
14
15
16
17

endl;

return 0;

Hey - default!
Hey - right aligned!
************** * - right aligned!
Hey - back to default!

s e tw (35) 8
s e t f i l l ( ' * ') c o u t . ,
, ,
, s e t f i l l ().

std: :c in
s t d : : c i n , ,
i n t , d o u b le c h a r * , ,
, g e t l i n e ().

std: :cin

c i n i n t , d o u b l e c h a r
. 27.4
c i n , .

594

27.

27.4. 1 i n t ,
d o u b le c h a r

0:
1:
2:
3:
4:
5:
6:
7:

#include<iostream>
using namespace std;
int main()
{
cout "Enter an integer: ";
int Inputlnt = 0;
cin Inputlnt;

8:

9:'
10:
11:

cout "Enter the value of Pi: ";


double Pi = 0.0;
cin Pi;

12:

13:
14:
15:
16:
17:
18:
19:
20:

cout "Enter three characters separated by space: " << endl;


char Chari = 'NO', Char2 = *\0\ Char3 = \0';
cin >> Chari Char2 Char3;
cout
cout
cout
cout

<<

"The recorded variable values are: " endl;


"Inputlnt: " Inputlnt endl;
"Pi: " << Pi endl;
"The three characters: " Chari Char2
endl;

Char3

21:

22:
23: }

return 0;

Enter an integer: 32
Enter the value of Pi: 0 . 3 1 4 1 5 9 2 6 5 e l
Enter three characters separated by space:
C +

The recorded variable values are:


Inputlnt: 32
Pi: 3.14159
The three characters: C + +

27.4 P i
P i
d o u b l e . ,
( 15).

s t d : : c i n : : g e t ( )

, c i n
i n t , :

std::cin

595

cout "Enter a line: " endl;


char CStyleStr [10] = {0}; // 10
cin CStyleStr; // : 10

,
.
:
cout "Enter a line: " endl;
char CStyleStr[10] = {0};
cin.get(CStyleStr, 9);
// 9-

27.5.

27.5. __________________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

#include<iostream>
#include<string>
using namespace std;
int main()
{
cout "Enter a line: " endl;
char CStyleStr[10] = {0};
cin.get(CStyleStr, 9);
cout "CStyleStr: " CStyleStr

endl;

return 0;
}

Enter a line:

Testing if I can cross the bounds of the buffer


CStyleStr: Testing i

, 8 c i n : : g e t ( ) ,
.
.

char.
std::string.

s t d : : cin
s t d : : s trin g
c i n ,
s t d : : s t r i n g :

596

27.

std::string Input;
cin Input; //

27.6 c i n
s td : : s trin g .
2 7 .6 . std::string cin_______

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:

#include<iostream>
#include<string>
using namespace std;
int main ()
{
cout "Enter your name: ";
string Name;
cin Name;
cout "Hi " Name endl;
return 0;
}

Enter your name: Siddhartha Rao


Hi Siddhartha

, .
, Name, c i n 8,
, . ? c i n
, .
, ,
g e t l i n e ():
string Name;
getline(cin, Name);

g e t l i n e () c i n 27.7.
2 7 .7 .
getline () cin__________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:

#include<iostream>
#include<string>
using namespace std;
int main()
{
cout "Enter yourname:
";
string Name;
getline(cin, Name);
cout "Hi " Name <<endl;

std::fstream
10 :
11:
12:

597

return 0;
}

Enter your name: Siddhartha Rao


Hi Siddhartha Rao

g e t l i n e ( ) , 8,
. .

s t d :: f stream

s t d : : f s t r e a m C ++ ()
. s t d : : f s t r e a m s t d : : o f s t r e a m
s t d : : o f s t r e a m .
, s t d : : f s t r e a m ,
.

std::fstream, :

#include <fstream>


open () c lo s e ()
f s tr e a m , o f s t r e a m i f s tr e a m ,
o p e n ():
fstream myFile;
myFile.open("HelloFile.txt",ios_base::in|ios_base::out|ios_base::trunc);
if (myFile.is_open())

{
//
myFile.close ();

o p e n () :
( , ),
, . ,
( i o s _ b a s e : : t r u n c ) , ( i n | o u t) .
i s _ o p e n ()
o p e n ().

598

27.

:
fstream myFile("HelloFile.txt",
i'os_base::in |ios_base::out |ios_base::trunc) ;

, :
ofstream myFile("HelloFile.txtM, ios_base::out);

, :
ifstream myFile("HelloFile.txt", ios_base::in);

, open (),
is_open (),

.

i o s b a s e : : . , .

i o s _ b a s e : : a t e . , .

i o s _ b a s e : : t r u n c . ( ).

i o s _ b a s e : : b i n a r y . ( ).

i o s _ b a s e : : in . .

i o s _ b a s e : : o u t. .


open
,
( 27.8).

27.8.
ofstream

0:
1:
2:
.
4:
5:
6:
7:

9:
10:
11:
12:

#include<fstream>
#include<iostream>
using namespace std;
int main()
{
ofstream myFile;
::out);
myFile.open("HelloFile.txt", ios_base:
if (myFile.is open())
{
cout "File open successful"

endl;

std::fstream
13:
14:
15:
16:
17:
18:
19:
20:
21:

myFile
myFile

" first text file!"


"Hello file!";

599

endl;

cout "Finished writing to file, will close now"


myFile.close ();

endl;

}
return 0;
}

File open successful


Finished writing to file, will close now

H e l l o F i l e . t x t :
My first text file!
Hello file!

7 i o s j o a s e : : o u t .. .

9 o p e n ( ),
o p e r a t o r ,
13 14. , 17.

27.8 ,
cout, , (..
).
, C++
,
cout of stream.


()
f s t r e a m ,
i o s j o a s e : : in , i f s tr e a m . 27.9
H e l l o F i l e . t x t , 27.8.

27.9. HelloFile.txt, 2 7 .8 _________


0:
1:
2:
3:
4:
5:
6:

#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main()
{

600
7

27.
ifstream myFile;
myFile.open("HelloFile.txt", ios_base::in);

10

if (myFile.is_open())

11

12
13
14
15
16
17
18
19

cout "File open successful. It contains: "


string fileContents;

endl;

while (myFile.good())
getline (myFile, fileContents);
cout fileContents endl;

20

21
22
23
24
25

cout "Finished reading file, will close now"


myFile.close();

endl;

else
cout

26
27
28: }

"open() failed: check if file is in right folder"


endl;

return 0;

File open successful. It contains:


My first text file!
Hello file!
Finished reading file, will close now

27.9 HelloFile.txt,
27.8,
, .

, i s o p e n () 8
o p e n ( ).
,
c o u t 18. g e t l i n e ()
, 27.7 ,
.


,
.
i o s b a s e : : b i n a r y . o f s t r e a m : : w r i t e ()
i f s t r e a m : : r e a d ( ), 27.10.

std::fstream

601

27.10.
0: #include<fstream>
1: #include<iomanip>
2 : #include<string>
3: #include<iostream>
4: using namespace std;
5:
/
6: struct Human
7: {
Human () {};
8:
Human(const char* inName, int inAge, \
9:
const char* inDOB) : Age(inAge)
10:
{
11:
strcpy(Name, inName);
12:
strcpy(DOB, inDOB);
13:
}
14:
15:
char N^me[30];
16:
int Age;
17:
char DOB[20];
18: };
19:
20: int main()
21: {
22:
Human Input("Siddhartha Rao", 101, "May 1910");
23:
24:
ofstream fsOut ("MyBinary.bin", \
ios_base::out I ios_base::binary);
25:
26:
if (fsOut.is_open())
27:
28:
cout "Writing one object of Human to a binary file"
endl;
29:
fsOut.write(reinterpret_cast<const char*>(&Input), \
sizeof(Input));
30:
fsOut.close();
31:
}
32:
33:
ifstream fsln ("MyBinary.bin", ios_base::in | ios_base::binary);
34:
35:
if(fsln.is_open())
36:
{
37:
Human somePerson;
38:
fsln.read((char*)&somePerson, sizeof(somePerson));
39:
40:
cout "Reading information from binary file: " endl;
41:
cout "Name = " somePerson.Name endl;
42:
cout "Age = " somePerson.Age endl;
43:
cout "Date of Birth = " somePerson.DOB endl;
44:
}
45:
46:
return 0;
47: }

602

27.

Writing one object of Human to a binary file


Reading information from binary file:
Name = Siddhartha Rao
Age = 101
Date of Birth = May 1910

22-31 Human, Name,


Age DOB. M y B in a r y .b i n
o f s t r e a m . , 3 3 -4 4 ,
i f s t r e a m .
, Name , .
i f s t r e a m o f s t r e a m
i f s t r e a m : : r e a d ( ) o f s t r e a m : : w r i t e () .
r e i n t e r p r e t c a s t 29,
c h a r * . 38
.

, Human
XML. XML
.
, Human,
(, NumChildren),
ifstream::read ,
.

s t d : : stringstream

, , " 4 5 " .
45? ?
, C++, s t r i n g s t r e a m ,
.

std::stringstream, :

#include <sstream>

s t r i n g s t r e a m
27.11.

std::stringstream

603

27.11. ,
, std: :stringstream_____________________
0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:

#include<fstream>
#include<sstream>
#include<iostream>
using namespace std;
int main()
{

cout "Enter an integer: ";


int Input = 0;
cin Input;
stringstream converterStream;
converterStream Input;
string strlnput;
converterStream strlnput;
cout "Integer Input = " Input endl;
cout "String gained from integer, strlnput = "
endl;

18:
19:
20:
21:
22:
23:
24:
25:
26:
27: }

strlnput

stringstream anotherStream;
anotherStream strlnput;
int Copy = 0;
anotherStream Copy;
cout

"Integer gained from string, Copy = "

Copy

endl;

return 0;

Enter an integer: 45
Integer Input = 45
String gained from integer, strlnput = 45
Integer gained from string, Copy = 45

.
s t r i n g s t r e a m ( 12) . ,
14,
.
,
s trln p u t.

604

27.

ifstream ,


close ()

of stream ,


is_open (}.
,

,
cin
strData;
strData

, getline (cin,
strData);
,

C++ .
, c o u t c in , .
, ,
. , s t r i n g s t r e a m
, i n t , , .


f stream , ,
o f stream i f stream?
,
if s tr e a m . , , o f stream . f stream ,
,
, .
c i n . g e t (), c i n . g e t l i n e () ?
c i n . g e t l i n e () ,
. i n . g e t ()
.
strin g strea m ?
s t r i n g s t r e a m
, (. 27.11).


, ,
. ,

605

, .
,
.


1. . ?
2. i n ?
3. s t d : : s t r i n g .
i o s _ b a s e : :b in a ry ?
4. o p e n ().
i s _ o p e n () ?

1. : :
fstream myFile;
myFile.open("HelloFile.txt", ios_base::out);
myFile "Hello file!";
myFile.close();

2. : :
ifstream MyFile("SomeFile.txt");
if(MyFile.is_open())

{
MyFile "This is some text"
MyFile.close();

endl;

28

,
, .
, ,
, ..
.
.


C++.

608

28.


, ,
. ,
, ,
! ,
. .
. ,
.
, .
: .
, ?
, .
, . ,
, ,
, , .
, ,
, .
, .
(exception).
.
, ,
, .
, ,
, .
, A ccess Violation
U nhandled E xception, .
, C++,
.


,
, ,
.
, , .
, (handle) ,
(exception safe).


try catch
, C++
t r y c a t c h .

try catch

609

, t r y ,
t r y c a t c h :
void SomeFuncO
try
int* pNumber = new int;
*pNumber = 999;
delete pNumber;

}
catch(...) // ...

{
cout

"Exception in SomeFuncO, quitting"

endl;

}
}

catch ( . . . )

, 8, , ,
new ,
, . 28.1 ,
new
,
.
28.1. try catch
____________________________________

0:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:18:
19:
20:

#include <iostream>
using namespace std;
int main()
{
cout "Enter number of integers you wish to reserve: ";
try
{
int Input = 0;
cin Input;
//
int* pReservedlnts = new int [Input];
delete[] pReservedlnts;
}
catch (...)
{
cout
}
return 0;
}

20 3ak. 3626

"Exception encountered. Got to end, sorry!" << endl;

610

28.

Enter number of integers you wish to reserve: -1


Exception encountered. Got to end, sorry!

- 1 . ,
.
. , ,
: G ot t o e n d , s o r r y ! ( , !).

Visual Studio,
, . 28.1.

. 2 8 .1 .

, Ignore
(). ,
.

28.1 c a t c h t r y . c a t c h ()
, ,
, c a t c h
.
s t d : : b a d _ a l l o c , new.

, , , ,
.


28.1 C++.
, ,
, , ,
, 28.2.

try catch

611

2 8 .2 . s t d : : b ad a l l o c ______________________

0:
1:
2:
3:
4
5:
6:
7:

# in c lu d e < io stre am >


# in c lu d e < e x c e p tio n > / / b a d _ a llo c
u s in g nam espace s t d ;
: i n t main ()
{
c o u t " E n te r number o f i n t e g e r s you w ish to r e s e r v e : " ;
try

8:

9:
10:

i n t I n p u t = 0;
c in I n p u t;

11:

12:
13:
14:
15:
16:
17:
18:
19:

/ /
in t* p R e s e r v e d ln ts = new i n t [ I n p u t] ;
d e l e t e [] p R e s e r v e d ln ts ;
}
c a tc h ( s td ::b a d _ a llo c & exp)
{
c o u t "E x c e p tio n e n c o u n te re d : " e x p .w h a t()
c o u t "Got to end, s o r r y ! " e n d l;

20:

21:
22:
23:
24:
25:
26: }

c a tc h ( . . . )
{
cout
}
r e t u r n 0;

e n d l;

"E x c e p tio n e n c o u n te re d . Got to end, s o r r y ! "

e n d l;

E n te r number o f in te g e r s you wish to re s e rv e : -1


E xception en c o u n tered : bad a l lo c a tio n
Got to end, so rry !

28.2 28.1. ,
,
bad allocation ( ). ,
c a t c h (, c a t c h ) ,
c a t c h ( b a d _ a l l o c & ) , 16-20.
c a tc h (), ,
.
c a tc h ( . . . ) , 28.2,
, c a tc h .

612

28.


throw
s t d : : b a d _ a l l o c 28.2,
s t d : : b a d _ a l l o c , new.
.
th ro w :
void DoSomething()

{
if(something_unwanted)
throw Value;

th r o w
, , 28.3.
2 8 .3 .

0
1

#include<iostream>
using namespace std;

double Divide(double Dividend, double Divisor)

4
5

{
if(Divisor == 0)
throw "Dividing by 0 is a crime";

6
7
8

return (Dividend / Divisor);

9
10

11
12

int main()

13
14
15
16
17
18
19
20

cout << "Enter dividend: ";


double Dividend = 0;
cin Dividend;
cout << "Enter divisor: ";
double Divisor = 0;
cin Divisor;
try

21

22
23
24
25
26
27
28
29
30
31

cout

"Result of division is: "


Divide(Dividend, Divisor);

}
catch(char* exp)

{
cout
cout

}
return 0;

"Exception: " exp endl;


"Sorry, can't continue!" endl;

613

Enter dividend: 2011


Enter divisor: 0
Exception: Dividing by 0 is a crime
Sorry, can't continue!

c h a r * ,
24, , ,
D i v i d e () 6. , t r y {}
m a in ( ) , ,
. ,
.


D iv id e () 28.3 c h a r * ,
c a t c h ( c h a r * ) m a in ().
th r o w ,
c a t c h ,
.
t r y . ,
c a t c h , . th r o w
t r y c a t c h ( ), ,
. ,
,
, c a t c h ,
.
, ( 28.4).
2 8 .4 . _____________

0:
1:
2:
3:
4:
5:
6:

#include <iostream>
using namespace std;
struct StructA
{
StructA() {cout "Constructed a struct A" endl; }
~StructA() {cout "Destroyed a struct A" endl; }

7: };
8:

9: struct StructB
10:

11:
StructB() {cout "Constructed a struct B" endl; }
12:
~StructB() {cout "Destroyed a struct B" endl; }
13: };
14:
15: void FuncB() //

614
16
17
18
19

28.
{
cout "In Func " endl;
StructA objA;
StructB objB;
cout "About to throw up!" endl;
throw "Throwing for the heck of it";

20

21
22

23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

}
void FuncAO
{
try

{
cout "In Func A" endl;
StructA objA;
StructB objB;
FuncB();
cout "FuncA: returning to caller"

endl;

}
catch(const char* exp)

{
cout "FuncA: Caught exception, it says: " exp endl;
cout "FuncA: Handled it here, will not throw to caller"
endl;
// throw; // main ()

}
}
int main ()

{
cout
try

"main(): Started execution"

endl;

FuncA();

}
catch(const char* exp)

{
cout

"Exception: "

exp

endl;

}
cout "main(): exiting gracefully"
return 0;

main(): Started execution


In Func A
Constructed a struct A
Constructed a struct
In Func
Constructed a struct A
Constructed a struct
About to throw up!
Destroyed a struct

endl;

615

Destroyed a struct
Destroyed a struct
Destroyed a struct
FuncA: Caught exception, it says: Throwing for the heck of it
FuncA: Handled it here, will not throw to caller
main(): exiting gracefully

28.4 m a in () F u n c A (),
F u n c B ( ) , 21. , F u n
c A ( ) m a in ( ) , ,
c a t c h ( c o n s t c h a r * ). F u n c B ( ) , ,
c a t c h ( ), ,
c a t c h F u n c A () ( 3 4-3 9 ), F u n c A ()
F u n c B ( ) . : F u n c A ( )
, ,
m a in (). , m a in () ,
. 38,
, .. m a in () .
( ,
) (
). F u n c B ( ) ,
, F u n c A ( ) , F u n c B ( )
.

28.4
.
, ,
, .

s t d : : exception
s t d : : b a d _ a l l o c 28.2
s t d : : b a d _ a l l o c , new. s t d : : b a d _ a l l o c C ++ s t d : : e x c e p t i o n ,
< e x c e p t io n > .

s t d : : e x c e p t i o n .

b a d a l l o c . new.

b a d _ c a s t . d y n a m ic _ c a s t
( ).

i o s _ b a s e : : f a i l u r e . io s t r e a m .

s t d : : e x c e p t i o n ,
, w h a t ( ) ,
, . e x p . w h a t ()

616

28.

18 28.2 b a d a l l o c a t i o n ,
, .
s t d : : e x c e p t i o n , ,
, c a t c h ( c o n s t e x c e p t i o n s ) 4, ,
s t d : : e x c e p t i o n :
void SomeFuncO

{
try

{
// ,

}
catch (const std::exceptions exp) // bad_alloc,
// bad_cast ..

{
cout

"Exception encountered: "

exp.what() << endl;

,
std: exception
, .
s t d : : e x c e p t i o n
c a t c h ( c o n s t s t d : : e x c e p t i o n s ) , b a d _ a l l o c , b a d _
c a s t ..
, ( 28.5).
2 8 .5 . CustomException, std: exception_________

0:
1:
2:
3:
4:
5:

#include <exception>
#include <iostream>
#include <string>
using namespace std;
class CustomException: public std::exception

6: {

7:
string Reason;
8: public:
9:
// , Reason
10:
CustomException(const char* why):Reason(why) {}
11:
12:
// 'Reason'
13:
virtual const char* what() const throw()
14:
{
15:
return Reason.c_str();
16:
}
17: };
18:
19: double Divide(double Dividend, double Divisor)


20:

617

21:
22:

if(Divisor == 0)
throw CustomException("CustomException: \
Dividing by 0 is a crime");

23:
24:
25: }
26:
27: int
28: {
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46: }

return (Dividend / Divisor);

main()
cout "Enter dividend: ";
double Dividend = 0;
cin Dividend;
cout "Enter divisor: ";
double Divisor = 0;
cin Divisor;
try
{
cout "Result of division is: "
Divide(Dividend, Divisor);
}
catch(exceptions exp) // CustomException,
// bad_alloc ..
{
cout exp.what() endl;
cout "Sorry, can't continue!" endl;
}
return 0;

Enter dividend: 2011


Enter divisor: 0
CustomException: Dividing by 0 is a crime
Sorry, can't continue!

28.3, c h a r *
. , , C u s to m E x c e p tio n ,
5 -1 7 , s t d : : e x c e p t i o n .
, w h a t ()
13-16, , .
c a t c h ( e x c e p t i o n s ) m a in () ( 3 9 -4 3 )
C u s to m E x c e p tio n , , b a d _ a l l o c ,
e x c e p t i o n .

618

28.

c-ustomException::
what () 13 28.5:
virtual const char* what() const throw()
throw (), , ,
, -
, .
throw ,
.
throw ( i n t ) , ,
i n t .


s t d : :ex cep tio n

( )
s t d : : e x c e p t ion


; ,
new,
t r y

,
t r u e f a l s e

c a t c h ().

C++.
, ,
, . ,
. , , ,
, , . , C ++
s t d : : e x c e p t i o n ,
.

, ?
. new
.
,
, .

s t d : : e x c e p t i o n ?
, , ,
c a t c h ( ) ,
s t d : e x c e p t i o n . ,

619

,
c a t c h (M yN ew E xceptionT ype& ) .

, .
?
. ,
.

?
! ,
.

?
. ,
. ,
, ,
, , ,
.


, ,
. ,
, .
,
.


1. s t d : : e x c e p t i o n ?
2.
new?
3. ( c a t c h )
,
?
4. M y E x c e p tio n ,
s t d : : e x c e p t i o n ?

1. : ?
class SomelntelligentStuff
{
bool StuffGoneBad;
public:
~ SomelntelligentStuff()

28.

620

if (StuffGoneBad)
throw "Big problem in this class, just FYI";

};
2. : ?
int main()

{
int* pMillionlntegers = new int [1000000];
//
delete []pMillionlntegers;

}
3. : ?
int main()

{
try

{
int* pMillionlntegers = new int [1000000];//
delete []pMillionlntegers;

}
catch(exceptions exp)

{
int* pAnotherMillionlntegers = new int [1000000];
// pMillionlntegers
//

}
}

29


C++.
,
(STL), , STL
.

.
.

C++
.

C++.

29


C++.
,
(STL), , S T L
.

.
.

C++
.

C++.

622

29.


,
() ( ), (). ,
Intel 8086 (. 29.1), 1978, 16-
10 .

. 2 9 .1 . Intel 8 0 8 6

, C++?


. ,
, .
Intel 64- 3,2
. . 29.2.
.

. 2 9 .2 . Intel


, . L1
.
, ,
. ? ,
,

623

. C++,
, , .
, , ,
. 29.3.


( )


( )

. 2 9 .3 .

,
, , ,
, . ,
,
.


,
, .
,

.


. (thread)
, . m a in ( ) ,
, .
, . ,
, ,
(m ultithreaded application).

624

29.

, ,
, A PI,
.

C++ ,
API ,
.

, API .


. C++
std::thread <thread>.

. ,
, ,
.
C++, Boost
Thread Libraries www.boost.org.


,
. , 1 10 000
A m azon.com . , - A m azon.com
9 999 , - . -
, . -
( , ),

.
-,
, .
(U ser Interface
T hread), ,
, (W orker Thread),
.
. ,
.
,
.
, ,
. , ,
.

625

,
, ,
"
.
. ,
,
. , .
, ,
.

(thread synchronization).


.
.
( ) , . 29.4.


1
1
1
1

r 1
1

1
1

1
! w
1
> float Progress
1
1
1

1 ^

bool Cancel
1
1
1
1
1
1
1
1
1
1
1

4T6Hnew |

"

- 29-4.

,
, , , .
, ,
,
,
.
: ,
. , ?
, .
.
.

21 . 3626

626

29.



,
, .

(sem aphore) (m utex).

. , ,
,
. ,
.
, ,
. , ,
(binary sem aphore).

.
Windows, , ,
.

,
, ,
,
(: ).
, .

(race condition).
. ? ?

(deadlock). ,
. .
. ,
,
:

, .

, ,
. ,
, ,
, .
, .
.
,

C++

627

.
.
, C ++
, .

C++
C ++ ,
, ,
C++.
C ++ .
,
C++.

( ).

, i n t , f l o a t , .

N U LL, ,
new.

.
.

c h a r * , s t r l e n ()
s t r c p y ( ). s t d : : s t r i n g
, , ,
.

,
, . ,
, s t d : : v e c t o r .

, ,
PO D ( ), ,
.

( ) ,
.
,
.

,
,
.

. g e t ()
, , .
, ,
.

.
, .


, .

628

29.

, .
.

, , ,
, ,
o p e r a t o r ^
.

- , ,
o p e r a t o r ( ) ,
, .

new.
, t r y
c a t c h ().

th r o w .

C++
, C++.
, !
C++ . ,
, . , Visual Studio,
intelli-sense , ,
, . !


STL,
, , M SD N ( h t t p : / / m s d n .
m i c r o s o f t . com /), .

STL MSDN
Visual Studio, C++11
Visual Studio 2010.

C + +
++11. , V isual Studio 2010
v a r i a d i c . G C C G N U 4.6
s t d : : t h r e a d .
, C++11
. V isual Studio C++11 Core L anguage Feature
Support , h t t p : / / b l o g s . m s d n . e o m / b / v c b l o g /
a r c h iv e /2 0 1 0 /0 4 /0 6 /c - 0 x - c o r e - la n g u a g e - f e a tu r e s - in - v c l0 - th e - ta b le . aspx,
G CC h t t p : / / g c c . g n u . o r g / p r o j e c t s / c x x O x . h tm l.

629


, C++11.
, .


C ++ . ,
C odeG uru (www. C o d e G u r u . com) C odeProject (www. C o d e P r o j e c t . com),
.
, .
.

C++!
, .
.
,

. .
, ,
C++. , C++
,
, , ,
, , ,
.
C++.


.
?
. .

.

++11 .
?
(V isual C ++ M icro so ft G C C G N U )
+ + 1 1, . ,
C++11 . , a u t o ,
, -
f o r e a c h () .
+ + 11 .

630

29.


, ,
. ,
, .
,
.


1.
. ?
2.
. , .
?

VI

.
. C++
.
.
. ASCII

634


, , 0 -9 .
. 10
, 10.
, 10,
10, .
957 = 9 102 + 5 101 + 7 10 = 9 100 + 5 x 1 0 + 7
957 7 0, 5 1, 9
2. 10, . ,
0 1 ( , 10 , 1000,
1).

10.
1 0 ,1 0 0 ,1 0 0 0 ..,
.


2 .
, 0 1. C++
f a l s e t r u e ( t r u e ).
,
10, 2:
101 () = 1 2 2 + 0 2 1 + 1 2 = 4 + 0 + 1 = 5 ().
, 101 5.

2, 4 ,8 ,1 6 ,3 2
.., .
, .

, . .1,
.
.1. 2

0
1
2
3
4
5

6
7

2 = 1
21 = 2
22 = 4
23 = 8
24 = 16
25 = 32
26 = 64
2 7 = 128

1
10
100
1000
10000
100000
1000000
10000000

635



, .
,
( )
( ).
. . 1 0,
.
, NOT, A N D , O R X O R, 5,
, , (. . 5 .2 -5 .5 ),
,
.


,
. , , ,
1, , 0. .

.
,
8 , , 8 2. ,
2 8 (255) . 255
ASCII.


1 1024 (2 10 ). 1024
1 , 1024 1 . 1024 1 .


16.
0 - 9 A -F . , 10
, 15 F:


()

()

0
1
2
3
4
5
6

0
1
2
3
4
5
6

8
9
10
11
12
13
14

8
9

15

636

,
10, 2,
16:
0x31F = 3 162 + 1 161 + F 16 = 3 256 + 1 6 + 15 () = 799.

".


.
0 1. , , ,
,
. , ,
1111 , F .
,
4 , ,
.

.
8, 0 7.




, ,
.
,
.
.



.
, .
.
,
0.
(breakdow n m ethod).


33 , cai
2 (32):





1: 3 3
2 :1 6
3 :8 /
4: 4 /
5: 2 /
6 :1 /

/ 2 = 16, 1
/ 2 = 8,
2 = 4,
2 = 2,
2 = 1,
2 = 0, 1

3 3 ( ): 1 0 0 0 0 1

156:







1 : 1 5 6 / 2 = 78,
2: 7 8 / 2 = 39,
3: 3 9 / 2 = 19, 1
4 : 1 9 / 2 = 9, 1
5: 9 / 2 = 4, 1
6 : 4 / 2 = 2,
7: 2 / 2 = 1,
9 : 1 / 0 = , 1

1 5 6 : 1 0 0 1 1 1 0 0

|
, ,
16, 2.
5211 :



1: 5 2 1 1 / 1 6 = 3 2 5 , 16 (1 1 10 16)
2: 3 2 5 / 1 6 = 20, 5
3: 2 0 / 1 6 = 1, 4
4 : 1 / 1 6 = 0, 1

5 2 0 5 10 = 1 4 5 16

,
, 27.1 27,
. std:: cout \
,
.
,
std: ibitset, 25, \
STL. !
25.1.


C++

C++. ,
.

. C++
False
Final
Float
For
Friend
goto
if
inline
int
long
long long int
mutable
namespace
new
operator
override
private
protected
public
register
reinterpret_cast
return
short

signed
sizeof
static
staticassert
static_cast
struct
switch
template
this
throw
true
try
typedef
typeid
typename
union
unsigned
using
virtual
void
volatile
wchar_t
while

:
compl
not
not_eq
or

or_eq
xor
xor_eq


, .

, .
, . .1 ,
C++ .

642

.1 .

,
,

,
, ,
new, new [ ] ,delete, delete [ ] ,cast

++

, ,

, , ,

II
V

==

10

AND

&

11

()

++

&

()

()

OR

16

17

V
V
II

15

1
II

11
? :
II

OR

1
&&

II

OR

+
II

!=

14

a n d

12
13

*
II

ing, sizeof

->

II

644

1

1. , (
) .
. C ++
,
, .
2. C++
.
.
, ,
.
3. . .
. . .
.
.

4. + + 11 ,
,
C++. ,

.

1. , .
2. : 2 48 14
3. i o s t r e a m , 1, #.

4. H e llo Buggy W orld

2

1. C ++ . I n t
i n t .
2. .
/* , ,
*/

645

1. C++.
, s t d : : C o u t .
, m a in () i n t .
2. :
#include <iostream>
int main()

{
std::cout
return 0;

"Is there a bug here?"; //

}
3. 2.4 :
##include <iostream>
#using namespace std;
//
int DemoConsoleOutput();
int main()

{
//
DemoConsoleOutput();
return 0;

}
//
int DemoConsoleOutput()

{
cout
cout

"Performing subtraction 10 - 5 = " 10 - 5 endl;


"Performing multiplication 10 * 5 = " 10 * 5 endl;

return 0;

Performing subtraction 10 - 5 = 5
Performing multiplication 10 * 5 = 50

3

1. (
). , ,
.
2. # d e f i n e
.

646

.
.
.

3. , , .
4. 2.
5. .
, .
. ,
. :
int Age = 0;

1. :
enum YOURCARDS { = 43, JACK, QUEEN, KING};
// = 43, JACK = 44, QUEEN = 45, KING = 46
// ..
enum YOURCARDS {ACE, JACK, QUEEN = 45, KING};
// ACE = 0, JACK = 1, QUEEN = 45, a KING = 46

2. 3.4
.
3. , ,
:
#include <iostream>
using namespace std;
int main()

{
const double Pi = 3.1416;
cout "Enter circle's radius: ";
double Radius = 0;
cin Radius;
cout
cout

"Area = " Pi * Radius * Radius endl;


"Circumference = " 2 * Pi * Radius endl;

return 0;

Enter circle's radius: 4


Area = 50.2656
Circumference = 25.1328

4.
, ( ),
:

647

Enter circle's radius: 4


Area = 50
Circumference = 25

5.

a u t o
.
, .

4

1. 0 4
.
2. , ,
, .
3. .
4. , . c o u t ,
, - ,
.
, , .
5. i n t c h a r .
vector<char> DynArrChars (3);

1.

. ROOK (),
, .
int main()

{
enum SQUARE
{
NOTHING = 0,
PAWN,
ROOK,
KNIGHT,
BISHOP,
KING,
QUEEN

};
SQUARE ChessBoard[8] [8] ;
// ,
ChessBoard[0][0] = ChessBoard[0][7] = ROOK;
ChessBoard[7][0] = ChessBoard[7][7] = ROOK;
return 0;

648

2. ,
MyNumbers [ 4 ], .
3.
. .
;
, .

5

1. ,
. f l o a t .
2. , 4.
3. 32.0, 32,
, f l o a t , 4,571.
4. , s i z e o f , .
5. , ,
, 1 + 5 = 6 ,
.
6. X O R f a l s e , . 5.5.

1. :
int Result = ((number

1) + 5)

1; //

2. n u m b er, 7 ,
+ , .
3. , ,
,
.
#include <iostream>
using namespace std;
int main()
{

cout "Enter a boolean value true(l) or false (0): ";


bool Valuel = false;
cin Valuel;
cout "Enter another boolean value true(l) or false (0): ";
bool Value2 = false;
cin Value2;
cout
cout
cout

"Result of bitwise operators on these operands: "


"Bitwise AND: " (Valuel & Value2) endl;
"Bitwise OR: " (Valuel I Value2) << endl;

endl;

6
cout

"Bitwise XOR: "

(Valuel Value2)

649

endl;

return 0;

Enter a boolean value true(l) or false(0): 1


Enter another boolean value true(l) or false (0): 0
Result of bitwise operators on these operands:
Bitwise AND: 0
Bitwise OR: 1
Bitwise XOR: 1

6

1. , ( ),
.
2. , .
3. . 1, .
4. f o r , ,
, c o u t .

1. , ,
:
#include <iostream>
using namespace std;
int main()

{
const int ARRAY_LEN = 5;
int MyNumbers[ARRAY_LEN]= {-55, 45, 9889, 0, 45};
for (int nlndex = ARRAY_LEN - 1; nlndex >= 0; -nlndex)
cout"MyNumbers [" nlndex
"] = "MyNumbers [nlndex] endl;
return 0;

MyNumbers[4]
MyNumbers[3]
MyNumbers[2]
MyNumbers[1]
MyNumbers[0]

=45
= 0
= 9889
=45
= -55

650

2. , 6.13,
, :
#include <iostream>
using namespace std;
int main()
{

const int ARRAY1_LEN = 3;


const int ARRAY2_LEN = 2;
int Mylntsl[ARRAY1_LEN] = {35, -3, 0};
int Mylnts2[ARRAY2_LEN] = {20, -1};
cout

"Adding each int in Mylntsl by each in Mylnts2:"

endl;

for (int ArraylIndex=ARRAYl_LEN-l;ArraylIndex>=0; ArraylIndex)


for(int Array2Index=ARRAY2_LEN-l;Array2Index>=0; Array2Index)
coutMyIntsl [Arrayllndex]" + "Mylnts2 [Array2Index] \
" = " Mylntsl[Arrayllndex] + Mylnts2[Array2Index]
endl;
return 0;

;
Adding each int in Mylntsl by each in Mylnts2:
0 + -1 = -1
0 + 20 = 20
-3 + -1 = -4
-3 + 20 = 17
35 + -1 = 34
35 + 20 = 55

3. 5 ,
:
cout "How many Fibonacci numbers you wish to calculate: ";
int NumsToCal = 0;
cin NumsToCal;

4. s w i t c h - c a s e ,
, , :
#include <iostream>
using namespace std;
int main()

{
enum COLORS
{
VIOLET = 0,
INDIGO,
BLUE,
GREEN,
YELLOW,

6
ORANGE,
RED,
CRIMSON,
BEIGE,
BROWN,
PEACH,
PINK,
WHITE,

};
cout
cout
cout
cout
cout
cout
cout
cout
cout
cout
cout
cout
cout
cout

"Here are the available colors: "


"Violet: " VIOLET endl;
"Indigo: " INDIGO endl;
"Blue: " BLUE endl;
"Green: " GREEN endl;
"Yellow: " YELLOW endl;
"Orange: " ORANGE endl;
"Red: " RED endl;
"Crimson: " CRIMSON endl;
"Beige: " BEIGE endl;
"Brown: " BROWN endl;
"Peach: " PEACH endl;
"Pink: " PINK endl;
"White: " WHITE endl;

endl;

cout "Choose one by entering code: ";


int YourChoice = BLUE; //
cin YourChoice;
switch (YourChoice)

{
case
case
case
case
case
case
case

VIOLET:
INDIGO:
BLUE:
GREEN:
YELLOW:
ORANGE:
RED:
cout "Bingo, your choice is a Rainbow color!"
break;

default:
cout
break;

endl;

"The color you chose is not in the rainbow"

}
return 0;

Here are the available colors:


Violet: 0
Indigo: 1
Blue: 2
Green: 3

endl;

651

652

.
Yellow: 4
Orange: 5
RED: 6
Crimson: 7
Beige: 8
Brown: 9
Peach: 10
Pink: 11
White: 12
Choose one by entering code: 4
Bingo, your choice is a Rainbow color!

5. f o r
10 , .
6. w h i l e ' ; ' .
L o o p C o u n te r
, , ,
.
7. b r e a k (.. d e f a u l t ,
c a s e , ).

7

1. .
2. SomeNumber .
.
3. .
4. .
5. ! ; , , ,
.

1. :
double Area (double Radius);
//
double Area (double Radius, double Height); //

() ,
, .
2.

7 .8 .

v o id P ro c e s s A rra y (d o u b le Numbers[],

i n t L e n g th );

3. , R e s u lt A re a :
v o id A re a (d o u b le R a d iu s ,

d ou b le & Result)

4. ,
.

653

8
5.


v o id

A re a

( d o u b le R a d i u s ,

d o u b le

& A re a ,

d o u b le

{ . C ir c u m f e r e n c e )

Area = 3.14 * Radius * Radius;


Circumference = 2 * 3.14 * Radius;

8

1. ,
, : .
2. .
3. .
4. (*).

1. 40.
2. .
, ,
. ,
.
.
3. c o n s t :
1: const int* pNuml = SNumber;

4. (..
):
*pNumber = 9; // : pNumber = 9;

5. ,
new p N u m b e r p N u m b e r .
d e l e t e .
6. 30.

9

1. . ,
i n t new.
2. s i z e o f () .
, , ,
-, .

654

3. , .
4. , .
5. -
.
6. .

1. C ++ .
c l a s s , C l a s s . ( ; ) ,
.
class Human
{
int Age;
string Name;
public:
Human () {}

2. - Human: : Age ( , ,
, )
, ,
.
3. Human :
class Human
{
int Age;
string Name;
public:
Human(string InputName, int InputAge)
: Name(InputName), Age(InputAge) {}

4. : ,
:
tinclude <iostream>
using namespace std;
class Circle
{
const double Pi;
double Radius;
public:
Circle (double InputRadius) : Radius(InputRadius), Pi (3.1416) {}
double GetCircumference()

{
return 2*Pi*Radius;

10

655

double GetArea()

{
return Pi*Radius*Radius;

}
};
int main()

{
cout "Enter a radius: ";
double Radius = 0;
cin Radius;
Circle MyCircle(Radius);
cout
cout

"Circumference = " MyCircle.GetCircumference()


"Area = " MyCircle.GetArea() endl;

endl;

return 0;

10

1. p r o t e c t e d .
, .
2. , , , ,
, .
.
3. .
4. .
5. , , B a s e , ..
D e r iv e d , B a s e . ,
B a s e S u b D e r iv e d ,
, .

1. : M am m al - B i r d - R e p t i l e P l a t y p u s . .
.
#include <iostream>
using namespace std;
class Mammal
{
public:
void FeedBabyMilk()

{
cout

"Mammal: Baby says glug!"

endl;

656

.
}
Mammal()

{
cout

"Mammal: Contructor"

endl;

"Mammal: Destructor"

endl;

}
-Mammal()

{
cout

}
};
class Reptile

{
public:
void SpitVenomO

{
cout

"Reptile: Shoo enemy! Spits venom!"

endl;

}
Reptile()

{
cout

"Reptile: Contructor"

endl;

"Reptile: Destructor"

endl;

}
-Reptile()

{
cout

}
};
class Bird

{
public:
void LayEggs()

{
cout

"Bird: Laid my eggs, am lighter now!"

endl;

}
BirdO

{
cout

"Bird: Contructor"

endl;

"Bird: Destructor"

endl;

}
-BirdO

{
cout

}
};
class Platypus: public Mammal, public Bird, public Reptile

{
public:
Platypus()

{
cout

"Platypus: Contructor"

endl;

"Platypus: Destructor"

endl;

}
-Platypus()

{
cout

11

657

int main()

{
Platypus realFreak;
//realFreak.LayEggs();
//realFreak.FeedBabyMilk();
//realFreak.SpitVenomO ;
return 0;

2. :
class Shape
{
// ... Shape

};
class Polygon: public Shape
{
// ... Polygon

}
class Triangle: public Polygon
{
// ... Triangle

}
3. D1 B a s e .
4. . D e r iv e d ,
.
5. S om eF unc () B a s e .
, ,
:
Derived objectDerived;
SomeFunc(objectDerived); //

11

1. S h ap e A re a ()
P r i n t ( ), C i r c l e T r i a n g l e .
2. . ,
, .
3. , .
, ,

.

22 . 3626

658

1.

S h a p e
C i r c l e T r i a n g l e .
#include<iostream>
using namespace std;
class Shape

{
public:
virtual double AreaO = 0;
virtual void Print() = 0;

class Circle

{
double Radius;
public:
Circle(double inputRadius) : Radius(inputRadius) {}
double Area()

{
return 3.1415 * Radius * Radius;

}
void Print()

{
cout

"Circle says hello!"

endl;

class Triangle

{
double Base, Height;
public:
Triangle(double inputBase, double inputHeight) : Base(inputBase),
Height(inputHeight) {}
double AreaO

{
return 0.5 * Base * Height;

}
void Print()

{
cout

"Triangle says hello!"

}
};
int main()

{
Circle myRing(5);
Triangle myWarningTriangle(6.6, 2);

endl;

12
cout
cout

"Area of circle: " myRing.Area() endl;


"Area of triangle: " myWarningTriangle.Area()

659

endl;

myRing.Print();
myWarningTriangle.Print();
return 0;

}
2. !
3.
: V e h i c l e ( ) , ( ) ,
- ().

12

1. , C++
. [ ]
,
, . C ++
, ,
:
& operator[](int Index) const;
Type& operator[](int Index);

2. , ,
.
3. ,
D a te ,

,
.

1. i n t ().
class Date
{
int Day, Month, Year;
public:
operator int()

{
return ((Year * 10000) + (Month * 100) + Day);

}
// .

660
2.

.

.
class Dynlntegers

{
private:
int* plntegers;
public:
//
Dynlntegers(Dynlntegers&& MoveSource)

{
plntegers = MoveSource.plntegers; //
MoveSource.plntegers = NULL; //
//

//
Dynlntegers& operator= (Dynlntegers&& MoveSource)

{
if (this != SMoveSource)

{
delete [] plntegers; //
plntegers = MoveSource.plntegers;
MoveSource.plntegers = NULL;
}

return *this;
}

-Dynlntegers() {delete[] plntegers;} //


// ,
// ,

13

1. dy n am i _ s t .
2. , . c o n s t c a s t
.
3. .
4. , .

1.
:
void DoSomething(Base* pBase)

{
Derived* pDerived = dynamic_cast <Derived*>(pBase);

14

661

if(pDerived) //
pDerived->DerivedClassMethod();
}

2. s t a t i c c a s t , ,
T una. 13.1,
m a in ():
int main()
{

Fish* pFish = new Tuna;


Tuna* pTuna = static_cast<Tuna*>(pFish);
// Tuna::BecomeDinner
// Tuna*
pTuna->BecomeDinner();
// Fish ~Tuna()
delete pFish;
return 0;

14

1. ,
.
2. 4.
3.

1 0 + 1 0 / 5 = 10 + 2 = 1 2 .

4. :
#define SPLIT() (() / 5)

1. :
#define MULTIPLY(a,b)

(()* (b))

2. , 4:
template<typename > Split(const & input)
{

return (input / 5);

}
3. sw ap () :
template <typename >
void Swap (T& x, T& )

662

.
temp = ;
= ;
= temp;

}
4. # d e f i n e QUARTER()

( ( ) / 4)

5. :
template ctypename ArraylType, typename Array2Type>
class TwoArrays
{
private:
ArraylType Arrayl [10];
Array2Type Array2 [10];
public:
ArraylType& GetArraylElement(int Index){return Arrayl[Index];}
Array2Type& GetArray2Element(int Index){return Array2[Index];}

15

1. d e q u e .
.
2. s t d : : s e t s t d : :m ap, - .
, s t d : : m u l t i s e t
s t d : :multimap.
3. . s t d : : s e t ,
, , s e t
.
.
4. , (
) ,
( ) .
5. h a s h _ s e t C++.
,
std::m ap.

15

1. s t d : : b a s i c _ s t r i n g <>
2. .
.
.

16
3.

663

, . ,
, STL
s t r i n g , -
, , .

1. s t d : : r e v e r s e ():
#include <string>
#include <iostream>
#include <algorithm>
int main ()

{
using namespace std;
cout "Please enter a word for palindrome-check:"
string strlnput;
cin strlnput;

endl;

string strCopy (strlnput);


reverse (strCopy.begin (), strCopy.end ());
if (strCopy == strlnput)
cout strlnput " is a palindrome!" endl;
else
cout strlnput " is not a palindrome." endl;
return 0;

}
2. s t d : : f i n d ():
#include <string>
#include <iostream>
using namespace std;
// 'chToFind' "strlnput"
int GetNumCharacters (strings strlnput, char chToFind)

{
int nNumCharactersFound = 0;
size_t nCharOffset = strlnput.find (chToFind);
while (nCharOffset != string::npos)

{
++ nNumCharactersFound;
nCharOffset = strlnput.find (chToFind, nCharOffset + 1);

}
return nNumCharactersFound;

664


int main ()

{
cout "Please enter a string:"
string strlnput;
getline (cin, strlnput);

endl

"> ";

int nNumVowels = GetNumCharacters (strlnput, 'a');


nNumVowels += GetNumCharacters (strlnput, 'e);
nNumVowels += GetNumCharacters (strlnput, 'i *);
nNumVowels += GetNumCharacters (strlnput, o );
nNumVowels += GetNumCharacters (strlnput, 'u');
// DIY: ..
cout

"The number of vowels in that sentence is: "

nNumVowels

return 0;

}
3. t o u p p e r ():
#include <string>
#include <iostream>
#include <algorithm>
int main ()

{
using namespace std;
cout
cout

"Please enter a string for case-conversion:"


"> ";

endl;

string strlnput;
getline (cin, strlnput);
cout endl;
for ( size_t nCharlndex = 0
; nCharlndex < strlnput.length ()
; nCharlndex += 2)
strlnput [nCharlndex] = toupper (strlnput [nCharlndex]);
cout
cout

"The string converted to upper case is: "


strlnput endl endl;

return 0;

}
4. :
#include <string>
#include <iostream>
int main ()

{
using namespace std;

endl;

17
const
const
const
const

string
string
string
string

strl
str2
str3
str4

=
=
=
=

665

"I";
"Love";
"STL";
"String.";

string strResult = strl + " " + str2 + " " + str3 + " " + str4;
cout
cout

"The sentence reads:"


strResult;

endl;

return 0;

17

1. , .
.
2. 10. 11- .
3. ; .. .
4. CM am m al.
5.

( [ ]) a t ().

6. .

1. :
#include <vector>
#include <iostream>
using namespace std;
char DisplayOptions ()

{
cout
cout
cout
cout
cout

"What would you like to do?" endl ;


"Select 1: To enter an integer" endl;
"Select 2: Query a value given ,
an index" endl;
"Select 3: To display the vector" endl "> "
"Select 4: To quit!" endl 11^ II.

char ch;
cin ch;
return ch;
main 0

{
vector <int> vecData;

666

.
char chUserChoice = '\0f;
while ((chUserChoice = DisplayOptions ()) != '4')

{
if (chUserChoice == '1')

{
cout "Please enter an integer to be inserted: ";
int nDatalnput = 0;
cin nDatalnput;
vecData.push_back (nDatalnput);

}
else if (chUserChoice == '2')

{
cout "Please enter an index between 0 and ";
cout (vecData.size () - 1) ": ";
int nIndex = 0;
cin nlndex;
if (nlndex < (vecData.size ()))

{
cout"Element ["<<nlndex"] = "vecData [nlndex] ;
cout endl;

}
}
else if (chUserChoice == '3')

{
cout "The contents of the vector are: ";
for (size_t nlndex = 0; nlndex < vecData.size (); ++ nlndex)
cout vecData [nlndex] ' ';
cout endl;

}
return 0;

}
2. s t d : : f i n d ():
vector <int>::iterator iElementFound = std::find (vecData.begin (),
vecData.end (), nDatalnput);

3. 1,
.

18

1. ,
.
.
2. ,
.

18
3. m L i s t . c l e a r

m L ist.erase

667

();
(m L ist.b e g i n (),

m L ist.e n d ());

4. , i n s e r t ()
.

1. , 1 17 .
:
mList.insert(mList.begin(), nDatalnput);

2. . ,
. ,
, .
3. :
#include <vector>
#include <list>
#include <iostream>
using namespace std;
int main ()

{
vector <int> vecData (4);
vecData [0] = 0;
vecData [1] = 10;
vecData [2] =20;
vecData [3] = 30;
list <int> listlntegers;
//
listlntegers.insert (listlntegers.begin (),
vecData.begin (), vecData.end());
cout

"The contents of the list are: ";

list <int>::const_iterator iElement;


for ( iElement = listlntegers.begin ()
; iElement != listlntegers.end ()
; ++ iElement)
cout *iElement " ";
return 0;

};
4. .
#include <list>
#include <string>
#include <iostream>

668

.
using namespace std;
int main ()

{
list <string> listNames;
listNames.push_back ("Jack");
listNames.push_back ("John");
listNames.push_back ("Anna");
listNames.push_back ("Skate");
cout

"The contents of the list are: ";

list <string>::const_iterator iElement;


for (iElement = listNames.begin(); iElement!=listNames.end();
++iElement)
cout *iElement " ";
cout endl;
cout "The contents after \reversing are: ";
listNames.reverse ();
for (iElement = listNames.begin(); iElement!=listNames.end();
++iElement)
cout *iElement " ";
cout endl;
cout "The contents after sorting are: ";
listNames.sort () ;
for (iElement = listNames.begin(); iElement!=listNames.end();
++iElement)
cout *iElement " ";
cout endl;
return 0;

19

1. s t d : : l e s s o ,
o p e r a t o r <
t r u e , .
2. , .
3. STL s i z e ().

1. :
struct FindContactGivenNumber

{
bool operator () (const CContactItem& lsh,

19
const CContactltemS rsh) const

{
return (lsh.strPhoneNumber < rsh.strPhoneNumber);

}
2. :
#include <set>
#include <iostream>
#include <string>
using namespace std;
struct PAIR_WORD_MEANING

{
string strWord;
string strMeaning;
PAIR_WORD_MEANING (const strings sWord, const strings sMeaning)
: strWord (sWord), strMeaning (sMeaning) {}
bool operator< (const PAIR_WORD_MEANINGS pairAnotherWord) const
{
return (strWord < pairAnotherWord.strWord);

}
};
int main ()

{
multiset <PAIR_WORD_MEANING> msetDictionary;
PAIR_WORD_MEANING wordl ("C++", "A programming language");
PAIR_WORD_MEANING word2 ("Programmer", "A geek!");
msetDictionary.insert (wordl);
msetDictionary.insert (word2);
return 0;

}
3. .
include <set>
include <iostream>
using namespace std;
template ctypename T>
void DisplayContent (const TS sequence)
{
T::const iterator iElement;
for (iElement = sequence.begin(); iElement!=sequence.end();
++iElement)
cout *iElement " ";

}
int main ()

669

Вам также может понравиться