Академический Документы
Профессиональный Документы
Культура Документы
21
S a m s T e a c h Y o u rs e lf
C++
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:
#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
:|include <iostream>
-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
Solution Explorer
__
. 1.1. C++ 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;
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:
main()
() ,
m a in (). C++ .
, m a in () i n t . i n t
m a in ().
program.exe /DoSomethingSpecific
/DoSomethingSpecific - ,
main ().
8, !
std::cout << "Hello World" << std::endl;
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
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;
}
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
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:
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;
InputNumber
endl;
21:
22:
23: }
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) ,
,
.
.
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
12
13
14
15
16
17
18
// ,
int MultiplicationResult = FirstNumber * SecondNumber;
19
//
cout FirstNumber " x " SecondNumber;
cout " = " MultiplicationResult endl;
20
21
22
23
24
return 0;
,
. ,
. 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
// ,
MultiplyNumbers();
// cout
// cout
return 0;
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. ,
( ).
, 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:
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
// ,
MultiplyNumbers();
cout
"Displayingfrom
main(): ";
// !
cout FirstNumber " " SecondNumber;
cout " = " MultiplicationResult endl;
return 0;
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
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- .
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:
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
cout
return 0;
,
.
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
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;
, . ,
.
, .
:
= 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;
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
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
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: }
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
:
int MyNumbers
[5] = {100}; //
// 100
:
int MyNumbers
(.. )
:
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 -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.
6 ,
. ,
c o u t MyNumbers
.
,
, 4.1
, .
.
.
, 2011 :
int AnlntegerValue;
AnlntegerValue = 2011;
2011 :
MyNumbers
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
return 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
{3, 4, 5}};
,
. : ,
, . ,
:
int ThreeRowsThreeColumns
{303, 456, 596}};
, C++
, .
,
.
SolarPanellDs ,
:
.
, ,
, ,
, .
, ,
, ,
.
:
int ThreeRowsThreeColumns
{303, 456, 596}};
, ,
.
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: "
ft " \
vv " \
endl;
VI " \
If " \
endl;
"Row 2: "
IV "\
VI " \
endl;
cout
cout
return 0;
}
,
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:
9:
10:
11:
DynArrNums[0] = 365;
DynArrNums[1] = -421;
DynArrNums[2]= 789;
12:
13:
cout
14:
15:
16:
17:
18:
19:
20:
DynArrNums.size()
21:
22:
23:
24:
25: }
cout
cout
cout
endl;
return 0;
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;
: ' \ 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
11
12
13
14
15
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
endl;
6:
7:
8:
9:
10:
= {'\0 '};
strlen (Userlnput)
11:
12:
13: }
return 0;
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
{
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;
21
22
23
24
endl;
4.
86
25:
26:
27:
28:
29:
30: }
cout
cout
endl;
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
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;
, ,
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:
12:
13:
14: }
return 0;
,
.
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
// 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;
11
12
Equality
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
endl;
Inequality
endl;
Num2
Num2;
endl;
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
97
98
5. ,
Result
Result
Result
Result
of
of
of
of
101
101
101
101
.
, . ==,
>= <= .
, ,
, , .
6,
.
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.
#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
endl;
endl;
endl;
100
12:
13:
14: }
5. ,
return 0;
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 (!)
4: {
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
endl;
101
22:
23:
24:
25:
26:
27: }
eridl;
return 0;
:
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? 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 .
103
OR | , AND
& XOR .
).
, ,
, , . ,
32 32- .
5.8.
5.8.
{
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;
01001010
endl;
104
5. ,
( 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
Half = Input 1;
Quarter = Input 2;
Double = Input 1;
Quadruple = Input 2;
cout
cout
cout
cout
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 -= Num2 ;
Numl *= Num2;
Numl /= Num2 ;
Numl %= Num2 ;
Numl = = Num2;
Numl = Num *
Num2 ;
Numl = = Num2;
Numl = Num :
Num2 ;
Numl 1= Num2 ;
Numl A= Num2;
5.10.
5.10. ,
#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
(Value |= 0x55)
endl
15:
16:
cout
cout
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;
, 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. ,
, .
.
, .
, :
,
;
, 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
endl;
21:
22:
23: }
return 0;
:
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;
6.2.
0
1
2
#include <iostream>
#include <string>
using namespace std;
3
4
5
6
7
int main()
{
char Buffer[20] = {\0*};
10
11
12
13
14
15
16
17
18
19
endl;
strcpy(Buffer, LineEntered.c_str());
cout "Buffer contains: " Buffer
}
return 0;
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
endl;
if...else
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
else
cout
endl;
}
else
{
cout "You want multiplication!" endl;
cout Numl " x " Num2 " = " Numl * Num2
endl;
29:
30:
31:
32: }
}
return 0;
:
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.
. ,
. 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
121
endl;
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): 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
{
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;
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): 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:
endl;
_4:
return
0;
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"
" +"
cin
127
Repeat;
1:
19:
12:
if (Repeat == '')
goto JumpToPoint;
12:
cout
24:
return 0;
"Goodbye!"
endl;
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:
9:
10:
11:
12:
13:
14:
cout
15:
16:
17:
18:
19:
20:
21:
22:
23:
24: }
Numl
endl;
Numl
endl;
endl;
" x "
Num2
" = "
Numl * Num2
" + "
Num2
" = "
Numl + Num2
"Goodbye!"
return 0;
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
17:
18:
19:
20:
cout
"Goodbye!"
endl;
21:
22:
23: }
return 0;
m
Enter the two integers:
909
101
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:
II:
II:
12:
13:
ARRAY_LENGTH
" integers"
Arraylndex
": ";
132
6.
16:
17:
18:
19:
20:
21:
22:
cout
endl;
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
I d:
16:
Numl
endl;
Numl
endl;
endl;
" x "
Num2
" = "
Numl * Num2
" + "
Num2
" = "
Numl + Num2
19
1j
cout
12:
return 0;
"Goodbye!"
endl;
13: }
m
Enter
789
-3 6
789 x
789 +
Press
-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
:
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: }
"Goodbye!"
return 0;
endl;
continue break
137
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
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
" ";
do
15
16
17
cout
13
19
:i
12
26
27
28
29
30
31
" ";
10
13
34
25
Numl + Num2
"Goodbye!"
endl;
return 0;
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 .
, ,
. ,
, .
,
.
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:
// "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.
(),
,
(),
. 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
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
1~:
cout
12:
return 0;
SurfaceArea(InRadius, InHeight)
22: }
12: double SurfaceArea(double Radius, double Height)
23: {
14:
15:
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:
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:
";
12:
13:
14:
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: }
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: }
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 (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, 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:
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
:
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: }
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:
endl;
11: }
12:
20:
21:
DisplayNums(MyNumbers);
23:
24:
25:
26:
27:
28:
29:
30:
31: }
cout
22:
endl;
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 ,
.
// &
cout "Integer Age is at: Ox" hex &Age endl;
cout "Double Pi is located at: Ox" hex &Pi endl;
12:
33: }
return 0;
, (&) 9 10
P i.
, .
, , ,
. sizeof () 3.4 ,
4 (
). ,
,
0x0045FE08, , sizeof (int) 4 ,
, , 0x0045FE000x0045FE04, .
170
8.
, , ,
, .
,
(&).
:
//
= ;
,
, (&):
//
* = &;
, 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: }
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:
6:
7:
8:
9:
10:
11:
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
, 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
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
cout
cout
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
DogsAge
endl;
7
8
10
11
cout
endl;
174
8.
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22: }
// ,
cin *;
// ,
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 = Π
char* pChar = &SayYes;
cout
cout
cout
cout
cout
cout
cout
cout
return 0;
, , 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: }
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.
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: }
179
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
11
12
13
14
15
16
17
18
19
20
21
{
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? 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:
12: {
14:
I.':
I:
II:
II:
double Area = 0;
CalcArea (&Pi, &Radius, &Area);
12:
cout
15:
return 0;
"Area
is = " Area
endl;
I-': }
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;
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.
,
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: }
*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: {
::
:
190
8.
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
// ()
int* pTemperature = new int;
*pTemperature = 30;
cout
// ?
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: }
-.
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).
#include <iostream>
using namespace std;
int main()
{
// nothrow
int* pAge = new(nothrow) int [Oxlfffffff];
6
7
11
13
else
10
12
}
cout
14
15
return 0;
16
17
endl;
193
, 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:
&Original
5:
'.I:
_i:
15:
14:
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:
::
::
ReturnSquare(Number);
cout "Square is: "
::
Number
endl;
return 0;
, , 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.
, 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:
12:
13:
207
Name = HumansName;
14:
16:
l7:
13:
19:
Age = HumansAge;
11:
void IntroduceSelf()
22:
13:
14:
15:
16: };
cout
cout
39 :
40:
41:
42: }
FirstMan.IntroduceSelf() ;
FirstWoman.IntroduceSelf();
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.
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
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 IntroduceSelf()
endl;
213
{
1:
2:
cout
cout
2:
4: };
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();
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:
endl;
{
22:
22:
Name = HumansName;
41:
61 :
42:
Age = HumansAge;
64:
46:
void IntroduceSelf()
4~:
42:
42:
:3 :
cout
cout
53
59
60
61
62
63
64
65
66
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:
:::
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
:
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
}
// ...
};
, ( : ) , ( . . . ) ,
- .
, 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;
}
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:
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()
{
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
SayHello.GetString()
endl;
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.
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();
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); //
{
//
}
,
. ,
(
), 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
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;
" Input.GetLength();
Input.GetString()
endl;
}
int main()
{
MyString SayHello("Hello from StringClass");
// SayHello ( )
UseMyString(SayHello);
return 0;
}
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,
,
++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:
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:
endl;
54:
return 0;
55:
56:
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:
//
//
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
}
.
, ,
, , 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.
{
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
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
{
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
240
76:
77:
78:
79:
80:
9.
Human FirstMaleHuman(FirstMan, 25, true);
Human FirstFemaleHuman(FirstWoman, 18, false);
cout
cout
cout <<
<<
81:
82:
83:
84: }
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:
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;
}
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:
3::
return 0;
31: }
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
)
)
( )
B i r d ()
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).
, ,
, ( ), , ,
. , 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;
}
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:
11:
45:
46:
cout "Dinner:
myDinner.Swim();
return 0;
";
endl;
251
252
10.
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:
}
};
19: {
2 5: public:
21:
Tuna()
22:
22:
24:
FreshWaterFish = false; //
//
}
28:
29:
Carp myLunch;
Tuna myDinner;
42:
cout
43:
44:
46:
4":
cout "Dinner:
myDinner.Swim();
"Getting
my food to swim"
endl;
";
// ,
//
// myLunch.FreshWaterFish = false;
52
53
return 0;
253
254
10.
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)
{}
public:
Carp() : Fish(true)
};
{}
2 2: int main()
:4: {
25:
Carp myLunch;
26:
Tuna myDinner;
cout
*]:
-1:
-2:
-4:
cout "Dinner:
myDinner.Swim();
*5:
:2:
-1: }
endl;
";
// 48,
//
// myLunch.FreshWaterFish = false;
return 0;
256
10.
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()
{
// ...
{
// ...
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.
{
:: 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
{}
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
}
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
endl;
261
,
, T u n a : : Swim ()
F i s h : : Swim ( ) , ,
( (hidden)), 10.6.
4: {
:: public:
i:
void Swim()
{
::
cout
"Fish swims...
!"
endl;
{
if (FreshWaterFish)
cout "Swims in lake" endl;
else
cout "Swims in sea" endl;
:i:
.1: public:
void Swim()
{
cout
endl;
int main()
{
Tuna myDinner;
cout
endl;
// myDinner.Swim(false); // : Fish::Swim(bool)
/ / Tuna::Swim()
myDinner.Swim();
return 0;
262
10.
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
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
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"
}
};
"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:
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.10.
, , ________________
0:
1:
2:
3:
4:
5:
6:
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
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;
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:
279
// 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.
#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;
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
52
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;
44:
45:
46: }
return 0;
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:
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;
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
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: }
( ) 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 ( ) ,
.
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: }
( ) 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;
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.) .
,
, .
,
?
.
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 ;
//
{
// ...
public:
Tuna * Clone() const //
{
return new Tuna(*this); // Tuna,
//
, C lo n e ()
, , 11.9.
#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
public:
Fish* Clone()
{
return new Tuna (*this);
}
void Swim()
{
cout
}
};
endl;
297
void Swim ()
{
cout
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 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: }
16-27
D a te ,
44, 51 52 m a in ( ) .
, .
, ,
(++) ( ). , 30 ,
.
D a te :
//
//
306
12.
{
// ,
//
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
, 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.
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 :
(*)
(->)
(*) (-> )
.
(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.
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
.
#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
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 " / "
*pDynamicInt;
53
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
";
();
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.
#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
,
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
{
}
bool
{
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;
(==) ,
, , , 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.
{// }
:
if (Datel <= Date2)
{// }
:
if (Datel > Date2)
{// }
:
if (greatDay >= Date2)
{// }
,
, ,
. ,
, , 12.8.
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
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);
{
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
endl;
endl;
endl;
321
322
12.
82:
cout
83:
84:
85:
endl^-
eS:
87:
return 0;
88:
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 != ©Source) //
{
//
}
return *this;
323
, , ,
M y S tr in g , 9.9.
, ,
, c h a r * B u f f e r , ,
, . ,
.
, , 12.9.
#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
: 6: {
53:
:9:
cl:
t2 :
-3:
t'4:
-5:
~6:
endl;
il:
t8:
i9 :
"9:
1:
"2:
"3:
~4:
"5: }
, , 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,
, :
,
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;
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 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;
{
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
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
.. ., !
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
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
}
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;
endl;
C++
70:
71:
72:
73:}
345
DetectFishType(&myLunch);
return 0;
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.
,
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 ,
.
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
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 :
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
int main()
{
SQUARE(Input1) endl;
" Inputl " is:
") = ";
") = ";
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
endl;
, ,
:
cout
: (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);
{
//.
. .
{
//
. . .
}
. , :
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
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
: 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
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
{
Valuel = valuel;
Value2 = value2;
12:
13:
14:
15:
16:
17:
18:
19:
20:
};
//
const T1 & GetFirstValue () const
{
return Valuel;
};
21:
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.
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;
return 0;
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.
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:
public:
EverythingButlnt()
{
static_assert(sizeof(T)
}
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 : : 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:
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);
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:
22:
23:
24:
35:
26:
// ,
if (iElement != vecIntegerArray.end ())
23:
385
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;
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:
. ,
C++11, :
20:
, , 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
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 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;
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25: }
<< 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;
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 :
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;
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:
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:
STL
17:
18:
19:
20:
else
cout
cout
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;
endl;
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;
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:
, 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
11
12
13
14
15
cout
cout
. . .
endl;
STL
401
16 :
17:
return 0;
-8: }
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
:
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;
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: }
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
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
{
cout
cout
}
// 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
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;
:
21
22
23
24
25
26
veclntegers.size ()
27
28
29
//
veclntegers.pop_back ();
30
31
32
33
34
35
36
, p o p _ b a c k ( ) , 29,
, . 32
s i z e () ,
, .
416
17. STL
(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
endl;
12:
13:
14:
15:
16:
17:
18:
19:
cout
veclntegers.capacity ()
417
endl;
// 6-
veclntegers.push_back (666);
cout
cout
cout
endl;
endl;
20:
21:
22:
23:
24:
25:
26:
27:
28:
29: }
//
veclntegers.push_back (777);
cout
cout
cout
endl;
endl;
return 0;
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
//
for ( size_t nCount = 0
; nCount < dqlntegers.size ()
; ++ nCount )
{
cout
cout
} '
cout
endl;
//
dqlntegers.pop_front ();
23
29
//
dqlntegers.pop_back ();
4z
cout
cout
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:
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)
{
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 ()
, .
{
for (T::const_iterator iElement = Input.begin ()
; iElement != Input.end ()
; ++ iElement )
cout *iElement '
cout endl;
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)
{
11:
12:
13: }
14:
15: int
16: {
17:
18
19
20
cout
endl;
main ()
list <int> listlntegersl;
// ...
listlntegersl.insert (listlntegersl.begin (), 2);
429
// 4 0...
Iistlntegers2.insert (listlntegers2.begin (), 4, 0) ;
22
23
24
25
26
2*7
28
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
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
list 2
list 3
list 3
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)
{
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
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;
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
{
for(auto
;
;
cout
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;
endl;
listlntegers.reverse();
cout "Contents of the list after using reverse():"
DisplayContents(listlntegers);
return 0;
endl;
433
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:
13:
14:
15:
16:
17:
434
18:
19: }
18. STL
cout
endl;
20:
.
. 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:
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: }
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)
{
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 :
.
#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 :
445
, 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
};
,
,
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, ,
.
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:
6:
7:
8:
9:
10:
#include <set>
#include <iostream>
using namespace std;
for(auto
;
;
cout
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
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 ()
:
{
for (T::const_iterator iElement = Input.begin () //
; iElement != Input.end ()
; ++ iElement )
cout *iElement '
cout endl;
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
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)
for(auto
;
;
cout
.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
//
DisplayContents(msetlntegers);
cout "Please enter a number to be erased from the set"
endl;
int nNumberToErase = 0;
cin nNumberToErase;
cout
cout
//
msetlntegers.erase (nNumberToErase);
cout "multiset contains " msetlntegers.size ()
" elements.";
cout " These are: " endl;
DisplayContents(msetlntegers);
return 0;
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;
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
endl;
return 0;
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 .
#include<unordered_set>
#include <iostream>
using namespace std;
template ctypename T>
void DisplayContents(const T& Input)
{
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: }
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;
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)
,
.
.
, .
-.
462
20. STL
STL
m u ltim a p - ,
, . 20.1.
. 20.1. ,
( ) (m u ltim a p ) ,
, .
, m u ltim a p STL
. , ,
, . ,
, ,
. , ,
.
#include<map>
463
std: :
std: :multixnap STL
-
m u ltim a p STL, .
, .
, ,
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:
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 , ,
.
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;
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 ()
:
{
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
,
f i n d ():
if (iPairFound != mapIntToString.end())
{
cout
cout
cout
}
else
Key
endl;
, C++11,
auto:
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
cout
469
endl;
//
DisplayContents(mapIntToString);
cout "Enter the key you wish tofind:
int Key = 0;
cin Key;
";
43:
44:
45: }
return 0;
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
++ iPairFound;
}
else
cout
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 ().
#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;
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
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()
79:
80:
81:
82:
83:
84:}
cout
cout
475
strNameInput
s number was not found ";
"in the case-sensitive directory" endl;
}
return 0;
> 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
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;
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:
479
else
cout
50:
51:
52: }
return 0;
, 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
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
{
cout << element << ' ';
}
};
, DisplayElement - .
, operator ()
public. ,
.
STL f o r _
each, , ,
21.1.
2 1 .1 .
_____________________________
0
1
3
#include
#include
#include
#include
4
5
<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
element
' ';
}
};
int main
()
{
vector <int> veclntegers;
20
21
22
23
24
25
26
27
28
29
30
31
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:
//
for_each ( listChars.begin () //
, listChars.end ()
//
, DisplayElement <char> () ); //
return 0;
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
{
++ 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.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
// ,
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 ()
{
veclntegers.push_back (nCount);
cout << nCount << ' ';
}
cout << endl << "Enter divisor
int Divisor = 2 ;
cin >> Divisor;
// , 4
auto iElement = find_if (veclntegers.begin ()
, veclntegers.end ()
, IsMultiple<int>(Divisor) );
492
24:
25:
26:
27:
28:
29:
30:
31:
32: }
21.
0;
. 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
{
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
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
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
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
, 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
{
for(auto
;
;
cout
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
()
"
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
8: {
9:
<algorithm>
<iostream>
<vector>
<list>
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27
28
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;
- 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;
- , , 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 ;
/ /
- - 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 ;
/ / ,
-
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33: }
505
0;
- , ,
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 tateV arl,
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
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
- 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
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;
{
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
- , 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
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
endl;
30:
31:
32:
33:
34:
35:
if
{
36:
37:
38:
39:
40:
41: }
cout
cout
}
return 0;
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
endl;
return 0;
}
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.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:
8:
9:
10:
11:
12:
13:
#include <algorithm>
#include <vector>
#include <list>
#include <iostream>
using namespace std;
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;
, ,
. 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
}
return
0;
Contents of
Element [0]
Element [1]
Element [2]
Element [3]
Element [4]
Element [5]
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 ()
{
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
"}"
endl
endl;
5, rand);
526
27:
28:
29:
30:
31:
32:
33:
34: }
23. STL
; iElementLocator != listlntegers.end ()
; ++ iElementLocator )
cout *iElementLocator ' ';
cout
"}"
endl;
return 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 ()
{
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;
527
528
48:
49:
50:
51:
52:
53: }
23. STL
cout endl;
cout
"
NumChars
endl;
return 0;
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:
endl;
());
transform ( Sample.begin ()
//
, Sample.end ()
//
, strLowerCaseCopy.begin () //
//
, tolower );
//
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
cout
cout
// ...
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: }
dqResultAddition [nlndex]
endl;
}
return
0;
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.
9:
10:
11:
12:
13:
14:
15: }
16: int
17: {
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
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:
//
copy_if ( listlntegers.begin(), listlntegers.end()
, iLastPos
, [](int element){return ((element % 2) == 1);});
cout
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:
49:
50:
51:
52:
53:
54: }
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 .
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;
STL
535
31:
32:
33:
34:
35:
36:
37:
38:
39:
40: }
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 ( ) ,
( ).
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
4
5
6
7
{
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;
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: }
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)
{
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;
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)
{
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;
: (, 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
cout
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
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. :
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.
push
, ..
qlntegers.push (10);
pop
, ..
qlntegers.pop ();
front
cout
back
cout
empty
qlntegers.front ();
, ..
qlntegers.back ();
, ; bool
if (qlntegers.empty ())
cout "The queue is empty!";
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
, 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: }
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.
push
pqlntegers.push (10);
pop
, ..
pqlntegers.pop ();
top
cout
empty
, ; bool
if (pqlntegers.empty ())
cout "The queue is empty!";
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:
15:
16:
17:
18:
19:
20:
21:
22:
return 0;
}
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:
21:
22:
23:
24: }
return 0;
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;
std::bitset
16:
17:
18:
19:
20:
21:
22: }
cout
eightbits
563
endl;
//
bitset <8> eightBitsCopy(eightbits);
return 0;
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;
OR
XOR
NOT
operator=
operator [N]
fourBits =
fourBits =
(2); //
(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
val=l)
val ( 1)
reset (N)
std::bitset
565
. 25.2
Flip
Size
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
cout
cout
cout
cout
cout
cout
cout
return 0;
inputFlipped
endl;
566
25.51-
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:
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:
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:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27: }
12:
cout endl;
v e c B o o lF la g s . f l i p
();
endl;
return 0;
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:
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:
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:
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
endl;}
{
inFish->Swim();
}
int main()
{
unique_ptr<Fish> smartFish (new Fish);
21
22
23
24
25
26
27
28
29
};
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;
( ),
(m anipulator),
. s t d : : e n d l ,
:
std::cout
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
oct
Input
endl;
stdncout...
11
12
cout
13
14
cout
cout
15
16
17
18
cout
cout
cout
hex
Input
591
endl;
19
20
cout
21
return 0;
22
. 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
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
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
cout
{
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:
12:
13:
14:
15:
16:
17:
18:
19:
20:
<<
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 +
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};
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:
, 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;
}
, .
, 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;
}
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
599
endl;
endl;
}
return 0;
}
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.
#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
endl;
while (myFile.good())
getline (myFile, fileContents);
cout fileContents endl;
20
21
22
23
24
25
endl;
else
cout
26
27
28: }
return 0;
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.
, 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()
{
18:
19:
20:
21:
22:
23:
24:
25:
26:
27: }
strlnput
stringstream anotherStream;
anotherStream strlnput;
int Copy = 0;
anotherStream Copy;
cout
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
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
610
28.
- 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:
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 n d l;
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;
4
5
{
if(Divisor == 0)
throw "Dividing by 0 is a crime";
6
7
8
9
10
11
12
int main()
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
cout
}
catch(char* exp)
{
cout
cout
}
return 0;
613
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
endl;
FuncA();
}
catch(const char* exp)
{
cout
"Exception: "
exp
endl;
}
cout "main(): exiting gracefully"
return 0;
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
,
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: }
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;
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, #.
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;
}
3. 2.4 :
##include <iostream>
#using namespace std;
//
int DemoConsoleOutput();
int main()
{
//
DemoConsoleOutput();
return 0;
}
//
int DemoConsoleOutput()
{
cout
cout
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
return 0;
4.
, ( ),
:
647
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()
{
endl;
6
cout
(Valuel Value2)
649
endl;
return 0;
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()
{
endl;
;
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
endl;
{
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;
}
return 0;
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 )
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
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
endl;
656
.
}
Mammal()
{
cout
"Mammal: Contructor"
endl;
"Mammal: Destructor"
endl;
}
-Mammal()
{
cout
}
};
class Reptile
{
public:
void SpitVenomO
{
cout
endl;
}
Reptile()
{
cout
"Reptile: Contructor"
endl;
"Reptile: Destructor"
endl;
}
-Reptile()
{
cout
}
};
class Bird
{
public:
void LayEggs()
{
cout
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
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
}
};
int main()
{
Circle myRing(5);
Triangle myWarningTriangle(6.6, 2);
endl;
12
cout
cout
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;
}
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()
{
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)
{
}
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;
}
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
"> ";
nNumVowels
return 0;
}
3. t o u p p e r ():
#include <string>
#include <iostream>
#include <algorithm>
int main ()
{
using namespace std;
cout
cout
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
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
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
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
};
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
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