You are on page 1of 1166

| ...

/ 2 | 2014

C++

, Ph.D.
...

2014

Creative Commons (CC) - -
3.0 (CC BY-NC-SA 3.0):
http://creativecommons.org/licenses/by-nc-sa/3.0/deed.el.

: , -
.

1999-2000

. ()
.
, -
,
,
( ) .
-
( )
.


(
). ,
.
-
! :
10 -

.1

.
, -
.
:
string
vector new delete;

. , -
.
, , -
.
-
. , . -
.
.
- -
. ( Objects!...) -

1 :
http://publib.boulder.ibm.com/infocenter/compbgpl/v9v111/index.jsp?topic=/com.ibm.xlcpp9
.bg.doc/language_ref/compiler_pubs.htm
http://www.cplusplus.com/

iii
iv

=
.
-

2.2.2. .

.
, 2014

..................................................................................................................................... iii

................................................................................................................................. v

: ............................................................................. 1

. 0 - .............................................................................. 3
0.1 ......................................................................................................................................................... 4
0.2 ............................................................................................. 7
0.3 ...................................................................................................................................... 9
0.3.1 ................................................................................................................................... 13
0.4 ....................................................................................................... 14
0.5 ..................................................................................................................... 15
0.6 C++ ................................................................................................................................................ 16
0.7 BNF ....................................................................................................................................... 17

. 1 ........................................................................................................... 19
1.1 ( ) C++ ............................................................................................. 21
1.2 .................................................................................................................................... 21
1.2.1 std::!............................................................................................................................... 21
1.3 ...................................................................................................................................................... 22
1.4 * include................................................................................................................................. 24
1.5 .................................................................................................................................... 25
1.5.1 ................................................................................................................................... 26
1.6 ................................................................................................................................ 26
1.7 ............................................................................................................... 27
1.7.1 ..................................................................................................... 29
1.8 .......................................................................................................................................... 30
1.8.1 ................................................................................................................................................ 31
1.8.2 .......................................................................................................................................... 31
1.9 ................................................................................................................. 31
1.10 C++ ................................................................................................................................. 34
1.10.1 cmath math.h ; ...................................................................................................................................... 36
1.11 ...................................................................................................................................... 37
1.12 C: printf() ....................................................................................................................... 38
1.13 .............................................................................................................................................................. 39
1.14 ; ................................................................................................................................................... 39
..................................................................................................................................................................... 41
...................................................................................................................................................................... 41
...................................................................................................................................................................... 41

. 2 ...................................................................................................... 43
2.1 .................................................................................................................................... 44
2.1.1 () .................................................................................................................................... 46
2.2 ................................................................................................ 48
2.3 ....................................................................................................................................... 51
2.4 ..................................................................................................................................... 55
2.5 C++........................................................................................................................ 55
2.6 ............................................................................................................................................ 58
2.7 - ......................................................................................... 58
2.8 C++ .............................................................................................. 62
2.8.1 typeid ...................................................................................................................... 62

v
vi

2.8.2 sizeof ................................................................................................................. 62


2.8.3 & * .............................................................................................................. 63
2.8.4 .................................................................................................................................. 64
2.9 ................................................................................................................................................. 65
2.9.1 C ......................................................................................................................................... 66
2.10 * ....................................................................................................... 67
2.11 * ......................................................................................................................... 68
2.12 scanf(): printf() ......................................................................................................................... 69
2.13 , ...................................................................................................................................................... 71
2.14 ( ) ............................................................................................................... 71
..................................................................................................................................................................... 72
...................................................................................................................................................................... 72
...................................................................................................................................................................... 72
...................................................................................................................................................................... 73

. 3 * .............................................................................................................. 75
3.1 ............................................................................................................................. 76
3.2 ......................................................................................................................... 77
3.3 .......................................................................................................................... 77
3.4 ............................................................................................................................ 77
3.5 true false ................................................................................................................... 79
3.6 ........................................................................................................... 79
3.6.1 ................................................................................................................. 79
3.6.2 ( ) .............................................................................. 80
3.6.3 ............................................................................................................... 81
3.7 .................................................................................................................................................... 82
3.8 .................................................................................. 83
3.9 .................................................................................................................... 84
3.10 ................................................................................................................................................. 85
..................................................................................................................................................................... 86
...................................................................................................................................................................... 86
...................................................................................................................................................................... 86
...................................................................................................................................................................... 87

. 4 bool, char ................................................................................ 89


4.1 ......................................................................................................................... 90
4.1.1 ! .......................................................................................................................... 93
4.2 ......................................................................................................... 94
4.3 : assert() ................................................................................................. 95
4.4 bool................................................................................................................................................ 97
4.4.1 false true............................................................................................................ 99
4.5 char .................................................................................................................................................. 99
4.5.1 char ....................................................................................................101
4.6 char ................................................................................................................. 103
4.7 wchar_t...................................................................................................................................... 106
4.8 ............................................................................................................................................... 106
4.9 ( ) .............................................................................. 107
4.10 ..................................................................................................................................... 108
................................................................................................................................................................... 109
....................................................................................................................................................................109
....................................................................................................................................................................109
....................................................................................................................................................................109

. 5 .................................................................................................................................... 111
5.1 - if ................................................................................................................................ 112
5.2 if ..................................................................................................................................................... 115
5.3 if - ...................................................................................................... 117
5.4 * ............................................................................................................. 120
5.4.1 * ..........................................................................................................................122
5.5 ....................................................................................................................... 124
5.6 .................................................................................................................... 127
vii

5.7 ";" ................................................................................................................................... 128


5.8 ( ) .................................................................................................................................. 129
................................................................................................................................................................... 129
....................................................................................................................................................................129
....................................................................................................................................................................130
....................................................................................................................................................................131

. 6 ............................................................................................................................. 133
6.1 ................................................................................................................................................. 134
6.1.1 - - ...................................................................................................137
6.1.2 .....................................................................................................................................139
6.2 * .................................................................................................................. 141
6.2.1 * ....................................................................................................................................................143
6.3 .......................................................................................................................... 150
6.4 for .................................................................................................................................................. 151
6.5 ............................................................................................................................ 154
6.6 ( ) .................................................................................................................................. 154
................................................................................................................................................................... 155
....................................................................................................................................................................155
....................................................................................................................................................................155
....................................................................................................................................................................156

. 7 ............................................................................................................................. 159
7.1. - ............................................................................................................... 160
7.2. return.................................................................................................................................... 161
7.3. ......................................................................................................................... 162
7.4. ..................................................................................................................... 166
7.4.1 .................................................................................................................................166
7.4.2 ...........................................................................................................................................................167
7.4.3 .................................................................................................................................169
7.5. main .................................................................................................................................. 170
7.6. unsigned; ........................................................................................................................ 170
7.7. ................................................................................................................................................ 171
7.7.1 exit() assert() .....................................................................................................................................................178
7.8. () ......................................................................................................... 179
7.9. * ................................................................................................................ 182
7.10. ...................................................................................................................................................... 184
7.11. ............................................................................................................................................ 185
................................................................................................................................................................... 185
....................................................................................................................................................................185
....................................................................................................................................................................186
....................................................................................................................................................................186

. 8 - Text ............................................................................................................................ 189


8.1 C++ ............................................................................................................................ 191
8.2 - ................................................................................................................ 192
8.3 ...................................................................................................................... 193
8.3.1 cin.eof() ...............................................................................................................................................................196
8.3.2 ............................................................................................................196
8.4 ......................................................................................................................... 197
8.5 ..................................................................................................................... 199
8.6 .......................................................................................................................... 201
8.7 ...................................................................................................................................... 204
8.8 ............................................................................................................................................... 205
8.9 -: ......................................................................................................... 205
8.10 ................................................................................................................................................ 207
8.11 ............................................................................................................................. 211
8.12 () .................................................................................................... 212
8.13 C................................................................................................... 214
8.14 ........................................................................................................................................................... 217
................................................................................................................................................................... 218
viii

....................................................................................................................................................................218
....................................................................................................................................................................218
....................................................................................................................................................................219

. 9 ..................................................................................................................................... 221
9.1 ......................................................................................................................................... 222
9.2 ............................................................................................................. 226
9.2.1 ............................................................................................................................................226
9.2.2 .......................................................................................................................228
9.2.3 ..............................................................................................................................................229
9.2.4 .............................................................................................................................................230
9.3 - .................................................................................................................................. 231
9.4 .................................................................................................................. 235
9.5 ........................................................................................... 241
9.5.1 ........................................................................................................................242
9.5.2 ............................................................................................................................245
9.5.3 .........................................................................................................................................247
9.6 - - ..................................................................................................... 249
9.6.1 binSearch..................................................................................................................254
9.7 ............................................................................................................................................ 254
................................................................................................................................................................... 255
....................................................................................................................................................................255
B ....................................................................................................................................................................255
....................................................................................................................................................................256

. 10 ......................................................................................................... 259
10.1 string ............................................................................................................ 260
10.2 ........................................................................................................................ 262
10.3 ............................................................................................................ 262
10.4 ................................................................................................................................... 263
10.5 ..................................................................................................................................................... 265
10.6 - .............................................................................................................. 268
10.6.1 ..............................................................................................................................268
10.6.2 size_type ...................................................................................................................................269
10.7 - .................................................................................................................................. 269
10.8 ..................................................................................................................................................... 270
10.9 - - ..................................................................................................... 273
10.10 .............................................................................................................................. 274
10.11 ................................................................................................................................................... 276
10.12 string ...................................................................................................................... 277
10.12.1 ............................................................................................................................................278
10.13 C: ........................................................................................... 281
10.13.1 C ........................................................................................................................................283
10.14 * std::wstring .............................................................................................................................. 284
10.15 ... ............................................................................................................................................ 285
................................................................................................................................................................... 285
....................................................................................................................................................................285
B ....................................................................................................................................................................286
....................................................................................................................................................................287

: ................................................................................... 289

. 11 .................................................................................................................. 291
11.1 ................................................................................................................................. 292
11.2 ...................................................................................................................................... 294
11.3 ............................................................................ 294
11.3.1 * ++ bool .............................................................................................................................297
11.4 .......................................................................................... 297
11.5 ............................................................................................................................ 298
11.6 for ............................................................................................................................................... 299
11.7 do-while ..................................................................................................................................... 302
ix

11.8 n+ - break .................................................................................................. 304


11.9 switch ........................................................................................................................................ 305
11.9.1 switch .....................................................................................................................307
11.10 * - goto ........................................................................................................................ 308
11.10.1 goto ....................................................................................................309
11.11 * continue .................................................................................................................................. 310
11.12 * .......................................................................................................................... 310
11.13 .......................................................................................................................... 311
11.14 ... ............................................................................................................................................. 312
................................................................................................................................................................... 312
....................................................................................................................................................................312

. 12 I ........................................................................................................................ 315
12.1 ........................................................................................................................................... 316
12.2 const ......................................................................................................................... 318
12.2.1 const .......................................................................................................................................318
12.3 ............................................................................................................................................ 320
12.3.1 .....................................................................................................................................321
12.3.2 ................................................................................................................................321
12.3.3 .....................................................................................................................................323
12.3.4 ptrdiff_t ..............................................................................................................................................326
12.3.5 ............................................................................................................................................................326
12.4 ................................................................................................................................ 327
12.5 .................................................................................................................................. 333
12.5.1 .......................................................................................................334
12.6 () ......................................................................................................................... 335
12.6.1 .........................................................................................................................................337
12.7 main ............................................................................................................................... 338
12.8 ... ...................................................................................................................................................... 339
................................................................................................................................................................... 339
....................................................................................................................................................................339
B ....................................................................................................................................................................340
....................................................................................................................................................................340

. 13 I - ..................................................................................................... 343
13.1 ......................................................................................................................... 344
13.2 I ...................................................................................................... 346
13.3 II ..................................................................................................... 348
13.3.1 unsigned; () .......................................................................................................................350
13.4 ........................................................................................................................................... 350
13.5 return () ................................................................................................................................. 353
13.6 .................................................................................................... 353
13.6.1 * .........................................................................................................................................357
13.6.2 .............................................................................................................358
13.7 * () .................................................................................................... 359
13.8 C () ...................................................................................................................... 360
13.9 ............................................................................................... 362
13.9.1 ................................................................................................................................................363
13.9.2 ...........................................................................................................................................364
13.9.3 ......................................................................................................................................................365
13.10 ......................................................................................................................... 370
13.11 ! ............................................................................................................................ 371
13.11.1 ....................................................................................................................374
13.11.2 E ....................................................................................................................................................376
13.11.3 ...........................................................................................................................................382
13.11.4 ...................................................................................................................................382
13.12 ............................................................................................................... 383
................................................................................................................................................................... 385
....................................................................................................................................................................385
....................................................................................................................................................................385
....................................................................................................................................................................386
x

. 14 II ........................................................................................................................... 389
14.1 inline .................................................................................................................................... 390
14.2 ........................................................................................................ 390
14.3 ............................................................................................................................ 392
14.4 * .................................................................................. 394
14.5 ......................................................................................................................... 397
14.6 ................................................................................................................................ 400
14.6.1 WeekDay .............................................................................................400
14.6.2 ++ WeekDay ..........................................................................................................401
14.6.3 ().........................................................................................................................403
14.6.4 ... .............................................................................................................................................................404
14.7 ..................................................................................................................................... 405
14.7.1 ..............................................................................................................................405
14.7.1.1 using................................................................................................................ 409
14.7.2 ...........................................................................................................................409
14.7.2.1 , ... .......................................................................... 410
14.8 ......................................................................................................................................................... 411
14.8.1 stackavail ......................................................................................................................................413
14.9 ......................................................................................................... 414
14.9.1 ...................................................................................................................................419
14.10 () ........................................................................................................................................... 420
14.11 * ............................................................................................................ 424
14.12 ... ............................................................................................................................................. 426
................................................................................................................................................................... 427
....................................................................................................................................................................427
....................................................................................................................................................................427
....................................................................................................................................................................428

. 15 - II ........................................................................................................................ 431
15.1 ............................................................................................................................................................. 432
15.1.1 ............................................................................................................................................436
15.2 ................................................................................................................................................... 436
15.3 .................................................................................................................................................... 437
15.3.1 ! ..............................................................................................................................................439
15.4 -................................................................................................................................. 439
15.5 .............................................................................................. 440
15.5.1 ........................................................................................................................................441
15.6 ......................................................................................................................... 442
15.6.1 * ......................................................................................................................................442
15.7 ........................................................................................................................ 444
15.8 * ................................................................................................................................................. 447
15.9 * union ............................................................................................................................................................ 448
15.10 .................................................................................................................................... 451
15.11 ......................................................................................................................... 454
15.12 - seek tell ................................................................................ 457
15.12.1 ................................................................................................................459
15.13 - ................................................................................................ 460
15.13.1 * string; ................................................................................................................461
15.14 ........................................................................................................................................... 462
15.14.1 .........................................................................................................................................463
15.14.2 ......................................................................................................................................467
15.14.3 ........................................................................................................................................472
15.15 ............................................................................................................................................ 474
................................................................................................................................................................... 474
....................................................................................................................................................................474
....................................................................................................................................................................475

project 1: ........................................................................................................ 477


Prj01.1 ............................................................................................................................................. 477
Prj01.2 .................................................................................................................................. 478
Prj01.3 openWrNoReplace() .......................................................................................................... 478
xi

Prj01.4 openFiles() ......................................................................................................................... 479


Prj01.5 copyTitle() .......................................................................................................................... 481
Prj01.6 closeFiles() ......................................................................................................................... 481
Prj01.7 ApplicXptn () ............................................................................................................................ 482
Prj01.8 main ................................................................................................................................................ 482
Prj01.9 openFiles() ................................................................................................................................ 483

project 2: 3 ............................................................................................. 485


Prj02.1 ............................................................................................................................................. 485
Prj02.2 Vector3 ........................................................................................................ 486
Prj02.3 ............................................................................................................................. 487
Prj02.4 +, -, *, ^ ................................................................................................................ 488
Prj02.5 - ............................................................................................................................. 489
Prj02.6 ........................................................................................................................... 489
Prj02.7 << ....................................................................................................................................... 490
Prj02.8 ... ......................................................................................................................... 490
Prj02.9 ........................................................................................................................................... 490

. 16 ............................................................................................. 493
16.1 new delete ............................................................................................................. 494
16.2 B ................................................................................................................. 496
16.3 T .................................................................................................. 498
16.4 ........................................................................................................................................ 500
16.5 * new ........................................................................................................................ 504
16.6 bad_alloc ................................................................................................................................... 504
16.6.1 ..................................................................................................................505
16.7 ..................................................................................................... 505
16.7.1 RAII: ...................................................................................................................................509
16.8 ......................................................................................................................... 511
16.9 ................................................................................................................. 511
16.10 * : void* .......................................................................................................................... 515
16.11 * C: malloc(), free(), realloc() ...................................................................................... 517
16.12 realloc() ................................................................................................................ 519
16.13 ................................................................................................................................................ 520
16.13.1 linSearch() .................................................................................................................................532
16.13.2 linSearch() ............................................................................................................................................533
16.13.3 reserved + incr 2 * reserved .............................................................................................................535
16.14 ............................................................................................................................... 535
16.15 ............................................................................................................................................ 537
................................................................................................................................................................... 538
....................................................................................................................................................................538

. 17 * ...................................................................................... 539
17.1 ................................................................................................................................... 541
17.2 - ................................................................................................ 543
17.2.1 * C99....................................................................................................................................544
17.3 ........................................................................................................................ 545
17.3.1 unsigned .................................................................................................................................547
17.4 * () ......................................................................................................................... 548
17.5 C++ ................................................................................................................................. 549
17.6 ..................................................................................................... 552
17.6.1 ........................................................................................................................................553
17.6.2 1 ..........................................................................................................................554
17.6.3 0 ..........................................................................................................................555
17.6.4 "1"............................................................................................................................................................556
17.6.5 ..............................................................................................................................................556
17.7 bitmask ............................................................................................................................................... 557
17.8 ...................................................................................................... 560
17.9 float .......................................................................................... 560
17.9.1 .............................................................................................................564
xii

17.10 .......................................................................................................... 564


17.11 float ...................................................................................................... 565
17.11.1 ................................................................................................................................................................566
17.11.2 - IEEE ...................................................................................................................567
17.11.3 double long double ................................................................................................................568
17.11.4 C .................................................................................................................569
17.12 .................................................................................................................. 570
17.13 ........................................................................................................... 570
17.13.1 .....................................................................................................................................571
17.13.2 ........................................................................................................................................571
17.14 ......................................................................................... 573
17.15 ................................................................................................................................... 576
................................................................................................................................................................... 578
....................................................................................................................................................................578
....................................................................................................................................................................579
....................................................................................................................................................................579

. 18 ................................................................................................. 581
18.1 define, ifdef ..................................................................................................... 582
18.2 ......................................................................................... 586
18.3 ................................................................................................................................ 588
18.4 ................................................................................................................................ 592
18.5 namespace: ................................................................................................ 593
18.6 ............................................................................................................................................ 596
................................................................................................................................................................... 597
....................................................................................................................................................................597
....................................................................................................................................................................597

: ................................................................ 599

. 19 ..................................................................................................... 601
19.1 .......................................................................................................................................................... 602
19.1.1 const ..............................................................................................................................................................609
19.1.2 .....................................................................................................................................609
19.1.3 class public ...................................................................................................................................610
19.1.4 ......................................................................................................................................612
19.1.5 ......................................................................................................................................................613
19.2 ................................................................................................................................ 613
19.3 ..................................................................................................................................... 613
19.3.1 ..........................................................................................................................614
19.4 inline ..................................................................................................................................... 615
19.5 - ........................................................................................ 615
19.6 class struct; .............................................................................................................................. 617
19.7 struct GrElmn class GrElmn ....................................................................... 619
19.8 ............................................................................................................................ 625
19.8.1 get, set ............................................................................................................................................626
19.8.2 powerDevice() ......................................................................................................................................626
19.8.3 maxTime().............................................................................................................................................627
19.8.4 reCharge() ............................................................................................................................................628
19.8.5 ..........................................................................................................................................628
19.8.6 .....................................................................................................................................................629
19.9 ( ) .................................................................................................. 630
- ............................................................................................................................................. 631
....................................................................................................................................................................631
....................................................................................................................................................................631
....................................................................................................................................................................632

project 3: ......................................................................................................... 633


Prj03.1 ............................................................................................................................................. 633
Prj03.2 () .................................................................................................... 635
Prj03.3 Course ........................................................................................................................................ 636
xiii

Prj03.4 Student ....................................................................................................................................... 641


Prj03.5 StudentInCourse ....................................................................................................................... 644
Prj03.6 ........................................................................................................................................... 645
Prj03.6.1 loadCourses() ........................................................................................................................................646
Prj03.6.2 ............................................................................................647
Prj03.6.3 . . . ..................................................................................................................648
Prj03.6.4 . . . ............................................................................................................649
Prj03.6.5 main ......................................................................................................................................................649
Prj03.7 char* string; ........................................................................................................................................ 651
Prj03.8 ............................................................................................................ 652
- ............................................................................................................................................. 653
....................................................................................................................................................................653

. 20 - ........................................................................... 655
20.1 : BString .................................................................................................................. 658
20.1.1 ................................................................................................................................................659
20.1.2 at() ..........................................................................................................................................661
20.1.3 .................................................................................................................................................662
20.2 .......................................................................................................................... 662
20.3 private.......................................................................................................... 664
20.4 = ........................................................................................................................ 664
20.4.1 assign() .............................................................................................................................................666
20.4.2 ...............................................................................................................667
20.5 this ......................................................................................................................................... 668
20.6 ; ................................................................................................................. 669
20.7 ..................................................................................................... 669
20.7.1 ......................................................................................................................................670
20.7.2 .................................................................................................................................671
20.7.3 .............................................................................................................................................679
20.7.4 ...............................................................................................................................................681
20.7.5 , .................................................................................................................................683
20.8 ................................................................................................................................... 687
20.8.1 ..................................................................................................................... 691
20.9 ... ..................................................................................................................... 694
- ............................................................................................................................................. 695
....................................................................................................................................................................695
....................................................................................................................................................................695
....................................................................................................................................................................695

. 21 ................................................................................................. 657
21.1 ..................................................................................................................................... 698
21.1.1 ...............................................................................................................................700
21.2 .............................................................................................................................. 701
21.3 ....................................................................................................... 704
21.4 ................................................................................................................... 706
21.5 ........................................................................................................................................... 708
21.5.1 ............................................................................................................711
21.5.2 ; ...............................................................................................................................711
21.6 ............................................................................................................................... 712
21.6.1 swap() ...............................................................................................................................................712
21.7 * ............................................................................................................................. 716
21.8 .............................................................................................................................. 717
21.9 renew() ..................................................................................................................... 717
21.10 : { } GE SE ...................................................................... 719
21.10.1 * string BString: reserve() ................................................................................721
21.11 ............................................................................................................................... 723
21.11.1 ; ....................................................................................................................................................728
21.11.2 .....................................................................................................................................................729
21.12 * ................................................................................................................................... 730
21.13 ....................................................................................................................................... 731
21.13.1 ...................................................................................................................................731
21.13.2 ...................................................................................................................................733
xiv

21.14 ................................................................................................................................... 734


21.15 .............................................................................................................................. 736
21.16 ..................................................................................................................... 737
- ............................................................................................................................................. 738
....................................................................................................................................................................738
....................................................................................................................................................................738

. 22 ........................................................................................................... 739
22.1 : ..................................................................................... 740
22.2 ......................................................................................................................... 741
22.3 friend ......................................................................................................... 743
22.4 ........................................................................................................................... 744
22.5 ............................................................................................................................................. 744
22.5.1 ............................................................................................................................745
22.5.2 ..........................................................................................................................746
22.6 - ....................................................................................................... 746
22.6.1 ..........................................................................................................................................746
22.6.1.1 [] BString ............................................................................................................... 747
22.6.1.2 += BString ............................................................................................................... 747
22.6.1.3 += Date..................................................................................................................... 749
22.6.1.4 * C ........................................................................................................................................ 749
22.6.1.5 * forward() ......................................................................................................................... 750
22.6.1.6 * ++ Date () ........................................................................................................... 751
22.6.2 () ....................................................................................................................751
22.6.2.1 * - ........................................................................................................... 754
22.6.3 .................................................................................................................................................754
22.7 ............................................................................................................................. 755
22.7.1 @= @ ......................................................................................................................................756
22.7.2 ......................................................................................................................................757
22.7.3 BString ...................................................................................................................757
22.7.3.1 * ............................................................................................................................... 760
22.8 Vector3................................................................................................................................ 760
22.9 ++ - ................................................................................. 761
22.9.1 -> .......................................................................................................................................764
22.10 * pimpl ............................................................................................. 764
- ............................................................................................................................................. 770
....................................................................................................................................................................770

project 4: ........................................................................................... 771


Prj04.1 ............................................................................................................................................. 771
Prj04.2 Course ........................................................................................................................................ 772
Prj04.3 ... ............................................................................................................... 779
Prj04.3.1 add1Course() delete1Course() ......................................................................................783
Prj04.3.2 save() load() ....................................................................................................................................785
Prj04.3.3 ..............................................................................................................................786
Prj04.3.4 []; ......................................................................................................................787
Prj04.4 ........................................................................................................................................ 788
Prj04.5 Student ....................................................................................................................................... 788
Prj04.5.1 ..........................................................................................................................789
Prj04.5.2 get set ............................................................................................................................790
Prj04.5.3 ........................................................................................................791
Prj04.5.4 ...............................................................................................................................793
Prj04.5.5 Student ......................................................................................................................................794
Prj04.6 ........................................................................................................................... 795
Prj04.6.1 , ...........................................................................................................798
Prj04.7 StudentInCourse ....................................................................................................................... 799
Prj04.8 StudentInCourseCollection ...................................................................................................... 802
Prj04.9 ............................................................................................................. 806
Prj04.10 ...................................................................................................................... 807
Prj04.10.1 CourseCollection ......................................................................................................................807
Prj04.10.2 StudentCollection .....................................................................................................................810
Prj04.11 1 .............................................................................................................. 812
Prj04.11.1 .......................................................................................813
xv

Prj04.11.2 .................................................................................................................................816
Prj04.11.3 .......................................................................................................................................................816
Prj04.11.4 ... .................................................................................................................................816
Prj04.12 2 ......................................................................................................... 819
Prj04.13 ............................................................................................................................. 821

project 5: ............................................................................................................... 825


Prj05.1 ............................................................................................................................................. 825
Prj05.2 Pascal............................................................................................................ 826
Prj05.3 ............................................................................................................................ 827
Prj05.3.1 : #x .......................................................................................................................................828
Prj05.3.2 - ..............................................................................829
Prj05.3.3 - ...............................................................................830
Prj05.3.4 : x = y ............................................................................................................................832
Prj05.4 ........................................................................................................................................... 832
Prj05.4.1 SetOfUCL ...................................................................................................................835
Prj05.5 ..................................................................................................................... 836
Prj05.6 ......................................................................................................................... 838

. 23 ............................................................................................................................. 849
23.1 ................................................................................................................ 842
23.1.1 .................................................................................................................................. 843
23.2 ............................................................................................................ 844
23.3 ...................................................................................................................................... 846
23.3.1 .....................................................................................................................................848
23.3.2 .................................................................................................................................848
23.4 .................................................................................................................................... 849
23.5 .............................................................................................................................. 849
23.5.1 ......................................................................................................................................852
23.6 ................................................................................................................................ 853
23.7 ................................................................................................... 853
23.8 private protected .................................................................................................................. 854
23.8.1 * protected: ....................................................................................................................855
23.9 ......................................................................................................................................... 857
23.10 * ....................................................................................................... 859
23.10.1 virtual .............................................................................................................................860
23.10.2 ... ..................................................................................................................................................861
23.11 ............................................................................................................................. 861
23.12 ................................................................................................................................... 862
23.12.1 (;) ......................................................................................................863
23.12.2 * ............................................................................................................................864
23.13 - RTTI................................................................................................................... 866
23.13.1 .......................................................................................................................................868
23.14 is_a has_a ..................................................................................................................................... 869
23.15 private, protected public .......................................................................................... 872
23.16 .................................................................................................................................... 874
23.17 ..................................................................................................................................... 875
23.18 ................................................................................................................................ 876
23.19 ........................................................................................................................................................ 878
23.20 ............................................................................................................................................ 879
- ............................................................................................................................................. 879
A ....................................................................................................................................................................879
....................................................................................................................................................................880

project 5: ............................................................................ 885


Prj06.1 ............................................................................................................................................. 885
Prj06.2 .................................................................................................................................................. 887
Prj06.3 Course OfferedCourse .................................................................................................... 887
Prj06.3.1 Course OfferedCourse ..........................................................................................890
Prj06.3.2 ........................................................................................................................890
Prj06.4 CourseCollection ...................................................................................................................... 892
xvi

Prj06.5 Student EnrolledStudent ................................................................................................ 899


Prj06.6 StudentCollection ..................................................................................................................... 905
Prj06.7 StudentInCourse StudentInCourseCollection .................................................................................. 909
Prj06.8 1 ( ) ................................................................................................ 910
Prj06.9 2 ( ) ........................................................................................................ 912
Prj06.10 ........................................................................................................... 914

. 24 - .......................................................................................... 917
24.1 C ...................................................................................................................................... 919
24.1.1 assert() ..........................................................................................................................................919
24.1.2 ...............................................................................................................920
24.1.2.1 std::exit() return ................................................................................................................ 921
24.1.3 ; errno ........................................................................................................................................922
24.2 ........................................................................................ 924
24.3 .......................................................................................... 927
24.4 ................................................................................................... 928
24.4.1 std::set_terminate() ..................................................................................................................928
24.4.2 std::terminate()..........................................................................................................................930
24.4.3 * ..................................................................................933
24.4.4 * std::uncaught_exception() ....................................................................................................934
24.5 try ............................................................................................................................. 935
24.6 C++ ..................................................................................................................... 936
24.6.1 logic_error ......................................................................................................938
24.6.1.1 domain_error............................................................................................................................... 938
24.6.1.2 invalid_argument ........................................................................................................................ 939
24.6.1.3 length_error................................................................................................................................. 940
24.6.1.4 out_of_range ............................................................................................................................... 940
24.6.2 runtime_error .................................................................................................941
24.6.2.1 range_error.................................................................................................................................. 941
24.6.2.2 overflow_error underflow_error ...................................................................................... 941
24.6.3 ; ...........................................................................................................943
24.7 ................................................................................... 943
24.8 ............................................................................................................... 944
24.8.1 ........................................................................................................945
24.9 ............................................................................................................... 948
24.10 ........................................................................................................................................................... 949

. 25 .......................................................................................................... 951
25.1 BString .................................................................................................. 952
25.2 ............................................................................................................ 955
25.3 ................................................................................................ 956
25.3.1 : pair ..............................................................................................................................956
25.4 ..................................................................................................................................... 958
25.5 ...................................................................................................................... 959
25.5.1 ...................................................................................................961
25.6 .................................................................................................................. 964
25.6.1 ...............................................................................................964
25.6.2 ...........................................................................................964
25.6.3 ..................................................................................965
25.7 .................................................................................................................................... 966
25.7.1 ................................................................................................................................970
25.7.1.1 ......................................................................................................................................... 974
25.7.2 .........................................................................................................................................975
25.7.3 , .........................................................................................975
25.7.4 ..................................................................................................................................................976
25.8 ................................................................................................................................................. 977
25.8.1 std::auto_ptr......................................................................................................................................................983
25.8.2 ... ...............................................................................................................................................985
25.9 ............................................................................................................. 985
25.10 ............................................................................................................................................ 988
................................................................................................................................................................... 988

. 26 - Standard Template Library (STL) ........................... 989


xvii

26.1 , ................................................................................................ 991


26.1.1 ..........................................................................................................................................992
26.1.2 .........................................................................................................................................994
26.1.3 ...........................................................................................................................................................996
26.1.3.1 .......................................................................................................... 1000
26.1.4 ...............................................................................................................................1003
26.2 .................................................................................................................................................. 1005
26.2.1 vector ...................................................................................................................................1008
26.2.1.1 , ............................................................................................................... 1011
26.2.1.2 : vector<bool>.................................................................................................. 1012
26.2.2 deque ...................................................................................................................................1013
26.2.3 list .........................................................................................................................................1014
26.2.4 ; ............................................................................................................................1018
26.3 ............................................................................................................................... 1018
26.3.1 set .........................................................................................................................................1020
26.3.1.1 .................................................................................................................. 1023
26.3.2 map .......................................................................................................................................1027
26.3.3 multiset multimap .................................................................................................1030
26.3.4 ..............................................................................................................................................1031
26.4 ; ........................................................................................................................ 1033
26.5 .................................................................................................................................... 1034
26.5.1 bitset ....................................................................................................................................1034
26.5.2 complex ...............................................................................................................................1037
26.6 ( ) .............................................................................................. 1038
................................................................................................................................................................. 1038

project 7: STL ......................................................................................... 1039


Prj07.1 STL I: vector ............................................................................................................. 1040
Prj07.1.1 Course .........................................................................................................................................1040
Prj07.1.2 CourseCollection........................................................................................................................1040
Prj07.1.2.1 getArr()............................................................................................................................. 1043
Prj07.1.3 Student ........................................................................................................................................1044
Prj07.1.4 StudentCollection.......................................................................................................................1046
Prj07.1.5 StudentInCourse ........................................................................................................................1049
Prj07.1.6 StudentInCourseCollection .......................................................................................................1049
Prj07.1.7 - .............................................................................................................................1051
Prj07.2 STL II ......................................................................................................................... 1052
Prj07.2.1 ..................................................................................................................................................1052
Prj07.2.1.1 ccArr CourseCollection ..................................................................................................................... 1052
Prj07.2.1.2 sCourses Student .............................................................................................................................. 1053
Prj07.2.1.3 scArr StudentCollection .................................................................................................................... 1053
Prj07.2.1.4 siccArr StudentInCourseCollection ................................................................................................. 1053
Prj07.2.1.5 - ................................................................................................................................... 1054
Prj07.2.2 Course .........................................................................................................................................1054
Prj07.2.3 CourseCollection........................................................................................................................1054
Prj07.2.4 Student ........................................................................................................................................1057
Prj07.2.5 StudentCollection.......................................................................................................................1058
Prj07.2.6 StudentInCourseCollection .......................................................................................................1061
Prj07.2.6.1 SICKeyLT ..................................................................................................................... 1064
Prj07.2.7 ..............................................................................................................................1065
Prj07.3 .......................................................................................................... 1066

project 8: ........................................................................................................ 1067


Prj08.1 : ................................................................................................. 1067
Prj08.2 ........................................................................................................................... 1068
Prj08.3 jpeg .............................................................................................................................................. 1070
Prj08.3.1 ...........................................................................................................................................1070
Prj08.3.2 ................................................................................................................................................1071
Prj08.4 ................................................................................................................................ 1072

...........................................................................................................................1075

..........................................................................................................................1079
xviii

. A: .......................................................................................... 1081
A.1 ................................................................................................................................................... 1081
A.2 .................................................................................................................................................... 1082
A.2.1 && ........................................................................................................................................1083
A.2.2 || ....................................................................................................................................... 1083
A.2.3 ! .......................................................................................................................................1084
A.2.4 ..............................................................................................................................................1084
A.2.5 ..................................................................................................................................1085
A.2.6 ................................................................................................................................................1086
A.2.6.1 Sheffer |.................................................................................................................. 1086
A.2.6.2 ||: .......................................................................................................................... 1086
A.2.6.3 v .................................................................................................................... 1086
A.2.7 ..............................................................................................................................................1086
A.3 ...................................................................................................................... 1087
A.4 ................................................................................................................................................... 1087
A.5 ...................................................................................................................... 1089
A.6 ......................................................................................................................................................... 1090
A.7 ............................................................................................................................. 1091
................................................................................................................................................................. 1091

. B: ..................................................................................................... 1093

. C: - C++........................................................................................................... 1095

. D: ............................................................................................. 1097
D.1 ISO 646 (ASCII) ............................................................................................................................................ 1097
D.2 928..................................................................................................................................... 1098
D.3 927..................................................................................................................................... 1099

. E: ............................................................................................ 1101

................................................................................................................................1105

................................................................................................................................... 1107
............................................................................................................... 1123
- ...................................................................................... 1133
- ....................................................................................... 1137


0. .........................................................................................................3
1. .......................................................................................................................................19
2. ..................................................................................................................................43
3. * ..........................................................................................................................................75
4. bool, char ..................................................................................................................89
5. ................................................................................................................................................................111
6. .........................................................................................................................................................133
7. I .........................................................................................................................................................159
8. Text .......................................................................................................................................................189
9. I .................................................................................................................................................................221
10. .....................................................................................................................................259

0
-

:
-
. -
.
:
-
.
.
.
:



(precondition)
(postcondition)

(inference rules)
(syntax)
(semantics)
BNF
:
0.1 .............................................................................................................................................................. 4
0.2 .................................................................................................. 7
0.3 ........................................................................................................................................... 9
0.3.1 ................................................................................................................................... 13
0.4 ............................................................................................................ 14
0.5 .......................................................................................................................... 15
0.6 C++ ..................................................................................................................................................... 16
0.7 BNF ............................................................................................................................................ 17

:
, , -
(information) . -
3
4 0

, -
,
. (information processing)
, , , -
.
-
, -
.
(data). ,
(data processing). ,
, (input data), -
(output data).
1
, , v i -
, (.. 50) :
( vk, ik ) k = 0..49
(.. ), :
( Ohm),
.
(vk, ik) .
Ohm .

2
, -
. -
, .
.
; .


.

,
, ,
.

(control) .

0.1
, ,
. , -
, (algorithm).
, , , :
17 13 67 104 2 69 45 375 35 84
- 5

. -
, , . 0-1.


1: 1 ( 17 )
2: 2
3:
:
4:
5:
6:
7: 3
. 0-1 .

. ; ! ,
, ,
, , -
( ) .

. :
:
: () ,
: <> :
: -
({)
.
: <>
: -
({).
, ak, k = 0..9 , m
, km .
:
m a0, km 0, k 1
k 9 :
ak > m

{ m ak, km k

k k + 1
, .
,
.
-
(flowcharts). -
. , -
. . 0-1 , . 0-2 -
.
-
. -
. -
, C++, , .
C++, :
6 0

() /
()

. 0-1: .

m = a[0]; km = 0;
for ( k = 1; k <= 9; k = k+1 )
if ( a[k] > m ) { m = a[k]; km = k; }
!
.

; ! -

m a0
km 0

k 1


k 9;


ak > m

m ak
km k

k k+1


m km

. 0-2
.
- 7

: -
(correct) (efficient). .

0.2

()!1
(program). (statement, in-
struction).
(programming languages).
, -
:
(syntax)
.
(semantics)
.
, -
( ) -
. , ,
. ,
,
. .
:
, .
(digital computer) -
: 0 1. , -
, . ... , (
): 0 1. -
, 0 1, (machine language).
.

:
0100000000000111
0001000000001000 ()
0101000000001001
:
1. 7 8 ,
2. 9.

(), .
(address). , 7, 8 9
.

, , -

. -
, ..:

1 (computer).
8 0

LOAD 7
ADD 8
STORE 9
, -
, .
.
(assembly language)
, . -
, . -

.
:
,
.
. . , -
(assembler), .
, , -
, , .2
, ,
, .
,
LOAD 0007 LOAD A
ADD 0008 ADD B
STORE 0009 STORE X
, :
+
.
(high level programming languages)
,
. , ,
, ( )
.
.
FORTRAN, ALGOL, APL .
COBOL, RPG . PL/I, Ada
. BASIC 1965
mini
, ! Pascal,
, ,
.
C++ -
-
FORTRAN .

. (
).

2 ,

(loader),
- 9

p.cpp p.obj p.exe


. 0-3 (p.cpp) (p.exe).


.
. -
.
(compiler).
,
-
( ) .
(source program)
(object program).
, , .
-
, .

(executable) . -
(linker linkage editor). . 0-3.
(interpreter).
,
.

0.3
0.2
. . .
m = a[0]; km = 0;
fot ( k = 1; k <= 9; k = k+1 )
if ( a[k] > m) then { m = a[k] km = k; }
. . .
, 3: for fot, if -
then m = a[k] km = k ;.
, , , -
: , () .
:
. . .
m = a[0]; km = 0;
for ( k = 11; k <= 9; k = k+1 )
if ( a[k] > m ) { m = a[k]; km = k; }
. . .
. , : k -
1 11 9.
: if (a[k] > m) { m = a[k]; km = k; }
m km .
:
. -
. -

3 0.2
.
10 0

. : ! ,
. 1.
, -
.
:
. . .
m = a[0]; km = 0;
for ( k = 11; k <= 9; k = k+1 )
if ( a[k] > M ) { m = a[m]; km = k; }
. . .
: m = a[m]. a[m] ,
m , -
.
-
. -
,
: ;
: ! , ; -
: 375 7 ! , -

. :
-
.
; :
1. :
-
>, .

> .
2. ( ) -
( )
. :
. , . 500 ; !
.
3. ( )
0 9. , m
km m = a[km].
1.
o (in-
put condition/predicate) (precondition). 2. 3. -

o (output condition predicate) (postcondition).
.
:
2000 kcal/h
220 V ( ).
x1 x2 axi2 + bxi + c = 0, a, b, c
: a 0 b2 4ac 0.
.
.
- 11

V = 220 V, :
2000 kcal/h.
: a, b, c R a 0 b2 4ac 0. : x1, x2 R
ax12 + bx1 + c = 0 ax22 + bx2 + c = 0.
:
: : = .

.
-
...
(
).
() ,
. ,
. ,
.
,
.
.
.
, -

,
,
(
).
;

. ; .
; -
:
: a[k] Z, k [ 0..9 ].
: m Z km [ 0..9 ] :
(m = a[km]) (m a[k] k [ 0..9 ]).
: [ 1..2 ] (1, 2 Z, 1 2)
1 2. ( 1.. 2 ], [ 1.. 2 )
( 1.. 2 ) () (1, 2], [1, 2) (1, 2)
.
, ,
. ,
.
. ,
:
o x1,... xm, o (x1,... xm).
y1,... yn o (x1,... xm, y1,... yn).
:
o o x1,... xm, o o
(x1,... xm) oo y1,... yn o o (x1,...
xm, y1,... yn).
12 0

(x1,... xm) (x1,... xm, y1,...


yn) .
-
(programming by contract) : -
( ).
, -
. -
.
: -
m km a[k].
: (m = a[km]) (m a[k] k [ 0 .. 9 ]) km
[ 0 .. 9 ].
,

, ..:
, -
,

.


. : ,
-
. .

x1,... xm
(x1,... xm) ()
y1,... yn
(x1,... xm, y1,.... yn) ()
(partially correct) -
4:
(x1,... xm) { E } (x1,... xm, y1,.... yn)

, -
(totally correct). :
(x1,... xm) < E > (x1,... xm, y1,.... yn)
, -
: C++ -
while, for dowhile -
, , .
-
1 (First Order Predicate Calculus)5. ,
, . -
(Propositional Calculus)
. , . -

4 :
{ (x1,... xm) } E { (x1,... xm, y1,.... yn) }
, C++.
5 .
- 13

. ,
... ... ...,
, -
.

0.3.1
.
(inference rules).
, -
.
:
x P(x)
, oo o
P(a) a.
:
xP( x )
P( a )
) )
. : ) ,
(
), )
.
o:
P
P Q, P Q,
, oo o
Q.
(modus ponens):
P , P Q
Q

.
( )6:
:
(a == a0) && (b == b0) { E } (a == b0) && (b == a0)
, :
(a == a0) && (b == b0) { E } (a == b0) && (b == a0) && (S == a0)
;
, (a == b0) && (b == a0) && (S == a0)
(a == b0) && (b == a0), (A && B) A.
(rule of
consequence):
P Q
Q R

6 == && . . .
14 0

E P R.
:
P{ E } Q , Q R
(1)
P { E} R
,
:
P Q
Q R

E P R.
:
P Q , Q { E} R
(2)
P { E} R
(2) -
.

0.4
,
.

.
(software engineer);
,
.
. -
:
(x1,... xm) < E > (x1,... xm, y1,.... yn)
E1,
..., EN:
(x1,... xm)
< E1 >
1(x1,... xm, y1,.... yn, z1,..., zp)
:
N-1(x1,... xm, y1,.... yn, z1,..., zp)
< EN >
(x1,... xm, y1,.... yn)
z1,..., zp ()
.
7.
E1, ..., EN ...
( -
).
(coding) .
-
; ,

7 .
- 15

. ,
-
.
, , -
-
.
-
.
: think first, code later , :
.
, -- (step-
by-step refinement) (rule of
composition):
1 P Q
2 Q R

P E1 E2,
R.
:
P { E1 } Q , Q{ E 2 } R
()
P { E1 ;E 2 } R
( ) -
, Z (Diller 1990), (Spivey 1988), VDM (Andrews & Ince 1991),
(Jones 1990) .., ( ). Z
-
( ). VDM (Vienna Development Method) -
-
. .

0.5
:
km = 0;
for ( k = 1; k <= 9; k = k+1 )
if ( a[k] > a[km] ) { km = k; }
m = a[km];

. (
.)
:
.
.
, , -
:
:
( ),
.
-
:
16 0


.
, , -
. -
.
(microoptimization). -
.
, -
!

.
.

0.6 C++
C++ B. Stroustrup
(object-oriented programming)
C. , , C (Kernighan & Ritsie 1978).
(Stroustrup 1997). -
ANSI X3J16 ( )
ISO WG21 ( ). (ISO/IEC 14882:1998)
1998 C++98. 2003 -
(ISO/ IEC 14882:2003) C++03. -
2011 ISO/IEC 14882: 2011
C++11.8
C++ C (
, )
. -
.
C++11

.

C++03. :
Borland 9 (v.5.5) C++
Builder. C++.

Notepad command line.
g++ GNU: -
(IDE) : ) Dev C++10, ) Code::Blocks Studio11.
g++ C++11 .12

8 C++11 - C++14.
9 http://dn.codegear.com/article/20633
10 http://www.bloodshed.net/
11 http://www.codeblocks.org/
12 http://gcc.gnu.org/projects/cxx0x.html
- 17

0.7 BNF

, , -
BNF (Backus - Naur Form).

1
() ,
0 ... 9
.
= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
= |
"a" | "b" | "c" | "d" | "e" | "f" |
"A" | "B" | "C" | "D" | "E" | "F";

, :
, .. ,
=

;.
:
(ter-
minal symbol) "...", .. "2" "3",
,
|,
-
(,).
2
00, 01, ... 99,
.
= , ;


:
() -
| : ,
.
, . 1 :
= "0" | ... | "9";
= | "a" | ... | "f" | "A" | ... | "F";
(recursion),
. :
3
, , :
= |
|
, ;
= ".", ;
18 0

= | , ;
= "0" | ... | "9";

,
. : 133 -
; :
' . -
, . , "3" . (13)
.
, 13 . -
, . "3" . (1) -
.
1 . 13 -
, 133 .
. -
:
= | , ;
. .
, .
4
:
= , |
;
= "+" | "-";
:
= [ ] ;
= "+" | "-";

-
. -
. .

1

:
! ; ! ,
.
:

. -
C++ -
.
:

cout
endl



include

:
1.1 ( ) C++ ................................................................................................... 21
1.2 ......................................................................................................................................... 21
1.2.1 std::! ............................................................................................................................... 21
1.3 ........................................................................................................................................................... 22
1.4 * include ...................................................................................................................................... 24
1.5 .......................................................................................................................................... 25
1.5.1 .................................................................................................................................... 26
1.6 ..................................................................................................................................... 26
1.7 .................................................................................................................... 27
1.7.1 ...................................................................................................... 29
1.8 ............................................................................................................................................... 30
1.8.1 ................................................................................................................................................ 31
1.8.2 ........................................................................................................................................... 31
1.9 ...................................................................................................................... 31
1.10 C++ .................................................................................................................................... 34
1.10.1 cmath math.h ;....................................................................................................................................... 36
1.11 ......................................................................................................................................... 37
1.12 C: printf() .......................................................................................................................... 38
1.13 .................................................................................................................................................................. 39
1.14 ; ...................................................................................................................................................... 39

19
20 1

..................................................................................................................................................................... 41
............................................................................................................................................................................... 41
............................................................................................................................................................................... 41
:
, , , -
. ,
, .
.
, ,
. (char-
acter set)
-
. , () -
.

.
(letters) , :
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
:
a b c d e f g h i j k l m n o p q r s t u v w x y z
-
.
.

C++ !1
.
, (digits) :
0 1 2 3 4 5 6 7 8 9
(alphanumeric
character). .
-
(space) (blank). , -
.
. _.
b.

TPITH_1_IAN_2013
PIb1bIANb2013

, , -
, ..:
( ) . , + - * / =

. ,
.
, . ,

.

1 .
21

1.1 ( ) C++
,
C++.
. C++
:
< > % : ; ? ^ & | ~ ! \ " _ { } [ ] #
C++, .

-
(digraph) (trigraph) .
:
{ <% } %>
[ <: ] :>
# %:
D .

1.2
.
#include <iostream>

int main()
{
std::cout << " " << std::endl;
std::cout << " !" << std::endl;
std::cout << " "<< std::endl;
std::cout << " !!!" << std::endl;
}
, -
. :

!

!!!
! std::cout <<
"" . <<
std::endl, , ,
. ; .

1.2.1 std::!
std::
.

, cout endl. -
.
, -
.

.
C++ :
(namespace)
22 1

. nm -
A, B
A::nm B::nm.
C++
, std ( standard). , std::cout :
cout std.
:
#include <iostream>

using std::cout;
using std::endl;

int main()
{
cout << " " << endl;
cout << " !" << endl;
cout << " " << endl;
cout << " !!!" << endl;
}
! using :
std::cout cout std::endl endl.
, :
#include <iostream>

using namespace std;

int main()
{
cout << " " << endl;
cout << " !" << endl;
cout << " " << endl;
cout << " !!!" << endl;
}
using namespace std std.
.
.
.

1.3
, C++
. C++
.
,
:
: int main(),
.
, ,
.
(body),
. : " {"
"}".
";".
23

, -
, , .
-
:
#include <iostream>
using namespace std;
int main()
{
cout << " " << endl;
cout << " !" << endl;
cout << " !!!" << endl;
cout << " " << endl;
}
:

!
!!!

, -
. .
:
#include <iostream>
using namespace std;
int main()
{
cout<<" "<<endl;cout<<
" !"<<
endl;
cout << " " << endl;
cout << " !!!" << endl;
}
:
#include <iostream>
using namespace std;
int main()
{
cout << " " << endl;

cout << " !" << endl;

cout << " " << endl;

cout << " !!!" << endl;


}

.

#include <iostream>
; ,
iostream ( )
. -
cout, <<, endl. ,

.
main, cout endl (identifiers).
.
.
24 1

1.4 * include
: , entoles.txt, :
cout << " " << endl;
cout << " !" << endl;
cout << " !!!" << endl;
cout << " " << endl;
prwto.cpp :
#include <iostream>
using namespace std;
int main()
{
#include "entoles.txt"
}
prwto.cpp prwto.exe.2 -
; :

!

!!!
include;
#include "entoles.txt"
, ,
entoles.txt. ,
, 1.2.
#include <iostream> ; ,
iostream3 Dev-C++ c:\Dev-Cpp, iostream -
c:\Dev-Cpp\include\c++\3.4.2. 4.
cout <<.
, :
iostream < >;
.
C , (pre-
processor). , include
.

#include < >
#include " "
(directive) .
;

. Dev-
C++, , c:\Dev-Cpp\include .

.
#include < >.

2 () .
3 iostream.h iostream.hpp.
4 , , ! !
25

1.5
, , :
" "
" !"
" "
" !!!"
.
5 (string literal) -
("). -
C++. -
.

"" "" ";" "1" "C++"
" " "12/15*()=" " "

, . ,
.
(length)
.
! () .
: 1, 1, 1, 2, 3, 14, 9, 3 .

("). :
,
\", (escape sequence). ,
, .
\, ?, '.

"\"" "What\'s up man\?" "\' "
: 1, 14, 16 .

,
C++.
.
:
.6
.

#include <iostream>
using namespace std;
int main()
{
cout << " * " << endl;
cout << " * * " << endl;
cout << " ***** " << endl;
cout << "* *" << endl;
}

5 .
6 (
Windows);!
26 1

:
*
* *
*****
* *

(.. ) ,
\n. ,
cout << "abc\ndef" << endl;
:
abc
def

1.5.1

.
:

\. ..,
cout << "abc\
def" << endl;
:
abcdef
, \ C++ -
.
:
, C++ (concatenation) ,

. .. :
cout << "abc" "def" << endl;
:
abcdef

1.6

cout << "" << endl
. ;
( ).
, , -
, .
default output device (file).
. (), C++, -
cout.
. :
cout << endl;
.
, cout ,
<<. , .
27


, .

:
cout << " " << "" << endl;
:

:
cout << " AB" << "CD" << "EF" << endl;
:
ABCDEF

endl; , . .. :
cout << "abc";
cout << "def" << endl;
:
abcdef
endl '\n', ..:
cout << " AB" << "CD" << "EF" << '\n';
.

1.7
(constant) ;
. ..:
37,4 -0,1 -1,1 41,00 +10,00017
:
"+" "-". "+".
, . : 37, 0,
1, 41, 10.

. ",".
, .

:
0,000000173 1,73107
:
3000000000 3109
(scientific notation) -
(floating point). ,
(fixed point).
C++
:
(.) (
),
28 1

10 e 10N. e, -
10 . .. 0.375e3 0.375 10 3
(=375). e (exponent).
C++ :
C++
37,4 37.4
0,1 -0.1
1,1 -1.1
41,00 41.00
10,00017 10.00017
1,7310-7 1.73e-7
3109 3e9

.

(floating point constants literals) .
BNF:
= [ ] |
, ;
= [ ] ".", |
, ".";
= "e" [ ] |
"E" [ ] ;
= "+" | "-";
= | , ;
:
, ..:
1234.5678 .1357 2345.
.
-
"e" "E", "+" "-",
, ..:
1234.5678e+12 1234.5678E-12 1234.5678e12
.1357e+15 .1357E-15 .1357e15
2345.e+15 2345.E-15 2345.e15
, , .
:
2345e+15 2345E-15 2345e15
; , -1.7e-7
C++ .
:
e !
, 5.36e-8 0.0000000536 5.36/108.
; e
5.36e-8e2
0.0000000536 100. 5.36e-8e2
.
, :

.
29

, (
):
5.67e+4 12.0 56700.0 0.00001 -0.0
+0.70135e+1 7.0135 .12 19.
:
23 ""
3,14 ","
710 "" ""
3 . 14
317. ( )
123

. ;

#include <iostream>
using namespace std;
int main()
{
cout << 5.67e+4 << endl; cout << 12.0 << endl;
cout << -56700.0 << endl; cout << 0.00001 << endl;
cout << -0.0 << endl; cout << +0.70135e+1 <<endl;
cout << 7.0135 << endl; cout << .12 << endl;
cout << 19. << endl;
}
:
56700
12
-56700
1e-05
0
7.0135
7.0135
0.12
19
, -
.

:

.

.
C++
.

1.7.1
,
:
2E
, . :
: (0 "+", 1 "-"),
: / ,
: / .
30 1

,
( ) .
;

#include <iostream>
using namespace std;
int main()
{
cout << 12.3456 << endl;
cout << 12.34567890123456789 << endl;
}
:
12.3456
12.3457
; ,
! ; , C++
(precision) :
#include <iostream>
using namespace std;
int main()
{
cout << 12.3456 << endl;
cout.precision(20);
cout << 12.34567890123456789 << endl;
}
, cout.precision(20)
cout. ;
12.3456
12.34567890123456735
17 .

. (loss of significant digits)
.

-
.
:
( ) . , ,
(overflow).
; C++.

1.8

. (integer constant
literal):
= | "0";
= - | , ;
- = "1" | ... | "9";
, ( ) 0
0.
31

, .. -375
, C++ 7.

:
12 0 417 375 2048
. :
12.0 (.)
1100 E
0,0 (,)

,
.
, . ,
.

. .. :
cout << 12 << endl;
:
12

1.8.1
0
0; 0;
0 (octal) ,
08 09 ( invalid octal constant)
"8" "9" 011 9.
,
cout << 11 << " " << 011 << endl;
:
11 9

1.8.2
C++ (hexadecimal) -
. 0x 0X : 0..9
a..f ( A..F).
cout << 0xA << " " << 0xff << " " << 0Xa12C << endl;
:
10 255 41260

1.9

(arithmetic expression). .. :
cout << (1 + 1) << endl;
1 + 1 .

7 , .
32 1

1.1
C++
C++
+ +

/ /

: %

C++
1.
,
2. *, /, %,
3. +, -.
C++ ,
: "*" "". ,
"/" ":".

, (.. )
8. , ,
.

:
#include <iostream>
using namespace std;
int main()
{
cout << (1 / 2) << " " << (1. / 2) << endl;
}
:
0 0.5
; 0 1 / 2 ,
, 0.5. ,
. , 1. / 2,
.

, %
: . /
:
= * +
. :
= ( / )* + ( % ) (1)
,
: 5 / 2 2
: 5 % 2 1

8 .
33

,
0 ().
%
(1) ! .. :
#include <iostream>
using namespace std;
int main()
{
cout << (1 / 2) << " " << (1 % 2) << " "
<< ((1/2)*2 + (1%2)) << endl;
cout << (1 / (-2)) << " " << (1 % (-2)) << " "
<< ((1/(-2))*2 + (1%(-2))) << endl;
cout << ((-1) / 2) << " " << ((-1) % 2) << " "
<< (((-1)/2)*2 + ((-1)%2)) << endl;
cout << ((-1) / (-2)) << " " << ((-1) % (-2)) << " "
<< (((-1)/(-2))*(-2) + ((-1)%(-2))) << endl;
}
:
0 1 1
0 1 1
0 -1 -1
0 -1 -1
-
. . ..
:
7*5 - 31.0/2 + 9*2/5.0
;
:
7*5 = 35
31.0/2 = 15.5
9*2/5.0 = 3.6
.
:
35 - 15.5 + 3.6 = 23.1
C++:
*, /, %,
+, -.
,
, , . ; ,
.
, .
:
1 + { 1 + 4 [ 6 + 2( 9 - 3.5 ) / 2.2 ] }
C++:
1 + ( 1 + 4 * ( 6 + 2 * ( 9 - 3.5 ) / 2.2 ) )
. !

.
, C++
.
, , ,
.
34 1

:
3.45
5 3.14159
:
3.45 / 5 * 3.14159
. , * / .
, : 3.45/5
3.14159. , :
3.45
3.14159
5
:
3.45/(5 * 3.14159)
,
3.45 .

1.10 C++

C++. ,
:
(72)
2.5 52 32
1 5
! :
cos(72 * 3.14159 / 180) / (1 + sqrt(5))
2.5 + sqrt(5*5 - 3*3)
: cos(3.14159 * 72 / 180), sqrt(5),
sqrt(5*5 - 3*3). C++ cos,
sqrt, . !
(72). 3.14159/180; : cos()
C++ . /180 .
C++ . ;
.
.
(function call).
,
, , .
:
,


.
. 1-1 .
. B (functions) -
(math) C++. -

#include <cmath>
:
35

cos(72 * 3.14159 / 180) / (1 + sqrt(5))

1.256637061 5

cos sqrt

0.309016994 2.236067977

0.309016994 / (1 + 2.236067977)
. 1-1
.

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << sqrt( 2.0 ) << " " << sqrt( 4.0*9 )<<endl;
cout << exp( 1.0 ) << endl;
cout << log( 1.0 ) <<" "<<log( exp( 1.0 ) )<<endl;
cout << sin( 3.141592653 / 3 ) << endl;
cout << cos( 3.141592653 / 6 ) << endl;
cout << atan( 1.0 ) << " = "<<4*atan( 1.0 )<<endl;
cout << pow( 10.0,3.0 )<<" "<<pow( 2.0, 0.5 )<<endl;
cout << fabs( -7.0 ) << " " << abs( 7 ) << endl;
}
1. sqrt: (square root) .
. ,
-. :
cout << sqrt( 2.0 ) << " " << sqrt( 4.0*9 )<<endl;
:
1.41421 6
2. exp: exp(x) ex, e .
e :
cout << exp( 1.0 ) << endl;
:
2.71828
3. log: .
. exp(). .. :
cout << log( 1.0 ) << " " << log( exp(1.0) ) << endl;
:
0 1
4. sin: ().
() . .. 60 (= /3):
cout << sin( 3.141592653 / 3 ) << endl;
:
0.866025
36 1

5. cos: ().
() . .. 30
(=/6):
cout << cos( 3.141592653 / 6 ) << endl;
:
0.866025
6. atan: . ,
, (/2, /2), .
(/4) = 1 : = 4(1),
, C++ . :
cout << atan( 1.0 ) << " = " << 4*atan( 1.0 ) << endl;
:
0.785398 = 3.14159
7. pow: pow(x, y) xy. ..
cout << pow( 10. 0,3.0 ) << " " << pow( 2.0, 0.5 ) <<endl;
:
1000 1.41421
8. abs, fabs: (absolute value) . abs()
, fabs() . ..
cout << fabs(-7.0) << " " << abs(7) << endl;
:
7 7

1.10.1 cmath math.h ;


#include <cmath>
#include <math.h>
; cmath math.h .
math C ( iostream, ,
C++). :
C++ () , ..
:
#include <iostream>
C c ( ),
..:
#include <cmath>
std, ..
std::fabs,
using namespace std.
C .h ( ), ..:
#include <math.h>
,
.
.
37

1.11
,
C++ . -
.
cout (field
width). :
cout.width(w);
w > 0, ( )
cout w . ..
:
cout.width( 4 ); cout << "abcdefghij";
cout.width( 4 ); cout << "ab";
cout.width( 6 ); cout << 1.1;
cout.width( 8 ); cout << 11;
cout.width( 10 ); cout << 0.0001 << endl;
:
abcdefghij__ab___1.1______11____0.0001
.
4 "abcdefghij", 10. 10 .
4 "ab", 2. 4 ,
( ) .
6 1.1, 3 . 6 ,
3 ( ) .
8 11, 2 . 8 ,
6 .
10 0.0001, 6 . 10 ,
4 .
, (preci-
sion). :
cout.precision( d );
d , d
. ..
cout.precision( 8 );
cout << 1234.5 << " " << 123456.78 << " "
<< 123456789.0123 << endl;
:
1234.5 123456.78 1.2345679e+08
, 8 .
cout.precision.
: 6.
C++ ,
, .
. :
cout.setf( ios::scientific, ios::floatfield );
(
cout.setf) . .. :
cout.precision( 8 );
cout << 1234.5 << " " << 123456.78 << " "
<< 123456789.0123 << endl;
38 1

:
1.23450000e+03 1.23456780e+05 1.23456789e+08
: d
:
"-",
,
d ,
e99 e999 .
, d , d + 6 d
+ 8 .
.
:
cout.setf( ios::fixed, ios::floatfield );
:
cout.precision( 8 );
cout << 1234.5 << " " << 123456.78 << " "
<< 123456789.0123 << endl;
:
1234.50000000 123456.78000000 123456789.01230000
, , ( 8)
.
:
cout.setf( 0, ios::floatfield );

1.12 C: printf()
( C C++)
printf().
.
printf()
cstdio iostream.
printf:
#include <cstdio>
#include <cmath>

int main()
{
printf( "%s%f) = %f\n", " (",
2.0, sqrt(2.0) );
}
:
(2.000000) = 1.414214
C++ cout , C stdout. printf()
. : , << cout printf()
stdout.
printf()
(format string) printf.
(format specifiers)
"%". .
39

"%s" :
( : " (").
"%f" :
( : 2.0).
")_=_".
"%f" : -
( : sqrt(2.0)).
, "\n" : , .
, %f (
) %e ( ), %d,
%s %c (
%d).
"%" .
%f %e -
. :
printf( "%4s%4s%6.1f%8d%10.4f\n",
"abcdefghij", "ab", 1.1, 11, 0.0001 );
:
abcdefghij__ab___1.1______11____0.0001
:
printf( "%6.1e %10.4e\n", 1.1, 0.0001 );
:
1.1e+00 1.0000e-04
C++, cout.
.

1.13
C++ (comments)
, . -
.
C++, :
"//", .:
cout << "1+1 = " << (1+1) << endl; //
//
"/*" "*/". ..
/* */
cout << 3.14159 / 2 /* = /2 */ << endl;

. !
,
,
.

1.14 ;
;
.
40 1

:
1 2 . :
int main()
{
cout << (1 + sqrt(2)) << endl
}
; ... ... 1 :
Undefined symbol 'cout' in function int main()
() cout !
:
#include <iostream>
using namespace std;
. 2 :
Function 'sqrt' should have a prototype in function int main()
:
#include <cmath>
. 3 :
Statement missing ; in function int main()
";" endl!
. :
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
cout << (1 + sqrt(2)) << endl;
}

include. :
cout << ...
#include <iostream>.

. #include <cmath>.
.
:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
1 + sqrt(2);
}
, ,
! ;
! :
cout << (1 + sqrt(2))...
41


1-1 :
1,0
56.000
-234a
89.5
1e1
+1.01e+01
5.e-1
1-2 :
1.0
1
-1
-1,0
78
999999
67.89
-8989
1-3 ,
C++.
.
7*12 + 3
7.*12 + 3
7.0*12 + 3
21 / 5 % 2
12 / 8
1. + 7/3
1.0 - 7 / 3
13 + 4 -12
5814
7/(12 - 11-3/7)
17 % 6/3


1-4 : , 2, , e, e2, e (e:
).
1-5 C++
:
1
1 e1 / 2 (60 o ) 2
1 5
(e: ).
1-6 C++
:
2 3 1 1 2 ( 3 1)
ln ln
2 1 2 1 2 4
(ln(x) () x).
1-7 ( )
:
42 1

) 10.5 cm 8.7 cm.


) 9.2 cm 5.3 cm.
) : (3,2) (5,8).
) x22x +3 x = 1,2,3
1-8 .
"*"
( 1.6).
1-9 1.9 :
,
. :
cout << (4./2) << " " << (4/2) << endl;
:
2 2
;
;
.: 1.11.

2

:

.
:

.
:

,




cin



:
2.1 .......................................................................................................................................... 44
2.1.1 () .................................................................................................................................... 46
2.2 ..................................................................................................... 48
2.3 ............................................................................................................................................ 51
2.4 ........................................................................................................................................... 55
2.5 C++ ............................................................................................................................. 55
2.6 ................................................................................................................................................. 58
2.7 - .............................................................................................. 58
2.8 C++ ................................................................................................... 62
2.8.1 typeid ..................................................................................................................... 62
2.8.2 sizeof................................................................................................................. 62
2.8.3 & * .............................................................................................................. 63
2.8.4 .................................................................................................................................. 64
2.9 ...................................................................................................................................................... 65
2.9.1 C ......................................................................................................................................... 66
2.10 * ......................................................................................................... 67
2.11 * ............................................................................................................................. 68
2.12 scanf(): printf() ............................................................................................................................ 69
2.13 , ... ...................................................................................................................................................... 71

43
44 2

2.14 ( ) .................................................................................................................. 71
..................................................................................................................................................................... 72
............................................................................................................................................................................... 72
............................................................................................................................................................................... 72
............................................................................................................................................................................... 73

:
... !

.
. -

;
-
.
-

( ) .
, (variable),
.
( C++, C,
C#, Pascal, Algol, Fortran ) ,
, (value) ,
.
(name).
(type).
: , , .
,
. :
(size), (bytes)
.
(address) .

. , , !

2.1
(.. Fortran)
. C++ -
. C ( Pascal, Ada ) -
.
.

. () .
(variable declaration) :
,
,
;.
45


:
double pi, e, distance, length;
int i, counter, j, number, integer;
:
int i;
double pi, e;
int metrntns, j, number, integer;
double distance, length;

int double,
C++. ;
,
.
, , int i
i int. , , , -
.
. ,
.
:
int double .
.
C++ :

:
double pi, e, distance( 0.0 ), length( 1.0 );
int i, counter( 0 ), j, number( 0 ), integer( 375 );
:
double pi, e, distance = 0.0, length = 1.0;
int i, counter = 0, j, number = 0, integer = 375;

.
:
,
-
.
,
.
.
, : -
, , , -
, . -
. 2-1, -
.

.
:
, , ,
,
46 2


counter 1245028 int 4 0
distance 1245044 double 8 0
e 1245052 double 8 ???
i 1245032 int 4 ???
integer 1245016 int 4 375
j 1245024 int 4 ???
length 1245036 double 8 1
number 1245020 int 4 0
pi 1245060 double 8 ???
. 2-1
: .

.
() .
(: ???).


.
, ,
, , -
. ..:
int x( 1 ), y( 2 ), z( x+y );
double q( 5 ), r( 1+sqrt(q) );

.

2.1.1 ()
-
. -
(identifiers).
:
= ;
C++ :

(_, underscore).
, .
.
= | , | , ;
= "_" | ;
:
.
- (keywords) C++1.
: (__).

1 - . C.
47


: C++,
: sqrt, cout . , .., :
double sqrt;
, , sqrt
2. , :
main, sqrt -
.
:
ALFA OMEGA _omikron Nikos prwto_programma
QWERTY aSdFgH program_1
:
12thprogram :
SYNTHESH$ : '$'
int : -
Prwto Progr :
MakryAnagnw
ristiko :
, C++ ( C)
:
. , : Paradeigma, PARADEIGMA, PaRaDeIgMa, pARADEIGMa
C++.
C++ . ,
.
, , :
. , ,
3.
:
.
.. ,
. a, b
perifereia, aktina ( C r
).
(readable).

, .
,
(documentation) . ,
(self-documented).

. ,
.

2 , std::sqrt.
3 () , .
48 2

2.2

. :
.
C++. , , -
:
.
:
, : ,
, .:
.
:
1 5 .
:
double x;
:
x = 1 + sqrt( 5 );
;
: 1 + sqrt(5).
x (
x).
: ,
x 1 + sqrt(5).
.
(assignment statements)
. ,
:
"="
"=" ( ) 4. :
.
.
.

:
pi = 4*atan(1);
e = exp(1);
number = 4*10 + 2*30;
integer = (100 % 51)*4 + 7;
:
x + 1 = 7; x + y = 12; sqrt(x) = 12;
( "=" ).

:
;

4 ; ; C++ ! -
= ! ...
49


double a, b, c;
. ,
: a b c
integer + length*3 i + j/2 double double double
sqrt(pi) + 1.0 ??? ??? ???
log(e+1) - 1/pow(e,2)

c = a + b;

. , a b c
- double double double

. - ??? ??? ???


cout << ,
a = 3.0;
.
: a b c
double double double
#include <iostream>
3.0 ??? ???
using namespace std;
int main()
{
int k; b = 4.5;

k = 3; a b c
cout << " k = " << k << endl; double double double
} 3.0 4.5 ???
:
k = 3
cout << c = << c << endl;

a b c
int k. double double double
k 3. cout 3.0 4.5 ???
<< : " k =
" k.
_k_=_ . 2-2
k. . 1.
, -
:
1
: c = a + b a = 3, b = 4.5,
c = 7.5. , :
#include <iostream>
using namespace std;
int main()
{
double a, b, c;

c = a + b;
a = 3; b = 4.5;
cout << " c = " << c << endl;
}
:
c = 4.24613e-314
;! : , a, b, c
. 0 ,

. :
50 2

c = a + b;
;
. 2-2. a, b,
( ??? ) , -
c. a = 3; b = 4.5
c = a + b .
(warning): possible use of 'a'
before definition in function main() ( a
main(), 'b')

:

.
.
.
2
, -
. .
a b.
: a b b a. :
#include <iostream>
using namespace std;
int main()
{
int a( 10 ), b( 20 );

a = b; b = a;
cout << " a = " << a << " b = " << b << endl;
}
:

int a( 10 ), b( 20 );

a b
int int

10 20

a = b; b = a;

a b a b
int int int int

20 20 20 20

cout << A = << a << B = << b << endl;

a b
int int

20 20

. 2-3 . 2.
51

a = 20 b = 20
! ; a = b, a 20, b.
b = a b () 20 a.
. 2-3 .
; a, a =
b b. -
s, a, b. :
#include <iostream>
using namespace std;
int main()
{
int a( 10 ), b( 20 ), s;

s = a; a = b; b = s;
cout << " a = " << a << " b = " << b << endl;
}
:
a = 20 b = 10

:
-
( b a b = a).
, (
).
: ;
; !

.
-
.

2.3
,
. -
.
, -
, :
cin >> ;
, -
">>".
cout,
(default Input
device (file) ) C++, () -
cin.
using namespace std
:
using std::cin;
cin >> .
; ( ),
52 2


<enter>. ;
(
) .
,
...

. ,
, <enter> . -
, .
.
.
.

1
:
#include <iostream>
using namespace std;
int main()
{
int k, j;
double x, y;

cin >> k >> j >> x >> y;


cout << k << ' ' << j << ' '
<< x << ' ' << y << endl;
}
,
(cursor) .
cin >> k >>. 4 . -
:
17 -375 145.78 31e4
<enter>. :
17 -375 145.78 310000
cout << k
, , . cin
>> k; , 17,
, . k, , 375, j, , 145.78,
x , 31e4, y, :
cin >> k >> j >> x >> y;

17 -375 145.78 31e4
:
___________17 _-375 ___________145.78 _314
:
31e4 17 -375 145.78
! k, int
31e4 , int,
, 1.7, 1.8. -
gcc (Dev C++):
31 42 5.28418e-308 9.92631e-315
53

Borland C++ v.5.5:


31 0 2.12414e-314 ( runtime error)
, double -
int.
,
:
17 -375 145.78 31e4 123
:
17 -375 145.78 310000
123; : .
! ,
123.
; . ,
<enter>, . -
. !


( ) -
. :
2

. -
: -
:
#include <iostream>
using namespace std;
int main()
{
int a1, a2, sum;

cout << " " << endl;


cin >> a1 >> a2;
sum = a1 + a2;
cout << " (" << a1 << ") + (" << a2 << ") = "
<< sum << endl;
}
, :

_
:
5 7
:
(5) + (7) = 12
,
, , :
57 -17
:
(57) + (-17) = 40
, cin >> a1 >> a2 : a1 = 5; a2 = 7
.

54 2

. .
3
, : ax2 + bx + c = 0 :
b
x : = b2 - 4ac
2a
a, b, c
.
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, b, c;
double x1, x2;
double delta;

cout << " " << endl;


cin >> a >> b >> c;
cout << " a = " << a << " b = " << b
<< " c = " << c << endl;
delta = b*b - 4*a*c;
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
cout << " 1 = " << x1
<< " 2 = " << x2 << endl;
}
, :

_
:
1 3 -10
:
a = 1 b = 3 c = -10
1 = 2 2 = -5
! : :
:
2 3 4
(gcc - Dev C++):
a = 2 b = 3 c = 4
1 = -1.#IND 2 = -1.#IND
(Borland C++ 5.5):
a = 2 b = 3 c = 4

sqrt: DOMAIN error

sqrt: DOMAIN error


1 = +NAN 2 = +NAN
; ( ) sqrt() -
. , -
( = 32 424 = 23) ... 5.
, ,
( ).

5 #IND; ...
55

2.4
: (=
3.14159...) , g (= 9.81
m/sec2).

vP = -sqrt( 2*h*9.81 );
(!):
vP = -sqrt( h*19.62 );
-
9.81 ( 19.62); , ,
g
10 9.8.
C++, ,
:
const double g( 9.81 ); // m/sec
:
vP = -sqrt( 2*h*g );
; ; -
, g = 5.32 -
. : Cannot modify a const object in function main(). ,
, -
.
:
const double pi( 4*atan(1) ); // =
() !

2.5 C++
int C++ -
, -2147483648 2147483647. -
int
C++ :
#include <iostream>
#include <climits>
using namespace std;
int main()
{
cout << "INT_MIN = " << INT_MIN << " INT_MAX = "
<< INT_MAX << endl;
}
gcc (Dev C++) Borland C++ :
INT_MIN = -2147483648 INT_MAX = 2147483647
, :
int number;
number
int.
int C++ . . 2-1
(integral) . :
; long int long
56 2


..
signed char char -128 .. 127 8
short int short -32768 .. 32767 16
int -2147483648 .. 2147483647 32
long int long -2147483648 .. 2147483647 32
long long int 9223372036854775808 .. 9223372036854775807 64
unsigned char 0 .. 255 8
unsigned short int 0 .. 65535 16
wchar_t 0 .. 65535 16
unsigned int 0 .. 4294967295 32
unsigned long int 0 .. 4294967295 32
unsigned long long int 0 .. 18446744073709551615 64
bool false (0) .. true (1) 8
. 2-1 C++. char signed char
(-128 .. 127) unsigned char (0 .. 255). wchar_t unsigned
short int. bool . long long int 64
C++11.
long int.6 : short -
(2 4 long int).
char !7 unsigned int
unsigned long int unsigned long long int.
: . C++
:
short int "" int "" long int "" long long int
""
. ( ). ,
Borland C++ ( gcc) short int "<" int "=" long int.
double -
. double -
. , , -
.
1.7.1.

double ( ):
#include <iostream>
#include <cfloat>
using namespace std;
int main()
{
cout << "DBL_MIN = " << DBL_MIN
<< " DBL_MAX = " << DBL_MAX << endl;
cout << "DBL_EPSILON = " << DBL_EPSILON << endl;
}
:
DBL_MIN = 2.22507e-308 DBL_MAX = 1.79769e+308
DBL_EPSILON = 2.22045e-16

6 64 C++11. gcc
Borland 5.5.
7 char, wchar_t bool . 4.
57



.
..
double 5.0e324 .. 1.7e+308 15-16 64
float 1.5e45 .. 3.4e+38 7-8 32
long double 1.9e4951 .. 1.1e+4932 19-20 80
. 2-2 (Borland) C++.


1 1:
= min{ u: R u > 0 (1 + u)fp 1fp u }
( qfp q double).
(epsilon) . double Borland C++:
= 2.220446e-16
; 1 + x, x [0,),
double 1.
cout << "DBL_EPSILON/2 = " << DBL_EPSILON/2 << endl;
cout << 1 + DBL_EPSILON/2 << endl;
:
DBL_EPSILON/2 = 1.11022e-016
1
:
double length;
length -
double.
C++ (floating point)
double. . 2-2
.
C++ : -
.
. -
; (suffix):
l L long,
u U unsigned,
f F float,
int,
double.

123 (int) 123L (long)
123U (unsigned) 123LU (unsigned long)
1.23 (double) 1.23f (float) 1.23L (long double)

, . -
; double ; ! :
double ( float long double) -
, .
,
( double) , .
58 2

(.. )
.
:
double int
.
double ,
, int.
-
. -
:
-
, .

2.6
, . :
double d;
:
cin >> d;
cout << d << endl;
cin >> d :
1e50000
:
4.24399e-314 (gcc - Dev C++)
+INF (Borland C++)
, .
.
. -
-
(modulo 2n).8

2.7 -

.
:
h .
h
:
)
) .
. : g = 9.81 m/sec.
Oz ,
, :
1
z 2 at2 v0t z0
:

8 .
59

v = v0 + at
, :
a : ,
v0: ,
z0: .
:
a = g v0 = 0 z0 = h
:
1
z = 2 gt + h
:
v = gt
z = 0 t
tP. tP :
1
0 = 2 g tP + h
:
tP = 2 h / g
:
vP = g tP = 2 gh
:
const double g( 9.81 ); // m/sec
double h, tP, vP;
:
: (g == 9.81) && (h 0)
: (tP == 2h / g ) && (vP == 2 gh )
:

.
, -
.
. :
h
tP, vP
tP, vP
.
, h,
. , h :
cout << " m: "; cin >> h;
tP, vP :
tP = sqrt(2*h/g);
vP = -sqrt(2*h*g);
.
: vP :
vP = -g*tP;
, -
.
. .
tP, vP :
60 2

cout << " = " << tP << " sec" << endl;
cout << " = "
<< vP << " m/sec" << endl;
:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const double g( 9.81 ); // m/sec2,
double h, // m,
tP, // sec,
vP; // m/sec,
// h
cout << " m: "; cin >> h;
// tP, vP
// (g == 9.81) && (0 h DBL_MAX)
tP = sqrt( 2*h/g );
vP = -sqrt(2*h*g);
// (tP (2h/g)) && (vP -(2hg))
// tP, vP
cout << " = " << h << " m" << endl;
cout << " = " << tP << " sec" << endl;
cout << " = "
<< vP << " m/sec" << endl;
}
. :
m: _
:
m: 80
:
= 4.03855 sec
= -39.6182 m/sec

m,
:
) m,
) lt.
.
:
.
.
.
.
-
.
(echo)
.
:
.
.
.
.
.
:
61





.
: pi, r, h, s, v, ,
, .
.
m3SeLt, 1000 . -
double.
:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
const double pi( 4*atan(1) ); // =
const double m3SeLt( 1000 ); // lt/m
double r, h, s, v;
//
cout << " m: "; cin >> r;
cout << " m: "; cin >> h;
cout << " :";
cout << " . = " << r << " m = "
<< h << " m" << endl;
//
s = pi*r*r; //
//
v = s * h; //
v = m3SeLt * v; // lt
//
cout << " = " << s << " m" << endl;
cout << " = " << v << " lt" << endl;
}
, :
: _
:
: 1.2
:
: _
:
: 1.8
:
: . = 1.2 m = 1.8 m
= 4.52389 m
= 8143.01 lt
:
: 1.2 1.8
: : . = 1.2 m = 1.8 m
= 4.52389 m
= 8143.01 lt
;
(1.2) (1.8). 1.8 cin >> r;
cin >> h;. : ,
62 2

<enter>
.

2.8 C++

().
-
, , ( )
. C++ .
C++
, (. 2.1):
double pi, e, distance( 0.0 ), length( 1.0 );
int i, counter( 0 ), j, number( 0 ), integer( 375 );
. 2.1.
,
C++ .
.

2.8.1 typeid
:
cout << typeid(pi).name() << " "
<< typeid(integer).name() << endl;
9:
double int
: pi double integer int.
, :
typeid( ).name()
<>.
(#include) typeinfo.
. 1-8:
cout << typeid(4./2).name() << " "
<< typeid(4/2).name() << endl;
:
double int

2.8.2 sizeof
. 2-1, 2-2 ,
, .
C++; sizeof
. :
cout << (sizeof number) << " "
<< (sizeof length) << endl;
:
4 8

9 gcc (.. Dev C++) : d i.


63

: number 4 (= 32 )
length 8 .
, :
"sizeof",
"sizeof", "(", , ")"
"sizeof", "(", , ")"
:
cout << (sizeof (4./2)) << " "
<< (sizeof (4/2)) << endl;
cout << (sizeof (double)) << " "
<< (sizeof (int)) << endl;
10:
8 4
8 4

2.8.3 & *
&. ..:
cout << &number << " " << number << endl;
:
0x343f2744 0
. (0) number, .
,
, number. , -
!
:
number , .
number,
&number

.
&number (referencing)
- (pointer)
() . , C++, -
.
- p,
p; , ,
&; C++ *: -
p *p. , ,
*(&number) number. , :
cout << &number << " " << number
<< " " << *(&number) << endl;
:
0x343f2744 0 0
:
*(&number) = 4;
cout << &number << " " << number
<< " " << *(&number) << endl;

10 . 1-8.
64 2

:
0x343f2744 4 4
, = ! ! -
*(&number) number.
* - (dereferences) - .
: * -
! ; , * -
-.

2.8.4
. 2-1
.
-
.
, :
double pi, e, distance( 0.0 ), length( 1.0 );
int i, counter( 0 ), j, number( 0 ), integer( 375 );
8 :
cout.width( 8 );
cout << "integer" << " " << &integer << " ";
, 6 , :
cout.width( 6 );
cout << typeid(integer).name() << " "
<< (sizeof integer) << " ";
:
cout << integer << endl;
:
#include <iostream>
#include <typeinfo>
using namespace std;
int main()
{
double pi, e, distance( 0.0 ), length( 1.0 );
int i, counter( 0 ), j, number( 0 ), integer( 375 );

cout << " \t\t\t\t" <<endl;


cout.width( 8 );
cout << "counter" << '\t' << &counter << '\t';
cout.width( 6 );
cout << typeid(counter).name() << '\t'
<< (sizeof counter) << '\t';
cout << counter << endl;

cout.width(8);
cout << "distance" << '\t' << &distance << '\t';
cout.width(6);
cout << typeid(distance).name() << '\t'
<< (sizeof distance) << '\t';
cout << distance << endl;
//
}
( ) :

counter 0x12FF64 int 4 0
distance 0x12FF74 double 8 0
65

e 0x12FF7C double 8 2.12414e-314


i 0x12FF68 int 4 1245072
integer 0x12FF58 int 4 375
j 0x12FF60 int 4 1
length 0x12FF6C double 8 1
number 0x12FF5C int 4 0
pi 0x12FF84 double 8 2.122e-314
:
, ; Excel Word
.
e, i, j pi : -
. , e, -
double.

2.9
T C++ ,
static_cast<T>
T ( ).
. :

:
cout << static_cast<int>(9.916) << " "
<< static_cast<int>(-9.916) << endl;
:
9 -9
: 9.916 9.916 int -
static_cast<int>. .
:
cout << static_cast<double>(901234567L) << " "
<< static_cast<float>(901234567L) << endl;
:
9.01235e+08 9.01235e+08
: 901234567L
double static_cast<double>
float static_cast<float>.
, 9 6.
; :
cout.precision(10);
cout << static_cast<double>(901234567L) << " "
<< static_cast<float>(901234567L) << endl;
:
901234567 901234560
long float
.

: int
2147483647
static_cast<int>( 2345678901.23 )
66 2

C++ . : T
minT maxT static_cast<T>(x)

minT static_cast<T>(x) maxT
()
(typecasting casting)11.

. .. :
double x( 123.457 );
int i;
i = static_cast<int>( x );
cout << " x = " << x << " i = " << i << endl;
:
x = 123.457 i = 123
i = static_cast<int>( x ) :
i = int( x );
. , :
T(v) static_cast<T>(v)
.
( ) : ,
:
int k( 10 ), n( 3 );
:
cout << " k/n = " << k/n << endl;
:
k/n = 3
; :
cout << " k/n = " << static_cast<double>(k)/n << endl;
:
cout << " k/n = " << double(k)/n << endl;
:
k/n = 3.33333

2.9.1 C
C++ C
:
(T) v 12 static_cast<T>(v)
,
(unsigned long int) -1234567890L
:
static_cast<unsigned long int>(-1234567890L)

11 , .
12 , ,
.
67

2.10 *
C++ .
: x b , -
:
x = x + b;
: x b,
x. C++ :
x += b;
:
x += ; : x = x + ;
x -= ; : x = x - ;
x *= ; : x = x * ;
x /= ; : x = x / ;
x %= ; : x = x % ;
/= %= .
: x .

1, :
++x; : x = x + 1; x += 1;
--x; : x = x - 1; x -= 1;
, : x++
x-- / x 1. ++x --x
.13
:
#include <iostream>
using namespace std;
int main()
{
int x, y;
int a = 1, b = 2;

x = 5; x += a+b; cout << x << " ";


x = 5; x -= a+b; cout << x << endl;
x = 5; x *= a+b; cout << x << endl;
x = 5; x /= a+b; cout << x << " ";
x = 5; x %= a+b; cout << x << endl;

x = 5; ++x; cout << x << " ";


x = 5; --x; cout << x << endl;
x = 5; x++; cout << x << " ";
x = 5; x--; cout << x << endl;
}
:
8 2
15
1 2
6 4
6 4
' .

13 C++ C!
68 2

2.11 *
. E C++.
:
(. 0).
(. 2).
(. 3)
. ; C++ :
+ - - +12 - + - -x
:
+(-(-(+12))) -(+(-(-x)))
.
, (. 5)
. :
2*x/y*z/5 : (((2*x)/y)*z)/5. :
(x*y)/(w/u) x*y w/u.
(. 6)
, .

, ().
a b. :
1. a, b long double, long
double .
2. , a, b double,
double .
3. , a, b float,
float .
4. , a, b ( ) , :
( ) a, b (char, short int,
signed unsigned), int unsigned int (
int)
a, b unsigned long,
unsigned long .
5. , a, b long int unsigned int,
unsigned int long int
unsigned int long int

unsigned long int.


6. , a, b long, long
.
7. , a, b unsigned,
unsigned .
8. int.
+, -, *, /
.
+, - ().
.
,
. , ,
. :
69

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

a = SHRT_MAX + 10;
cout << SHRT_MAX+10 << " " << a << endl;
cout << sizeof(SHRT_MAX+10) << " " << sizeof(a) << endl;
}
:
32777 -32759
4 2
.
: SHRT_MAX + 10 4
a 2...

2.12 scanf(): printf()


C, printf()., scanf(). : , >>
cin scanf() stdin, C
.
. 1 2.3 scanf()
printf():
#include <cstdio>
using namespace std;
int main()
{
int k, j;
double x, y;

scanf( "%d %d %lf %lf", &k, &j, &x, &y );


printf( "%d %d %f %f\n", k, j, x, y );
}
scanf printf
.
: scanf ( ) ,
. .

%d &k. :

( int)
&k.
%d &j.
%lf &x :

double
&x.
%lf
&y.
70 2

%d . d
(modifier) h
short int l long int ( int).14
%f ( %e %E %f %g
%G). f l
double L long double ( float).
:
C, C++
C. O C .
:
#include <stdio.h>

int main()
{
int k, j;
double x, y;

scanf( "%d %d %lf %lf", &k, &j, &x, &y );


printf( "%d %d %f %f\n", k, j, x, y );
}
test_C_IO.c C. -
.
. 3 2.3 scanf printf:
#include <cstdio>
#include <cmath>
using namespace std;
int main()
{
double a, b, c;
double x1, x2;
double delta;

printf( " \n" );


scanf( "%lf %lf %lf", &a, &b, &c );
printf( " a = %f b = %f c = %f\n", a, b, c );
delta = b*b - 4*a*c;
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
printf( " 1 = %f 2 = %f\n", x1, x2 );
}

. :

printf( "%s\n", " " );

printf( " \n" );

printf( "%s %f %s %f %s %f\n",
" a =", a, " b =", b, " c =", c );

printf( " a = %f b = %f c = %f\n", a, b, c );

14 %u .
71

2.13 , ...

. -
. .
/ -
. 15
! (,
...)
, :
";" C++ (statement terminator).
.
( )
.

, cin >> .
,
:
, :
, , . 17.0
, 17,0 1.7e1. 17 ! , , -
INT_MAX.
,
. "." ",".
,
. !

2.14 ( )
,
.
.
/ .
/ .
, ()
C++ .
;
.

15 ; debugging, o oo

, .
o bugs (, oo). o oo .
72 2


2-1 :
#include <istream>
using namespace std;
int main()
{
int i, j, k;

i = 5; j = 7; k = 10;
cout << i << ' ' << (i+1) << ' ' << (i+j)
<< ' ' << (i + j*k) << endl;
k = i + j; cout << k << endl;
j = j + 1; cout << j << endl;
i = j + 2*i + j; cout << i << endl;
}
(, ),
.
2-2 :
#include <iostream>
using namespace std;
int main()
{ double first, second, realResult;
int third, intResult;

cin >> first >> second >> third;


realResult = first + second + third;
intResult = first + second - third;
realResult = realResult - intResult;
intResult = intResult - realResult;
cout << realResult << intResult << endl;
}
:
1.5e1 8.1 5 7.41e-5 33.0
2-3 x
:
1
1 + ex/2 xx + xx/2
1 x
x -x e x / 2 e x / 2
xx/3 + x3x
2 x 2
e .
2-4
x :
x, x, x, x, x, x


2-5 : ( -
, 1) x ( ) logx x.
.: : logx = lnx/ln.
73

2-6 -
, (%).
.
2-7 , x, y,
r, . x > 0.
: ) atan ) atan2.
.: r = x 2 y 2 , = (y/x).
2-8 2%, -
, .

.
2-9 R1 R2 , R = R1
+ R2. R1 R2
R.
2-10 R1 R2 , :
R1 R2
R
R1 R2
R1 R2
R.
2-11 C
R . U
= U0(2t).
U0 (V), (Hz), C
(F), R () :
U = U0 / 2 ,
= 2,
1
= (C ) 2 ,
R2
i0 i ,
U i, = (CR).
2-12 2.5
int. INT LONG,
SHRT, CHAR, UINT, ULONG, USHRT, UCHAR, . 2-1
long int, short int, char, unsigned int, unsigned long int, unsigned
short int, unsigned char, .
.

double. DBL FLT LDBL
float long double .
. 2-2.


2-13 , -

.
74 2

3
*
:

.
:
.
:




:
3.1 .................................................................................................................................. 76
3.2 .............................................................................................................................. 77
3.3 ............................................................................................................................... 77
3.4 ................................................................................................................................. 77
3.5 true false ........................................................................................................................ 79
3.6 ................................................................................................................ 79
3.6.1 ................................................................................................................. 79
3.6.2 ( ) .............................................................................. 80
3.6.3 ............................................................................................................... 81
3.7 .......................................................................................................................................................... 82
3.8 ....................................................................................... 83
3.9 .......................................................................................................................... 84
3.10 .................................................................................................................................................... 85
..................................................................................................................................................................... 86
............................................................................................................................................................................... 86
............................................................................................................................................................................... 86
............................................................................................................................................................................... 87

:
0.4:
,
,
(
).

75
76 3

0.3 0.4
,
(verification) (correctness proof) .
, 2.2 :

.
(program testing) -
!
.
.
; , , -
;

3.1
.
2-1 2-2. :
int number;
unsigned int uNumber;
double rNumber;
number
int -
:
( number Z ) && ( INT_MIN number INT_MAX )
(invariant) int.
, uNumber :
( uNumber N ) && ( 0 uNumber UINT_MAX )1
rNumber:
( rNumber Q ) && ( -DBL_MAX rNumber DBL_MAX )
.
; ..:
int number( 37 );
:2
( number == 37 ) && ( number Z ) && ( INT_MIN number INT_MAX )
: number == 37 number Z
INT_MIN number INT_MAX. ,
number == 37
.
:
int number( 3.0/2 );
(warning) convert-
ing to 'int' from 'double' number 1.

int number( );
:

1 UINT_MAX;;; . 2-12;
2 ==; = C++ ,
, == . .
* 77

( number == static_cast<int>() ) &&


( number Z ) && ( INT_MIN number INT_MAX )
,
T x( );
static_cast<T>(), :
( x == static_cast<T>() ) && IT( x )
IT T,
T.

3.2
:
. , P

cout << number;
.

.
, , :
cin >> number;
:
( number Z ) && ( INT_MIN number INT_MAX )
number (.. number == 37) .

3.3
g .
g == 9.81 .
: :
const T cn( c );
3 cn == c IT(cn) T:
( cn == c ) && IT( cn )

3.4

.
double x;
int y;
:
x = 7; // x == 7.0
y = x + 4; // y == 11

: ,
, .

3 : , .
78 3

, ,
, ..:

double x, a, b;
:
x = pow( a + b, 2 ) + 1;
a == a0, b == b0, a0, b0
:
|a0 + b0|
x ;
:
(a0 + b0)2 + 1 = (|a0 + b0|)2 + 1
: |a0 + b0| , :
= (a0 + b0)2 + 1 5/4
:
x = (a0 + b0)2 + 1 5/4
:

v T
v = P( static_cast<T>() )
v =

v = P( v ),
P( static_cast<T>() ) v static _cast<T>( ).
.
:
1. P( static_cast<T>() )
v. ,
. , ,
:
(a == a0) && (b == b0) && (|a0 + b0| )

x = pow( a + b, 2 ) + 1;
.
2. , v v = .
, x = pow(a + b,
2) + 1 x == 0. ,
-DBL_MAX x DBL_MAX double x. x == 0
x = (a0 + b0)2 + 1 5/4.
:
v = ,
v = P( v )

v = P( static_cast<T>() ), -
P( v ) v static_cast<T>( ).
, .
* 79

3.5 true false


:
. : true. :
(x 0) || (x < 0)
true, false :
. ..
(x 0) && (x < 0)

3.6
, ,
.
, , .
,
(program specifications).
. :
: (a == a0) && (b == b0)
: (a == b0) && (b == a0)
: (a == a0) && (b == b0)
: (a == b0) && (b == a0).
;
:
-
.
( )
.

.
.
, , , .

3.6.1
.

.
:
P(static_cast<T>()) { v = } P(v) P(v) :
1. P(static_cast<T>()).
2. v. v ,
.
3. &&
v.

:
// (a == a0) && (b == b0)
( s) a.
s = a. ;
80 3

.
s a. :
1. : (a == a0) && (b == b0).
2. s, .
3. a a == a0 a s:
// (a == a0) && (b == b0)
s = a;
// (a == a0) && (b == b0) && (s == a0)
, a b (a = b).
. , a
b. :
1. : (a == a0) && (b == b0) && (s == a0).
2. , a: (b == b0) && (s == a0).
3. b b == b0 b a:
// (a == a0) && (b == b0)
s = a;
// (a == a0) && (b == b0) && (s == a0)
a = b;
// (a == b0) && (b == b0) && (s == a0)
, b a, s. , b (b
== b0) b , s (b ==
a0):
// (a == a0) && (b == b0)
s = a;
// (a == a0) && (b == b0) && (s == a0)
a = b;
// (a == b0) && (b == b0) && (s == a0)
b = s
// (a == b0) && (b == a0) && (s == a0)
;
. ... :
(a == a0) && (b == b0), : (a == b0) && (b == a0) && (s ==
a0). . , .4, (P && Q) P , P
(a == b0) && (b == a0) Q (s == a0) :
((a == b0) && (b == a0)) && (s == a0) ((a == b0) && (b == a0))
(1), 0.4.1,
.

3.6.2 ( )
, : ( )
.
.
,
, .

: Q
E, ; -
,
3.4, :
P(static_cast<T>()) { v = } P(v) P(static_cast<T>())
:
* 81

1. P(v).
2. v static_cast<T>().

:
// (a == a0) && (b == b0)
s = a; a = b; b = s;
// (a == b0) && (b == a0)
:
b = s;
// (a == b0) && (b == a0)
; , b
s. :
1. : (a == b0) && (b == a0).
2. b s: (a == b0) && (s == a0).
:
s = a; a = b;
// (a == b0) && (s == a0)
b = s;
// (a == b0) && (b == a0)
a = b.
a b. :
1. : (a == b0) && (s == a0).
2. a b: (b == b0) && (s == a0).
:
s = a;
// (b == b0) && (s == a0)
a = ;
// (a == b0) && (s == a0)
= s;
// (a == b0) && (b == a0)
, s = a
(b == b0) && (s == a0). s a. :
1. (b == b0) && (s == a0)
2. s a (b == b0) && (a == a0).
:
// (b == b0) && (a == a0)
s = a;
// (b == b0) && (s == a0)
a = b;
// (a == b0) && (s == a0)
b = s;
// (a == b0) && (b == a0)
: (b == b0) && (a == a0)
.
: && , (a == a0) &&
(b == b0) (b == b0) && (a == a0). .

3.6.3
, :
; : ;
82 3


.
.

:
:
// (a == b0) && (b == a0)
b == a0,
b = s s == a0. , a
= b0, a = t t == b0:
// (t == b0) && (s == a0)
a = t; b = s;
// (a == b0) && (b == a0)
(t == b0) && (s == a0);
,
s = a; t = b (a == a0) && (b == b0), .
, :
// (a == a0) && (b == b0)
s = a; t = b;
// (t == b0) && (s == a0)
a = t; b = s;
// (a == b0) && (b == a0)
, .

3.7

:
; !
, , !
: -- -
(0.5).
4.
-
.
;
! ,
--
.
.
, , ,
.
:
.
() s == a0 .
:

, C++ ( ). ,

4, .
* 83

, , -
.
,
.
,
; , .
(verification conditions)
.

3.8

( 2.7) ()
.
2.5 double ( float long
double) . ... (
double) []. , 1.7.1 :
cout.precision(20);
cout << 12.34567890123456789 << endl;
:
12.34567890123456734884
. 2-2
double 16 . :
12.34567890123457
pow:
v = pow(0.3,4.0); cout << " 0.3^4 = " << v << endl;
v = pow(0.7,2.0); cout << " 0.7^2 = " << v << endl;
:
0.3^4 = 0.0081
0.7^2 = 0.4899999999999999
.
float (
8 ):
cout.precision(8);
v = pow(0.3f,4.0); cout << " 0.3^4 = " << v << endl;
v = pow(0.7f,2.0); cout << " 0.7^2 = " << v << endl;
:
0.3^4 = 0.0081000013
0.7^2 = 0.48999998
; ,
(.. double), .
:
: (tP == 2h / g ) && (vP == 2 gh )
:
: (tP 2h / g ) && (vP 2 gh )

:
: (|tP - 2h / g | < TA) && (|vP + 2 gh | < VA)
84 3

TA VA , . ; tP
2h / g TA vP
, 2 gh , VA.
, :
: (|tP - 2h / g | < TR 2h / g ) && (|vP + 2 gh | < VR 2 gh )
TA, VA, TR VR
() .
. TR = VR =
5104. , float .
; double,
, ,
"" "==".
.

3.9
: ;
:
: (g == 9.81) && (h 0)
: (tP 2h / g ) && (vP 2 gh )
:
// (g == 9.81) && (0 h DBL_MAX)
tP = sqrt(2*h/g);
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))
:
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))
;
, :
(tP 2h / g ) && (gtP 2hg )
:
tP = sqrt(2*h/g);
// (tP (2h/g)) && (gTp (2hg))
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))
tP = sqrt(2*h/g);
:
(sqrt(2h/g) 2h / g ) && (gsqrt(2h/g) 2hg )
:
g g 0,
: 2h/g 0
2hg 0 ( ).
:
(g 0) && (hg 0) && (sqrt(2h/g) 2h / g ) && (gsqrt(2h/g) 2hg )
, (g == 9.81) && (h 0)
hg 0
g == 9.81 g 0
* 85

sqrt , ,
, (sqrt(2h/g) 2h / g ) && (gsqrt(2h/g) 2hg ).
g == 9.81
,
g.
! h 0 .

.
: h
; .
h : 0 h DBL_MAX. :
tP = sqrt(2*h/g);
:
0 2h 2DBL_MAX
5 ,
g :
(2/g)h (2/g)DBL_MAX < DBL_MAX, 2/g < 1
, .. ,
:
tP = sqrt((2/g)*h);
, tP :
2
0 tP == sqrt((2/g)h) g
DBL _ MAX

:
vP = -g*tP;
tP, g, :
2
0 g sqrt((2/g)h) g g
DBL _ MAX

, g 2 / g DBL _ MAX == 2 g DBL _ MAX DBL_MAX


: 2g < DBL_MAX. double,
DBL_MAX 10308. DBL_MAX g sqrt(2h/g)
DBL_MAX .
-
: tP = sqrt(2*h/g) : tP =
sqrt((2/g)/h). : vP = -g*tP
, vP = -sqrt(2*g*h), -
.

3.10

. .
.

( )

5 ! h >
DBL_MAX/2 . !
.
86 3

. 0.
,
(.. ) .
;
! .
.


3-1 :
int k, sum;
:
// sum == (k - 1)*k/2
sum = sum + k;
k = k + 1;
// sum == (k - 1)*k/2
3-2 :
double x, y, z;
:
// z == y/2 - 1
x = z + 1; x = x + y/2; z = z + 1;
// (x == y) && (z == y/2) }


3-3 , , ,
:
a = a - b; b = b + a; a = b - a;
. .
3-4 :
int d1, d2, q, r;
:
// (r d2) && (r 0) && (d1 = q*d2 + r)
q = q + 1;
r = r - d2;
// (r 0) && (d1 == q*d2 + r)
3-5 :
int k, x, y;
:
// true
k = 0; x = 1; y = 1;
// (y = 2k+1) && (x == (k+1)2)

// (y == 2k+1) && (x == (k+1)2)


k = k + 1; y = y + 2; x = x + y;
// (y == 2k+1) && (x == (k+1)2)
* 87


3-6 (double) x static_cast<long> (x);
static_cast<long> (, , ).
.: x 0 x < 0.
3-7 :
a, b, c (a b c a).
.
88 3

4
bool, char

:
bool char.
.
:

bool.
( ).
:
bool

assert

char, signed char, unsigned char


typedef
:
4.1 .............................................................................................................................. 90
4.1.1 ! ........................................................................................................................... 93
4.2 ............................................................................................................... 94
4.3 : assert() ...................................................................................................... 95
4.4 bool ..................................................................................................................................................... 97
4.4.1 false true ............................................................................................................. 99
4.5 char..................................................................................................................................................... 99
4.5.1 char.....................................................................................................101
4.6 char ...................................................................................................................... 103
4.7 wchar_t ........................................................................................................................................... 106
4.8 .................................................................................................................................................... 106
4.9 ( ) ................................................................................... 107
4.10 ........................................................................................................................................ 108
................................................................................................................................................................... 109
.............................................................................................................................................................................109
.............................................................................................................................................................................109
.............................................................................................................................................................................109

89
90 4

:
,
. :
(1 true 0 false) , cout << ,
,
( ):
.
bool.
char wchar_t.
. 2 . ;
:
bool b( true );
char c1( ' ' ), c2( '!' ), c3;
int j;
:
j = 32*b;
c3 = c1 + c2;
cout << j << " " << c3 << endl;
:
32 A

!
4.1 . A
.

4.1
, ..:
( number Z ) && ( INT_MIN number INT_MAX )
(a == a0) && (b == b0) && (|a0 + b0| )
(|tP - 2h / g | < TR 2h / g ) && (|vP + 2 gh | < VR 2 gh )
( )
.
. C++
:
, , -
C++. . 4.1.
. 4.2
.
&&, ||, !, , , , -
==, <= xor !=. . 4-1 -



P Q !P P && Q P || Q P <= Q P == Q P != Q
(not P) (P and Q) (P or Q) (P Q) (P Q) (P xor Q)
false false true false false true true false
false true true false true true false true
true false false false true false false true
true true false true true true true false
. 4-1 C++.
bool, char 91

4.1
()
C++

= == (.. x == 5)
!=
< < (.. x < 12)
> >
<=
>=

. .
( ) ,
.. INT_MIN number INT_MAX
INT_MIN <= number && number <= INT_MAX
C++ &&, ||, ! and, or, not
. &&, ||, ! -
( C)
. , , C++ (.. Borland C++)
not_eq ( !=), and, or, not.
==, <, >, <=, >=, !=, not_eq, &&, and, ||, or, !, not
(tokens) C++ ,
,
.
(logical expressions), true false,
-
. , -
(true false) (.. ),
( ) -
.
.4.2 .
.
:
!(a > 0) && b <= 0 || c == 1

((!(a > 0)) && (b <= 0)) || (c == 1)
.

(!(a > 0) && b <= 0) xor (c == 1)
. :
!(a > 0) && b <= 0 != c == 1
!(a > 0) && (((b <= 0) != c) == 1) ( . 4-2).
, , . E, :
! (not) (. 3),
,
, <, <=, >, >= (. 5)
==, != (. 6),
92 4

4.2

C++
, and, && and

, or, || or

, ~, ! not

v, xor !=

, <=

==

:
, -
: not (!),
and (&&), or (||). "!=" (xor), "<=" () "==" () -
.

: && (and) (. 10) || (or)1


(. 11),
.
:
(x > 0) || (y > 0)
(x > 0) == (y > 0)
(x < 0) == (y < 0)
(k <= l) && (l < m + 5)
(a 2 > b) && (b < c) || (c == 0)
(a 2 > b) && ((b < c) || (c == 0))
, true false,
. ..
( int) : x = 5, y = 4, a = 1, b = c = 0, k = 2 , l = 1 m = 4,
:
(x > 0) || (y > 0): true ( x > 0 y > 0),
(x > 0) == (y > 0): true ( (x > 0) true (y > 0) true),
(x < 0) == (y < 0): true ( (x < 0) false (y > 0) false),
(k <= l) && (l < m + 5): false (: (k <= l) true (l < m + 5) false),
(a 2 > b) && (b < c) || (c == 0): true ( c == 0),
(a 2 > b) && ((b < c) || (c == 0)): false ( (a - 2 > b) false).
2 3: == ().
true
: 2 true, 3 false.
5 6:
&& ||, 5 : ((a 2 > b) && (b <
c)) || (c == 0) true || true c == 0 true,
true.
6, || &&.
false && false a 2 > b false,
false.

1 .
bool, char 93


:
x > 0 || y > 0
x > 0 == y > 0
x < 0 == y < 0
k <= l && l < m + 5
a - 2 > b && b < c || c == 0
a - 2 > b && (b < c || c == 0)
:
(cout << ) ,
. :
true ( ) 1 (), false ( )
0 ().
, :
cout << ()
:
cout << 1 true,
cout << 0 false.

:
int n1, n2;
:
n1 = 12; n2 = 13;
cout << n1 << " < " << n2 << " : " << (n1 < n2) << endl;
cout << n1 << " > " << n2 << " : " << (n1 > n2) << endl;
:
12 < 13 : 1
12 > 13 : 0


.
:
C++ (
) , .. 0 <= x < 10 (0 <= x) && (x <
10). ,
(0 <= x) < 10 true (0 <= x)
10 true (1) false (0).

4.1.1 !
, :
C++ ( C) : ()
"=" "==". :
: a == 1, b == c == 0 :
(a 2 > b) && (b < c) || (c == 0)
:
cout << ((a 2 > b) && (b < c) || (c = 0)) << endl;
94 4

: 0 (false)! ; C++ 2 c = 0
|| 0 false.

(a 2 > b) && (b < c) || (c == 44)
:
cout << ((a 2 > b) && (b < c) || (c = 44)) << endl;
: 1 (true)! ; C++ c = 44
44 || 44 0 true.
, c, , 44 0
!
Borland C++ : Possibly
incorrect assignment ( ). ,
, .

4.2
, ,
( ) true.
.
,

.
:
#include <iostream>
using namespace std;
int main()
{
const int a0 = 10, b0 = 20;

int a, b;
int S;

a = a0; b = b0;
// a == a0 && b == b0
cout << " : " << (a == a0 && b == b0) << endl;
S = a;
// (b == b0) && (S == a0)
cout << " 1: " << ((b == b0) && (S == a0)) << endl;
a = b;
// (a == b0) && (S == a0)
cout << " 2: " << ((a == b0) && (S == a0)) << endl;
b = S;
// a == b0 && b == a0
cout << " : " << (a == b0 && b == a0) << endl;
cout << " a = " << a << " b = " << b << endl;
}
:
cout << -
. : :
, : 1, 2, 3,...
.

2 !; , :
.
bool, char 95

C++,
.
:
: 1
1: 1
2: 1
: 1
a = 20 b = 10
, , :
#include <iostream>
using namespace std;
int main()
{
const int a0 = 10, b0 = 20;

int a, b;

a = a0; b = b0;
// a == a0 && b == b0
cout << " : " << (a == a0 && b == b0) << endl;
a = b; b = a;
// a == b0 && b == a0
cout << " : " << (a == b0 && b == a0) << endl;
cout << " a = " << a << " b = " << b << endl;
}
:
: 1
: 0
a = 20 b = 20
!
3.
, () -
true .

4.3 : assert()
-
.
.

:
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
const int a0 = 10, b0 = 20;

int a, b;

a = a0; b = b0;
assert( a == a0 && b == b0 );
a = b; b = a;
assert( a == b0 && b == a0 );
cout << " a = " << a << " b = " << b << endl;
}

3 . !
96 4

:
Assertion failed: a == b0 && b == a0, file test02a.cpp, line 13
assert();
, . 1, :
( bool,
)
.
.
assert #include
<cassert>.
:
, 11, - (true).
: .
, 13, - (false).
.
:
#include <iostream>
#include <cassert>
using namespace std;
int main()
{
const int a0 = 10, b0 = 20;

int a, b;
int S;

a = a0; b = b0;
assert( a == a0 && b == b0 );
S = a;
assert( (b == b0) && (S == a0) );
a = b;
assert( (a == b0) && (S == a0) );
b = S;
assert( a == b0 && b == a0 );
cout << " a = " << a << " b = " << b << endl;
}
:
a = 20 b = 10
assert!4
, assert
(2.7). eleptw.cpp
, assert( h >= 0 ) 14
, :
#include <iostream>
#include <cmath>
#include <cassert>
using namespace std;
int main()
{
const double g( 9.81 ); // m/sec2,
double h, // m,
tP, // sec,
vP; // m/sec,

4 .
.
bool, char 97

// h
cout << " m: "; cin >> h;

assert( h >= 0 );

// (g == 9.81) && (0 h DBL_MAX)


// tP, vP
tP = sqrt( 2*h/g );
vP = -sqrt(2*h*g);
// (tP (2h/g)) && (vP -(2hg))
// tP, vP
cout << " = " << h << " m" << endl;
cout << " = " << tP << " sec" << endl;
cout << " = "
<< vP << " m/sec" << endl;
}
:
m: -80
Assertion failed: h >= 0, file eleptw.cpp, line 14
, 80
.

4.4 bool
,
4.1.

: int () duble ().
, bool. bool false
true :
false < true
bool : &&,
||, !. : , , xor! ,
:
. .
(. -3) 1, 2 4 P Q
true, false < true, P <= Q. 3,
P Q false, P > Q !(P <= Q).
xor (. -4) 2 3 P xor Q
true, P != Q, 1 4 P xor Q false, P == Q
!(P != Q).
, (. -5) 1 4 P
Q true, P == Q, 2 3 P Q false, P !=
Q !(P == Q).
: -
(true false),
bool ( ),
( ) &&, ||, !, <=, == !=.
, bool
( ).
bool ,
, . ..:
bool x, y, logical, signal, ok, lgc;
int i, k;
98 4

double a;

x, y, logical, signal, ok lgc true false. ..,
,
( ),
bool.
x = true; y = !signal || x;
logical = (x || y) && signal; ok = (a <= 18) && (k != 2);
lgc = false; signal = k < -1;


. 4-1, false
true 0 1 .
#include <iostream>
using namespace std;
int main()
{
bool P, Q;

cout << "P Q !P P&&Q P||Q P<=Q P==Q P!=Q" << endl;
P = false; Q = false;
cout << P << " " << Q << " " << !P << " " << (P && Q)
<< " " << (P || Q) << " " << (P <= Q) << " "
<< (P == Q) << " " << (P != Q) << endl;
P = false; Q = true;
cout << P << " " << Q << " " << !P << " " << (P && Q)
<< " " << (P || Q) << " " << (P <= Q) << " "
<< (P == Q) << " " << (P != Q) << endl;
P = true; Q = false;
cout << P << " " << Q << " " << !P << " " << (P && Q)
<< " " << (P || Q) << " " << (P <= Q) << " "
<< (P == Q) << " " << (P != Q) << endl;
P = true; Q = true;
cout << P << " " << Q << " " << !P << " " << (P && Q)
<< " " << (P || Q) << " " << (P <= Q) << " "
<< (P == Q) << " " << (P != Q) << endl;
}
:
P Q !P P&&Q P||Q P<=Q P==Q P!=Q
0 0 1 0 0 1 1 0
0 1 1 0 1 1 0 1
1 0 0 0 1 0 0 1
1 1 0 1 1 1 1 0

true false 1 0 -
( ) 32*true 32! bool
0 1.
.
false < true ( 0 1).
!false == true !true == false ( 1-false == true
1-true == false).
C: C bool -
true, 0 false. C++ -
. :
bool b;
:
b = static_cast<bool>( 37.5 ); cout << b << " ";
bool, char 99

b = 37.5; cout << b << " ";


b = static_cast<bool>( 0 ); cout << b << " ";
b = 0; cout << b << endl;
:
1 1 0 0
, ( double) true -
0 false.
, C -
bool.
. .
:
bool (flag)
(true) (false).

4.4.1 false true


0 1 false true
cout boolalpha : :
#include <iostream>
using namespace std;
int main()
{
cout << false << " " << true << endl;
cout << boolalpha;
cout << false << " " << true << endl;
}
:
0 1
false true

4.5 char
2.3 char. -
C++ :
char,
signed char,
unsigned char.

1
#include <iostream>
using namespace std;
int main()
{
char c; unsigned char u; signed char s;

c = 195; u = 195; s = 195;


cout << c << " " << u << " " << s << endl;
cout << static_cast<int>(c) << " " << static_cast<int>(u)
<< " " << static_cast<int>(s) << endl;
}
:

-61 195 -61
100 4

:
: c = 195; u = 195; s = 195
: 195. :
c = static_cast<char>(195);
u = static_cast<unsigned char>(195);
s = static_cast<signed char>(195) .
cout << c << " " << u << " " << s << endl
: . ; . , . -4 (-3)
Windows, 195, .
modulo
(mod 256 ). 61 = 256 - 195.

, char
: char
.
2
:
const char plus = '+', space = ' ', aLower = 'a', aUpper = 'A';
char letter, digit, spcChar;
:
letter = aLower;
digit = '7';
spcChar = plus;
cout << ' ' << letter << space << digit << spcChar << endl;
:
a 7+
, :
_a_7+

char :
:
'+' ' ' 'a' 'A' '7'
,
:
char : \, ?, ', "
: '\\', '\?', '\'', '\"'. (. 4-2)
. LF '\n'
char HT '\t'
. VT '\v'
BS '\b'
; . CR '\r'
FF '\f'
3 BEL '\a'
: \ '\\'
char c1, c2, c3; ? '\?'
: ' '\''
cin >> c1 >> c2 >> c3; " '\"'
cout << c1 << c2 << c3 << endl; . 4-2
: char
-
a b c<Enter>
.
:
. D.
bool, char 101

abc

! () ;
c2; >> cin ,
.
cin.get(a);
a,
char. : !
3
:
char c1, c2, c3, c4;

cin.get(c1); cin.get(c2);
cin.get(c3); cin.get(c4);
cout << " c1: " << c1 << endl;
cout << " c2: " << c2 << endl;
cout << " c3: " << c3 << endl;
cout << static_cast<int>(c4) << endl;
:
a b<enter>
:
c1: a
c2:
c3: b
10
: c2: _. -
. 10 : cout << static_cast<int>(c4).
c4 <Enter> (LF, '\n') !


cin >> cin.get(v) .
cin >> cin.get(v).
, .
cin >> .

4.5.1 char
. ..
65 ASCII 'A' .
, ,
:
'0', '1', ..., '9' ' .
,
, .
,
, .
c unsigned char, static_cast<int>
(order) . .. :
unsigned char c;

c = 'D'; cout << static_cast<int>(c);


102 4

c = ''; cout << " " << int(c);


cout << " "
<< static_cast<int>(static_cast<unsigned char>('')) << endl;
:
68 195 254
, int unsigned char
. .. :
cout << static_cast<unsigned char>(68) << " ";
cout << static_cast<unsigned char>(195) << " ";
cout << static_cast<unsigned char>(254) << endl;
:
D
: c, unsigned char :
static_cast<unsigned char>(static_cast<int>(c)) == c
(int k, 0 k 255):
static_cast<int>(static_cast<unsigned char>(k)) == k
, unsigned char;
; . : c = 'D' -
, c, static_cast<int>
('D'), .

. ,
unsigned char
. .
wchar_t
unsigned char
.
signed char char
unsigned char,
int : 8 ( 1 )
1 (-). .. :
unsigned char uc;
char c;

c = ''; uc = '';
cout << c << " " << uc << endl;
cout << static_cast<int>(c) << " "
<< static_cast<int>(uc) << endl;
c = c - 1; uc = c;
cout << c << " " << uc << endl;
cout << static_cast<int>(c) << " "
<< static_cast<int>(uc) << endl;
:

-2 254

-3 253
:
1. , '', ,
.
2. static_cast<int>(c) static_cast<int>(uc) -2
254. ;
: 111111102. ,
bool, char 103

, 1 "1" . .
:
c (int) uc (unsigned int) ( :
)
static_cast<int>(c) 0
static_cast<int>(c) == static_cast<int>(uc)
( static_cast<int>(c) < 0)
static_cast<int>(c) == (static_cast<int>(uc) - 256)
3. c c = c - 1. , char
.
4. c uc uc =
static_cast<unsigned char>(c).
('').
Windows, char signed char
-128 127.

4.6 char
: :
int k;
, :
cin >> k;
, 375.
<3>, <7> <5>. , k 375,
.

<3> <7> <5>.
, char.
375; ,
375
k . -
.
:
'0', '1', ..., '9' . ..
ASCII 48 ('0') 57 ('9'). ,
'0'
. .. ( ASCII):
static_cast<int>('7')-static_cast<int>('0') = 55 - 48 = 7
,
C++.
, -
. :
, . -
,
10. :
#include <iostream>
using namespace std;
int main()
{
const int ord0 = static_cast<int>('0');
// o '0'
104 4

unsigned char digit1, digit2, digit3;


// ()
unsigned char ceol; // <enter>
int value1, value2, value3;
//
int integer;
//

cin.get(digit1); cin.get(digit2); cin.get(digit3);


cin.get(ceol);
value1 = static_cast<int>(digit1) - ord0;
value2 = static_cast<int>(digit2) - ord0;
value3 = static_cast<int>(digit3) - ord0;
integer = value1*100 + value2*10 + value3;
cout << " = " << integer << endl;
}
:
375
:
= 375
:
007
:
= 7
.
. :
__7
:
= -1753
; .
375
('3'), ( '7')
('5').
375 / 100.
(375 % 100 == 75) 10, (75 /
10) , (75 % 10) .
-
.
cin >> integer;
value1 = integer / 100;
digit1 = static_cast<unsigned char>(ord0 + value1);
integer = integer % 100; value2 = integer / 10;
digit2 = static_cast<unsigned char>(ord0 + value2);
integer = integer % 10; value3 = integer;
digit3 = static_cast<unsigned char>(ord0 + value3);
cout << digit1 << digit2 << digit3 << endl;
C++ char. . 4-3
, .
int C,
. bool ().
: #include
<cctype>. . :
#include <iostream>
#include <cctype>
bool, char 105

true ( 0) :
isalpha ('a'..'z', 'A'..'Z')
isupper ('A'..'Z')
islower ('a'..'z')
isdigit ('0'..'9')
isxdigit ('0'..'9', 'a'..'f', 'A'..'F')
isspace ' ', '\t', '\r', '\n', '\f'
iscntrl : static_cast<char>(0) ..
static_cast<char>(31), static_cast<char>(127)
ispunct
isalnum
isprint : static_cast<char>(32) (= ' ') ..
static_cast<char>(126) (= '~')
isgraph isalpha || isdigit || ispunct
isascii ASCII (ISO 646)
static_cast<char>(0) .. static_cast<char>(127)
. 4-3 C++ .
char. true
. false. -
: #include <ctype>.
using namespace std;
int main()
{
char c1 = 'f', c2 = '', c3 = '3';

cout << isalpha(c1) << " " << isalpha(c2) << endl;
cout << (isxdigit(c1) && !isdigit(c1)) << endl;
cout << (isxdigit(c3) && !isdigit(c3)) << endl;
}
:
8 0
1
0
'f' isalpha(c1) 8 0
true. '' isalpha(c2)
0 false. 'f' -
'f' . true (1). ,
'3' '3'
false (0).
, : 8 :
cout << static_cast<bool>(isalpha(c1)) << " "
<< static_cast<bool>(isalpha(c2)) << endl;
, .
cctype tolower
, .. tolower('Q')
'q'. toupper, cctype,
, .. toupper('q') 'Q'.
106 4

4.7 wchar_t
wchar_t C++5
. 65536
, 256 char
Unicode.
wchar_t char L, ..:
L'a' L'%' L''
. 2-1, 16 (2 ).
:
cout << sizeof('A') << " " << sizeof(L'A') << endl;
:
1 2
wchar_t cin
cout, . ..
wchar_t a, b;

a = L'a'; b = L'\n';
cout << a << " " << b << endl;
:
97 10
cwctype6
wchar_t, .
4-3. is isw. ..,
a, b,
cout << iswalnum(a) << " " << iswprint(b) << endl;
:
256 0
( L'a' L'\n' .)
:
, a
Unicode, 0x03b1 (945) a =
0x03b1 a = 945. a = L''
225 (Windows).

4.8
:
bool { 0, 1 } int.
unsigned char 0 .. 255
int.
signed char char
-128 .. 127 int.

5 C stddef.h (Borland C):


typedef unsigned short wchar_t;
6 cctype.
bool, char 107

int.
(ordinal types)7. int,
, .
int, , int, int .
(ordered).
(predecessor) (successor). ..
0 1 1, 'C' 'B' 'D'.
, INT_MAX INT_MIN.
char char(-128) char(127). bool
false true.

4.9 ( )
C++ .
(enumerated types). ,
, :
enum WeekDay { sunday, monday, tuesday, wednesday, thursday,
friday, saturday };
enum EurUn { Austria, Belgium, Bulgaria, Cyprus, CzechRepublic,
Denmark, Ellas, Estonia, Finland, France, Germany,
Hungary, Ireland, Italy, Latvia, Lithuania,
Luxembourg, Malta, Netherlands, Poland, Portugal,
Romania, Slovakia, Slovenia, Spain, Sweden,
UnitedKingdom };
:
WeekDay day1, day2;
EurUn country;
:
day1 = sunday; day2 = wednesday;
// . . .
country = Ellas;
enum.
, ,
.
, , ,
.
.
, WeekDay, day1,
: sunday, monday, tuesday, wednesday, thursday, friday, saturday.
. ..:
sunday < monday < tuesday < wednesday < thursday < friday < saturday
Austria < Belgium < Bulgaria < . . . < Sweden < UnitedKingdom
static_cast<int>
() :
static_cast<int>(sunday) == 0,
static_cast<int>(monday) == 1,
static_cast<int>(tuesday) == 2 ...
static_cast<int>(Austria) == 0,
static_cast<int>(Belgium) == 1,
static_cast<int>(Denmark) == 2 ...

7 Pascal.
108 4


:
static_cast<WeekDay>(0) == sunday,
static_cast<WeekDay>(1) == monday,
static_cast<WeekDay>(2) == tuesday ...
static_cast<EurUn>(0) == Austria,
static_cast<EurUn>(1) == Belgium,
static_cast<EurUn>(2) == Bulgaria ...
cout << v
: cout << static_cast<int>(v)...
()cin >>
v). int k
:
cin >> k;
v = static_cast<T>( k );
T v.
int
. .. :
enum DecDigit { zero = 48, one, two, three, four, five, six,
seven, eight, nine };
:
static_cast<int>( zero) == 48,
static_cast<int>(one) == 49,
. . .
static_cast<int>(nine) == 57
.
:
enum Digit { miden = 48, zero = 48, one, two, three, four,
five, six, seven, eight, nine };
enum Digit { zero = 48, one, two, three, four,
five, six, seven, eight, nine, miden = 48 };
:
static_cast<int>(miden) == static_cast<int>(zero) ==48,
static_cast<int>(one) == 49,
. . .
static_cast<int>(nine) == 57
:
enum Digit { zero = 48, one, two, three, four,
miden = 48, five, six, seven, eight, nine };
:
static_cast<int>(miden) == static_cast<int>(zero) == 48,
static_cast<int>(one) == static_cast<int>(five) == 49,
static_cast<int>(two) == static_cast<int>(six) == 50,
. . .

4.10
WeekDay EurUn :
typedef enum { sunday, monday, tuesday, wednesday, thursday,
friday, saturday } WeekDay;
typedef enum { Austria, Belgium, Bulgaria, Cyprus,
CzechRepublic, Denmark, Ellas, Estonia, Finland,
France, Germany, Hungary, Ireland, Italy,
Latvia, Lithuania, Luxembourg, Malta,
bool, char 109

Netherlands, Poland, Portugal, Romania,


Slovakia, Slovenia, Spain, Sweden,
UnitedKingdom } EurUn;
typedef (type definition) .
enum { sunday, monday, tuesday, wednesday, thursday, friday,
saturday }, typedef .
. ..
typedef unsigned int Natural;
typedef unsigned long int LongNatural;
typedef unsigned char byte;
typedef bool Logical;
, Natural, LongNatural, Logical byte, -
, , .
:
Natural n, e;
LongNatural athr, aAth;
Logical yparxei;
byte c1, c2;


4-1 1753 4.5,
: __7.


4-2 : ((A || B) && B) B.
4-3 : (A && B) A (A && B) B.


4-4 4.5,
.
110 4

5

:
-
:
.
:
,
.
.
:

if
ifelse


if ifelse
:
5.1 - if ............................................................................................................................... 112
5.2 if.................................................................................................................................................... 115
5.3 if - ..................................................................................................... 117
5.4 * ............................................................................................................ 120
5.4.1 * ..........................................................................................................................122
5.5 ...................................................................................................................... 124
5.6 ................................................................................................................... 127
5.7 ";" .................................................................................................................................. 128
5.8 ( ) ................................................................................................................................. 129
................................................................................................................................................................... 129
.............................................................................................................................................................................129
.............................................................................................................................................................................130
.............................................................................................................................................................................131

:
, . /,

, ,
. , ,

111
112 5

,
.
, -
, -
.
C++ (selectin statements).
, .

5.1 - if
... -
.
. .
, -
, "
: ". :
double x, y, maxxy;
:
cin >> x >> y;
:
cout << " : " << maxxy << endl;
maxxy . ,
, :
x > y { maxxy x
{ maxxy y
maxxy x maxxy y C++.
; :
if ( x > y ) maxxy = x;
else maxxy = y;
:
#include <iostream>
using namespace std;
int main()
{
double x, y, maxxy;

cin >> x >> y;


if (x > y) maxxy = x;
else maxxy = y;
cout << " : " << maxxy << endl;
}
113

ifelse C++ :
if ( S ) Et else Ef
S ( ) Et, Ef . :
S,
true ( ) ) Et
) Ef -
ifelse,
false ( ) ) Et, ) -
Ef ifelse.
ifelse . 5-1.
(true
false) S. if-
else ( if ) (branching).
cin >> x >> y
:
1.6 0.6
1.6 x 0.6 y. ifelse
x > y 1.6 > 0.6, true.
maxxy = x ifelse,
cout << ... :
: 1.6
maxxy = y .
cin >> ... :
1.6 2.6
x > y (1.6 > 2.6) false.
maxxy = y cout << ... :
: 2.6
cin >> ... :
2.6 2.6
x > y (2.6 > 2.6) false.
3 2.3.
ax2 + bx + c = 0. -
. :
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
cout << " 1 = " << x1 << " 2 = " << x2 << endl;
delta 0


S
true false

Et f

. 5-1 ifelse.
114 5

. ifelse,
-
;
C++ :
(compound statement) .
: ({)
(}) . :
{
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
cout << " 1 = " << x1 << " 2 = " << x2 << endl;
}
:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, b, c; //
double x1, x2; //
double delta; //

cout << " " << endl;


cin >> a >> b >> c;
cout << " a = " << a << " b = " << b
<< " c = " << c << endl;
delta = b*b - 4*a*c;
if ( delta >= 0 )
{
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
cout << " 1 = " << x1 << " 2 = " << x2 << endl;
}
else
cout << " " << endl;
cout << " " << endl;
}
(
):
1 3 -10
:
a = 1 b = 3 c = -10
1 = 2 2 = -5

:
2 3 4
:
a = 2 b = 3 c = 4


, :
0 1 2
: . ;
0 a x1 x2 2a. -
, if. .
115

5.2 if

- S
false
:
x > y { maxxy x true

x y { maxxy y

C++;
:
if (x > y) maxxy = x; else;
if (x <= y) maxxy = y; else;
:
. 5-2
x > y { maxxy x if.
{
x y { maxxy y
{
else (empty) (null) -
C++ .
, "else;":
if (x > y) maxxy = x;
if (x <= y) maxxy = y;
if :
if ( S ) Et
S ( ) Et . :
S,
true ( ) ) Et -
) if,
false ( ) Et -
ifelse.
. 5-2 if.
:
#include <iostream>
using namespace std;
int main()
{
double x, y, maxxy;

cin >> x >> y;


if (x > y) maxxy = x;
if (x <= y) maxxy = y;
cout << " : " << maxxy << endl;
}
. cin >> x >> y :
1.6 0.6
1.6 x 0.6 y. if (x >
y) maxxy = x x > y 1.6 > 0.6,
true. maxxy = x
if, if (x <= y) maxxy = y. x
<= y 1.6 <= 0.6 false maxxy = y
cout << ... :
: 1.6
maxxy = y .
cin >> :
116 5

5.1
if
"if", "(", , ")",
:
if ,
,
C++.
if:
.
true (),

false .

ifelse
"if", "(", , ")", -1, "else", -2
:
if else ,
,
-1 ( if) C++.
-2 ( else) C++.
ifelse:
.
true (),
-1 else.
-2 .
( false)
-2 else.
-1 .

1.6 2.6
x > y (1.6 > 2.6) false maxxy = x . -
if x <= y 1.6 <= 2.6 true
maxxy = y cout << :
: 2.6
-
.
#include <iostream>
using namespace std;
int main()
{
double x, y, maxxy;

cin >> x >> y;


maxxy = y;
if (x > maxxy) maxxy = x;
cout << " : " << maxxy << endl;
}
(. y).
( x > maxxy)
: maxxy = x.
, . .
117

x > y
: maxxy = x maxxy = y. 1 1
.
(x > y, x <= y),
if. ,
true false. , maxxy = x maxxy = y -
. : 2 1 .
maxxy = y .
x > maxxy. maxxy = x
x > y. 50%,
1 1.5 .

5.3 if -
ifelse ( if) , ,
C++. if,
:
if ( S1 )
if ( S2 ) -1
else -2
: else; C++
if ( if) :
if ( S1 )
{
if ( S2 ) -1
else -2
}
, if if if (S1).... else if
(S2)... . -1 S1 S2
. -2 S1
S2.
else (
) if. -
2 S1 , -
:
if ( S1 ) { if ( S2 ) -1 }
else -2
if if,
(nested) if.
if
. -
ifelse ifelse else
.
1
1:
800 kWh (0 .. 800]: 0.088 /kWh
400 kWh (800 .. 1200]: 0.112 /kWh

1 , . ... .
.
118 5

500 kWh (1200 .. 1700]: 0.136 /kWh


kWh (1700 .. +): 0.28 /kWh
kWh
2.
:
<= 800
= *0.088
( 800)
800 < <= 1200
= 800*0.088 + ( - 800)*0.112
( 1200)
1200 < <= 1700
= 800*0.088 + 400*0.112 + ( - 1200)*0.136
( 1700)
= 800*0.088 + 400*0.112 + 500*0.136 +
( - 1700)* 0.28
ifelse :
if ( consumption <= 800 )
cost = consumption*0.088
else
...
else consumption <= 800 false
consumption > 800. ifelse :
if ( 800 < consumption && consumption <= 1200 ) ...
( &&) ,
true.
.
#include <iostream>
using namespace std;
int main()
{
double consumption; // kWh
double cost;

cout << " kWh: "; cin >> consumption;


if (consumption <= 800)
cost = consumption * 0.088;
else if (consumption <= (800 + 400))
cost = 800*0.088 + (consumption - 800)*0.112;
else if (consumption <= (800 + 400 + 500))
cost = 800*0.088 + 400*0.112 + (consumption - 1200)*0.136;
else
cost = 800*0.088 + 400*0.112 + 500*0.136
+ (consumption - 1700)*0.28;
cout << cost << endl;
}

:
if (S1) E1
else if (S2) E2
else if (S3) E3
:
else if (Sn) En
else En+1

2 , , , , . !
119

S1 true
E1 E2, E3,... En,
(S1 false) S2 true
E2 E1, E3,... En,
(S1 S2 false) S3 true
E3 E1, E2,... En,
...
(S1, S2,... Sn1 false) Sn true
En E1, E2,... En-1,
(S1, S2,... Sn false)
En+1 E1, E2,... En.
! if .
k- if
(! S1) && . . . && (! Sk1) && Sk
:
(! (S1 || . . . || Sk1)) && Sk
, , false!
() , :
if ( consumption <= (800 + 400 + 500) )
cost = 800*0.088 + 400*0.112 + (consumption - 1200)*0.136;
else if ( consumption <= (800 + 400) )
cost = 800*0.088 + (consumption - 800)*0.112;
else if ( consumption <= 800 )
cost = consumption * 0.088;
else
:

cost = 800*0.088 + (consumption - 800)*0.112;
: !(consumption <= 1700) && consumption <= 1200.
false, consumption. , false
!(consumption <= 1700) && !(consumption <= 1200) && consumption
<= 100 : cost = consumption*0.088.
if. ..
:
if ( consumption <= 800 )
cost = consumption * 0.088;
if ( 800 < consumption && consumption <= 1200 )
cost = 800*0.088 + (consumption - 800)*0.112;
if ( 1200 < consumption && consumption <= 1700 )
cost = 800*0.088 + 400*0.112 + (consumption - 1200)*0.136;
if ( consumption < 1700 )
cost = 800*0.088 + 400*0.112 + 500*0.136
+ (consumption - 1700)*0.28;
, . ; -
.3 .. 50
if, if
false .

3 ; .
120 5

2

(pocket calculator).
(+, -, *, /)
.
unsigned char
oper. x1, x2,
double.
oper:
oper == '+'

, oper '-', '*', '/'
oper == '-'

, oper '*', '/'
oper == '*'

, oper '/'

C++ ifelse
else ifelse. : -
.
+, -, * /. @, . -
. , -
0 ().
:
#include <iostream>
using namespace std;
int main()
{
double x1, x2; //
unsigned char oper; //

cin >> oper >> x1 >> x2;


if (oper == '+') cout << (x1 + x2) << endl;
else if (oper == '-') cout << (x1 - x2) << endl;
else if (oper == '*') cout << (x1 * x2) << endl;
else if (oper == '/')
if (x2 != 0) cout << (x1 / x2) << endl;
else
cout << " " << endl;
else
cout << " (+,-,*,/) " << endl;
}

5.4 *

ifelse if.
:
// P
if (S) Et else Ef
S t P && S
Qt. S !S f
121

P && (!S) Qf. , -


ifelse : Qt || Qf. :
ifelse ||.
, ,
, ,
:
// P
if (S) Et else Ef (1)
// Q
: P if (S) Et else Ef
Q. ;
S t P && S.
Q. S !S
f P && (!S).
Q. :
(1) -
:
P && S { Et } Q
P && (!S) { Ef } Q
ifelse, :
P & & S { Et} Q , P & & (!S) { Ef } Q
P { if (S) Et else Ef } Q
if. :
// P
if (S) Et
: S t P && S -
Qt. S !S
t P && (!S). , -
if : Qt || (P && (!S)).
if. :
// P
if (S) Et (2)
// Q
S t P && S.
Q. S ( !S)
Q .
P && (!S) Q. :
(2) -
:
P && S { Et } Q
(P && (!S)) Q
if. :
P & & S { Et} Q, ( P & & (!S)) Q
P { if (S) Et } Q


ifelse
5.2 . ,
.
122 5

maxxy ( )
x y: (maxxy x) && (maxxy y). maxxy x
y: (maxxy == x) || (maxxy == y). :
((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
; . -
x, y cin >> x >> y.
, 3.7, :
true
:
// true
if (x > y) maxxy = x;
else maxxy = y;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
ifelse, :
// true && (x > y)
maxxy = x;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))

// true && (!(x > y))


maxxy = y;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
.
1: ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
maxxy = x : ((x x) && (x y)) && ((x == x) || (x == y)),
maxxy x.
x x x == x true x,
(true && A) A,
(true || A) true,
: x y. x > y.
2: ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
maxxy = y : ((y x) && (y y)) && ((y == x) || (y ==
y)). , y y y == y true
y, ,
: y x. !(x > y) :
x y.

5.4.1 *
,

.
if.
: P
:
// P
if (S) Et else Ef
// Q
Pt Pf :
// Pt // Pf
Et Ef
// Q // Q
123

Pt Pf P ( . 5-3):
(Pt && S) || (Pf && (!S))
1
:
// (-1 x < 0) || (1 x < 6)
if (x < 0) y = x;
else y = x - 2;
// -1 y 4
:
1. , , P :
// P
if (x < 0) y = x;
else y = x - 2;
// -1 y 4
2. P (.. (2), 0.4), .:
((-1 x 0) || (1 x 6)) P
:
1. :
Et : y = x;
Ef : y = x - 2;
Q : 1 y 4
Pt Pf :
// Pt // Pf
y = x; y = x - 2;
// -1 y 4 // -1 y 4
-1 y 4 y = x -1 x 4.
Pt.
, 1 y 4 y = x - 2 , ,
1 x2 4 1 x 6. Pf.
, ifelse : (Pt && S) || (Pf && (!S)) ,
S x < 0 !S !(x < 0) (x 0):
((1 x 4) && (x < 0)) || ((1 x 6) && (x 0))
: (1 x < 0) || (1 x 6)

2. (1 x < 0) || (1 x 6)
(1 x < 0) || (1 x < 6).
1 x < 0 1 x < 6 ( , ).
P . (1 x < 6), 1 x 6,
P.
.

if : P
:
// P
if (S) Et
// Q
, , Pt :
// Pt
Et
// Q
Pt, P ( . 5-3):
124 5

(S && Pt) || ((! S) && Q)


2
, ,
, :
// true
maxxy = y;
if (x > maxxy) maxxy = x;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
if, .
(S && Pt) || ((! S) && Q). :
S x > maxxy !S !(x > maxxy) x maxxy,
Q ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
Pt :
// Pt
maxxy = x;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
. 5.5 Pt : x y.
((x > maxxy) && (x y)) ||
((x maxxy) && ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y)))
, :
((x > maxxy) && (x y)) ||
(((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y)))
:
maxxy = y;
// ((x>maxxy) && (xy)) ||
// ((maxxyx) && (maxxyy) && ((maxxy==x)||(maxxy==y)))
if (x > maxxy) maxxy = x;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
y maxxy
maxxy = y:
((x > y) && (x y)) || (((y x) && (y y)) && ((y == x) || (y == y)))
:
(x > y) && (x y) (x > y),
y y y == y true
:
(x > y) || (y x)
true .

5.5
assert
.
1

h 0. :
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
125

const double g( 9.81 ); // m/sec2,


double h, // m,
tP, // sec,
vP; // m/sec,

// h
cout << " m: "; cin >> h;
if ( h >= 0 )
{ // (g == 9.81) && (0 h DBL_MAX)
// tP, vP
tP = sqrt( (2/g)*h );
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))
// tP, vP
cout << " = " << h << " m" << endl;
cout << " = " << tP << " sec" << endl;
cout << " = "
<< vP << " m/sec" << endl;
}
else
// false
cout << " " << endl;
}
false , else, ; tP
vP h < 0.
4.4 : assert
if. ...

2
, , ,
a.
: a 0
0. :
: (a 0) && (b2 4ac 0)
b b 2 4ac b b 2 4ac
: (x1 = ) && (x2 = )
2a 2a
,
5.2, .
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, b, c; //
double x1, x2; //
double delta; //

cout << " " << endl;


cin >> a >> b >> c;
cout << " a = " << a << " b = " << b
<< " c = " << c << endl;
delta = b*b - 4*a*c;
if ( a != 0 && delta >= 0 )
{
x1 = (-b + sqrt(delta))/(2*a);
x2 = (-b - sqrt(delta))/(2*a);
cout << " 1 = " << x1 << " 2 = " << x2 << endl;
}
else //
{
if ( a == 0 )
126 5

cout << " 1 " << endl;


else
cout << " " << endl;
}
cout << " " << endl;
}
, , x1 x2 a 0
delta 0.

1. , a != 0, , a -
double. a ,
, () , , -
.
2. , -
a == 0. . 5-7.
3. x1 x2 -
.
,
.
:
if ( b >= 0 )
x1 = (-b - sqrt(delta))/(2*a);
else // b < 0
x1 = (-b + sqrt(delta))/(2*a);
x2 = c/(a*x1);
, , a, b, c 1, -1, -30 ,
x1 = (-b + sqrt(delta))/(2*a);
-(-1)+((-1)2 - 41(-30)) = 1 + 121 = 1 + 11 = 12 (x1 == 6).
(x2 == -5) : x1*x2 == c/a.
a, b, c 1, 11, 30,
x1 = (-b - sqrt(delta))/(2*a);
-11 - (112 - 4130) = -11 - 1 = -11 - 1 = -(11+1) = -12 (x1 == -6).
: x2 == (30/1)/(-6) == -5.
,
.

3
. 2 5.4 ( ). ,
+, -, *, /. ,
/ 0 (). :
:
(oper == '+') || (oper == '-') || (oper == '*') ||
((oper == '/') && (x2 != 0))
:
((oper == '+') && (res == x1 + x2)) || ((oper == '-') && (res == x1 - x2)) ||
((oper == '*') && (res == x1 * x2)) || ((oper == '/') && (x2 != 0) && (res == x1 / x2))
:
#include <iostream>
using namespace std;
int main()
{
double x1, x2; //
unsigned char oper; //
127

double res; //

cin >> oper >> x1 >> x2;


if (oper == '+' || oper == '-' ||
oper == '*' || (oper == '/' && x2 != 0))
{
if (oper == '+') res = x1 + x2;
else if (oper == '-') res = x1 - x2;
else if (oper == '*') res = x1 * x2;
else /* if (oper == '/') */ res = x1 / x2;
cout << res << endl;
}
else
cout << " " << endl;
}
, , x2 != 0
.

5.6
, 4.1, , -
. C++

&& false
false .
|| true
true .
;

E -
x y 2 , , x 0.
:
if ( x >= 0 )
if ( sqrt(x) > y + 2 ) E

x .
&& :
if ( x >= 0 && sqrt(x) > y + 2 ) E
x x >= 0 false -
sqrt(x), E
.

C++ bool -
(short-circuit boolean evaluation)4
. -
, if, .5

4 C++ Java C# -
.
5 , .
128 5

5.7 ";"
, ,
.
(4.1.1):
== =.
( )
, .
';'.
. :
if ( x > y );
maxxy = x;
else;
maxxy = y;
Borland C++ .
:
if (x > y) : code has no effect ( -
). , -
if ( ifelse) : x > y !
, if .
else misplaced else (else ).
if ifelse, else .
: -
, :
if ( x > y )
maxxy = x;
else;
maxxy = y;
. : x 4, y
5, 5, . : 5 x, 4
y, 4. ; , !
: x > y 4 > 5 false,
else ... ; !
else ';' .
ifelse, maxxy = y , .
, x > y true if, maxxy = x.
maxxy (5)
ifelse, maxxy = y, maxxy 4.
, , -
: maxxy = x ( if): 'maxxy' is assigned a value that is
never used ( maxxy ).
';'
if:
maxxy = y;
if (x > maxxy);
maxxy = x;
, if maxxy = x .
:
';'

else.
129

if
. :
const bool debug( true );
, cout << ... , -
, 3.2, :
if ( debug ) cout << ...
, :
const bool debug( false );
, .
, 6, -
debug true.7
-
(debugging8 utilities, debuggers),
.

5.8 ( )

.

,
. if /
ifelse .

.
, ,
if / ifelse.

.


5-1 a = 0, b = 1, x = 2, y = 3,
;
) if (x > y) x = y; else y = x;
) if (x == y) a = b; else b = a;
) if (x > 0) a = b;
) if (x = y) y = x;
) if (a = sqrt(b)) y = x;
) if (x > x) if (y < y) a = b;

6 There is always one more bug! ( Murphy).


7 , ()
.
8 .
130 5

) if (a + b) y = x;

5-2 , y -
, a b:
y = a + 100, a 0 b = 0
y = b + 5, a 0 b 0
y = b 5, a < 0 b = 0
y = a 100, a < 0 b 0
C++.
5-3 ) P { if (S) Et else Ef } Q t P
&& S Q, Ef P && (!S) Q.
, , Pt Pf
: Pt { Et } Q Pf { Ef } Q ifelse (Pt && S)
|| (Pf && (!S)).
:
(((Pt && S) || (Pf && (!S))) && S) Pt
(((Pt && S) || (Pf && (!S))) && (!S)) Pf
!
) P { if (S) Et } Q t P && S
Q, (P && (!S)) Q.
, , Pt
: Pt { Et } Q if (Pt && S) || (Q && (!S)).
:
(((Pt && S) || (Q && (!S))) && S) Pt
(((Pt && S) || (Q && (!S))) && (!S)) Q
!


5-4 (
a, b, c d int):
if ( a > b ) y = a; else y = b;
if ( c > y ) y = c;
if ( d > y ) y = d;
5-5 30
, (3) . 3 -
50 .

.
5-6 ( . 2-14 2-15) R1
R2 ( ) R.
, , -
, . :
'P' ,
'S' .
.
5-7 5.6, :
1. a = 0 x1 = c/b, b 0.
2. a = b = 0 c = 0 c 0.
131

3. delta < 0
ReX1 = ReX2 = b/(2a)
ImX1 = ImX2 = delta / (2a)
:
"(", , ",", , ")"
.


5-8 (int a, b, c, y):
// true
if ( a > b ) y = a; else y = b;
if ( c > y ) y = c;
// (y == a || y == b || y == c) && (y a && y b && y c)
5-9 , -
, a 0 .
b + b 2 4ac b b 2 4ac .

;
5-10 ( . 2-7).
r
. , : atan (/2, /2) : <
.
y, .: x = 0, :
/2 y > 0,
-/2 y < 0,
y = 0.
atan2(y, x).
5-11 :
// (ia na || (ia = na+1) && ib nb)
if ( ib > nb || ia na ) ia = ia + 1;
else ib = ib + 1;
// ia na + 1
5-12 :
// true
if ( x > y ) maxxy = x;
if ( x <= y ) maxxy = y;
// ((maxxy x) && (maxxy y)) && ((maxxy == x) || (maxxy == y))
5-13
:
((x y) && (maxxy == x)) || ((y x) && (maxxy == y))
:
// true
if (x > y) maxxy = x;
else maxxy = y;
// ((x y) && (maxxy == x)) || ((y x) && (maxxy == y))
5-14
.

:
132 5

"" ,
"" ,
" " .
.
:
.
. ,
, .

6

:
-
: () .
:
.
: -
.
:
-
while
for

-

:
6.1 ................................................................................................................................................ 134
6.1.1 - - ....................................................................................................137
6.1.2 .....................................................................................................................................139
6.2 * ................................................................................................................. 141
6.2.1 * .....................................................................................................................................................143
6.3 ......................................................................................................................... 150
6.4 for ................................................................................................................................................. 151
6.5 ........................................................................................................................... 154
6.6 ( ) ................................................................................................................................. 154
................................................................................................................................................................... 155
.............................................................................................................................................................................155
.............................................................................................................................................................................155
.............................................................................................................................................................................156
:



.
, . C++,
, .

133
134 6

6.1
.
-
n (..10) t1, t2,... tn -
.
, n x1, x2, ... x10
:
cin >> x1; cin >> x2; ... cin >> x10;
sum = x1 + x2 + ... + x10;
, , n 10,
100 1000 10000.
.
:
sum = 0; // sum == 0
cin >> x; sum = sum + x; // (x == t1) && (sum == (j:1..1)tj)
cin >> x; sum = sum + x; // (x == t2) && (sum == (j:1..2)tj)
. . .
cin >> x; sum = sum + x; // (x == tN) && (sum == (j:1..n)tj)
() m-
cin >> x; sum = sum + x;
m- (tm), x
sum.
x . , -

.
sum ; 0.
. sum
, m- sum -
m . n- sum -
n .
.
m
(j: 1..m)tj : t j .
j 1

! .
; -
: cin >> x; sum = sum + x; n .
n :
sum = 0; m = 1;
(m <= n) :
{
cin >> x; sum = sum + x;
// (x == tm) && (sum == (j:1..m)tj)
m = m + 1;
}
: m n
. m (counter)
(unsigned) int.
m 1 , 1,
m <= n n . , , m
1 1, m
n.
135

C++:
sum = 0; m = 1;
while ( m <= n ) { cin >> x; sum = sum + x;
// (x == tm) && (sum == (j:1..m)tj)
m = m + 1;
}
while ( : , , ) -
C++. while
(repetitive statement)

. 6.1 . - S
while false
. 6-1. , - true

(loops).
m
(x = tm) && (sum = t j )
j 1

, ,
-
(invari-
ant) . -
. 6-1 while.
.
: while, if, -
, ,
({) (}) .
while:
while ( a > b ) a = a - b;
while ( n > 0 )
{
a = a + n*n;
n = n - 1;
}
. -
1 while:
// : 1
#include <iostream>
using namespace std;
int main()
{
const int n( 10 );

int m; //
double x; //
double sum; // () .
// .
double avrg; // x (<x>)

sum = 0; m = 1;
while ( m <= n )
{
cout << " : "; cin >> x; // x = tm
sum = sum + x; // (x == tm) && (sum = (j:1..m)tj)
m = m + 1; //
} // while
avrg = sum / n;
cout << " = " << sum << " <x> = " << avrg << endl;
}
136 6

6.1
while
"while", "(", , ")",
:
while -,
,
C++
.
while:
,
while.
true (),
.
,
while.
true (),
...
false

while.
false , -
!
sum = 0; m = 1, while,
, .
,
while.
n, while,
( n=10),
n . ,
, .
(
n), .
( n = 100) -
. 2
n -
:
int n; //
. . .
cout << " : ";
cin >> n; //
. . .
: n > 0
n:
cout << " : ";
cin >> n; //
if ( n > 0 )
{
sum = 0; m = 1;
. . .
}
137

6.2 6.2

sum = 0; prod = 1;
while ( S ) while ( S )
{ {
. . . . . .
() ()
x x
sum = sum + x; prod = prod * x;
. . . . . .
} // while } // while
// sum == x // prod == x

else
cout << " " << endl;
, , 2 (. 6-1).
,
-
.
. 6.2. (. 6.2).

(counted) .
.

6.1.1 - -
-
. , , .
.
;
, -
.
, -.

. :
.

.
;
: cin >> x .
x . ,
x: double. :
;
; ;
,
. : -
0. :
0 : cin >> x.
0
.
138 6

0 - (sentinel value) -
. while
:
while ( x != sentinel )

: while
x.
while:
cin >> x;
while ( x != sentinel )
: while :
{
cin >> x;
x
}
;
. :
cin >> x;
while ( x != sentinel )
{
x;
cin >> x; //
}
: , ,
. 0 1.
, 3, ,
.
// : 3
#include <iostream>
using namespace std;
int main()
{
const double sentinel = 0;

int n; // .
//
double x; //
double sum; // () .
// .
double avrg; // x (<x>)

sum = 0; n = 0;
cout << " - 0 : "; cin >> x;
while ( x != sentinel )
{
n = n + 1; // x == tn
sum = sum + x; // (x == tn) && (sum = (j:1..n)tj)
cout << " - 0 : "; cin >> x;
} // while
cout << " " << n << " " << endl;
if ( n > 0 )
{
avrg = sum / n;
cout << " = " << sum << " <x> = " << avrg << endl;
}
}
:
1. :
cout << " - 0 : "; cin >> x;
139

6.3
-
v
while ( v )
{
v;
v
} // while

. , ! .
2. sentinel -
. -
.
3. , -, . ..

:
cout << " - <= 0 : "; cin >> x;
while ( x > 0 )
{
n = n + 1; // x == tn
sum = sum + x; // (x == tn) && (sum = (j:1..n)tj)
cout << " - <= 0 : "; cin >> x;
} // while
4. -
. . , ,
.
5. , , :
char resp;
:
cout << " ; (/): "); cin >> resp;
:
while ( resp == '' ) { . . .
1.
(
'N', , , , .)
- ( )
. . 6.3.

6.1.2

, .. ,
, . , -
,
, . ..
1000 Hz 1500 Hz;
;
, x,
;

1 '' resp; ;...


140 6

, -
;
:
x;
if ( x )
x
: 3
:
,


() 10.
.
: (selN) ,
(selSum)
(selAvrg) . :
if ( 0 < x && x <= 10 ) // ' -
{
selSum = selSum + x; //
selN = selN + 1; //
} // if
4:
// : 4
#include <iostream>
using namespace std;
int main()
{
const double sentinel( 0 );

int n; //
int selN; //
double x; //
double sum; //
double selSum; //
double avrg; //
double selAvrg; //

sum = 0; n = 0;
selSum = 0; selN = 0;
cout << " - 0 : "; cin >> x;
while ( x != sentinel )
{
n = n + 1; //
sum = sum + x; //
if ( 0 < x && x <= 10 ) // ' -
{
selSum = selSum + x; //
selN = selN + 1; //
} // if
cout << " - 0 : "; cin >> x;
} // while
cout << " " << n << " " << endl;
if ( n > 0 )
{
avrg = sum / n;
cout << " = " << sum << " <x> = " << avrg << endl;
}
cout << " " << selN << " (0,10]" << endl;
if ( selN > 0 )
{
141

selAvrg = selSum/selN;
cout << " = " << selSum
<< " <x> = " << selAvrg << endl;
}
}
if while.

6.2 *
6.1:
sum = 0; m = 1;
while ( m <= n )
{
cout << " : "; cin >> x; // x = tm
sum = sum + x; // (x == tm) && (sum = (j:1..m)tj)
m = m + 1; //
} // while
; : n (> 0) t1 ... tn, ,
n
while, sum == tj ;
j 1

m 1 1
. m <= n
while m == n + 1. I: sum ==
m 1
t j .
j 1

2.
: , while, ,
m 1
: (sum == 0) && (m == 1). sum == t j ; sum
j 1

m - 1 { t1 ... t } -
. , sum
11 0
0. t j == t j . ,
j 1 j 1

while, I.
: I m
m (: m+1).
m , .
m 1
: I: (sum == t j ) -
j 1

,
:
// sum == (j:1..m-1)tj
cin >> x;
sum = sum + x;
m = m + 1;
// sum == (j:1..m-1)tj

2 . .. , 1994.
142 6

m 1
: sum == tj m = m + 1
j 1
( m 1)1 m
sum == tj : sum == t j . :
j 1 j 1

cin >> x;
sum = sum + x;
// sum == (j:1..m)tj
m = m + 1;
// sum == (j:1..m-1)tj
m
sum == tj sum = sum + x
j 1
m
: sum + x == tj :
j 1

cin >> x;
// sum + x == (j:1..m)tj == (j:1..m-1)tj + tM }
sum = sum + x;
// sum == (j:1..m)tj)
m = m + 1;
// sum == (j:1..m-1)tj
, , cin >> x m- tm,
m
: x == tm. t j ==
j 1
m 1 m 1
tj + t m cin >> x sum == tj .
j 1 j 1

, .
;
I ( ), m == 1.
( ) I 3
, m, I , I
m == 2.
I m == 2, , m == 3
... , I m .
I -
(repetition invariant).

1. while .
; : -
, ,
. while -
! -
. ...
2. :
while ( S ) E;
// Q
; Q (!S) && QI,
QI while. , QI

3 sum = 0; m = 1;, o o while, -


I while.
143

while. -
, .. .
3. : while ( S ) E, I,
S. , :
// I && S
E
// I
,
while:
I & & S {E} I
I {while(S) E} (!S) & & I
,
while; ; !
,
,
. ; : -
n - m .
while m n n - m 0,
.
, m 1
.
4 -
. -
while , .
-
.
.

6.2.1 *
1
C++ %. -
d1, d2 () , -
()
d1:d2.
: y, ,
0 y < d2. p ;
: d1 == pd2 + y:
: (d1 0) && (d2 > 0)
: (0 y < d2) && (d1 == pd2 + y)
(
): d2
d1 ( d2 d1) d1 d2 . -

. :
// (d1 0) && (d2 > 0)
y = d1;
p = 0;

4 .
144 6

while ( d2 <= y )
{
y = y - d2;
p = p + 1;
} // while
// (0 y < d2) && (d1 == p*d2 + y)
, ,
.
, while !S && I.

!S !(d2 <= y), : d2 > y.


I .
; : -
while : (0 y < d2) && (d1 == pd2 + y) : (0 y) && (y < d2) && (d1 == pd2 + y).
y < d2, !S,
. (0 y) && (d1 == pd2 + y)
while.
1. : while.
:
// (d1 0) && (d2 > 0)
y = d1;
p = 0;
// (0 y) && (d1 == p*d2 + y)
(0 y) && (d1 == pd2 + y) p = 0
(0 y) && (d1 == 0d2 + y) :
(0 y) && (d1 == y)
y = d1;
// (0 y) && (d1 == y) }
p = 0;
// (0 y) && (d1 == p*d2 + y)
(0 y) && (d1 == y) y = d1
: (0 d1) && (d1 == d1) : d1 0 .
2. : :
// (d2 y) && (0 y) && (d1 == p*d2 + y)
y = y - d2;
p = p + 1;
// (0 y) && (d1 == p*d2 + y)
p = p + 1 (0 y) && (d1 == pd2 + y)
: (0 y) && (d1 == (p+1)d2 + y):
y = y - d2;
// (0 y) && (d1 == (p+1)*d2 + y)
p = p + 1;
// (0 y) && (d1 == p*d2 + y)
(0 y) && (d1 == (p+1)d2 + y) y = y - d2
: (0 y - d2) && (d1 == (p+1)d2 + y - d2) : (d2 y) && (d1 == pd2 + y).
(d2 y) && (0 y) && (d1 == pd2 + y).
.
, .
y. :
,
, y = y - d2 d2 y

d2 > 0.
145

.
while .
. :
#include <iostream>
using namespace std;
int main()
{
int d1, d2, p, y;

cin >> d1 >> d2;


if ( d1 >= 0 && d2 > 0 )
{ // (d1 0) && (d2 > 0)
y = d1;
p = 0;
while ( d2 <= y ) // I: (0 y) && (d1 == p*d2 + y)
{
y = y - d2;
p = p + 1;
} // while
// (0 y < d2) && (d1 == p*d2 + y)
cout << " : " << p << " : " << y << endl;
cout << " C++ : " << endl;
cout << " : " << (d1 / d2)
<< " : " << (d1 % d2) << endl;
}
else
// false
cout << " ! " << endl;
}


0 ();
.
while ! ( 0)
while 5! , ,
if, , d2 = 0.
2
C++ -
. . ; 6
: x0 > 0 x02 > a :
a
{ n: N+, xn: R x n 21 x n1 }
x n1
a .7
; : ;
> 0:
x a
(1)
a

5 , 0
.
6 x2
= 0 Newton - Raphson.
7 http://en.wikipedia.org/wiki/ Methods_of_computing_square_roots
( 1962), .
146 6

while
:
x = ;
while ( S )
x = 0.5*(x + a/x);
x; : (x > 0) && (x2 > a).
:
if (a <= 1) x = a + 1; else x = a;
:
// a > 0
if (a <= 1) x = a + 1; else x = a;
// (x > 0) && (x > a) }
, :
// (a > 0) && (a <= 1) // (a > 0) && (a > 1)
x = a + 1; x = a;
// (x > 0) && (x > a) // (x > 0) && (x > a)
.
S ; (1), :
x a

a
:
x a x a x a x2 a x2 a

a a x a a x a 2a

( : x a ).
;
:
x2
1 2
a
.
x2/a 1 < double (DBL_EPSILON). -
, = DBL_EPSILON. -
:
if ( a <= 1 ) x = a + 1; else x = a;
while ( fabs(x*x a ) >= DBL_EPSILON*a)
x = 0.5*(x + a/x);
; !
while.
while;
x a > 0
N n > N xn a < . = a ,
n : xn a < a , -
: x2 a < 2a. !(x2 a 2a),
while.
, : A a > 0.
a < 0 while ( )
! ( )
while. C++ -
(sqrt) ,
147

sqrt, ,
.

. ; -
!
:
#include <iostream>
#include <cfloat>
#include <cmath>
using namespace std;
int main()
{
double a, x;

cin >> a;
if ( a > 0 )
{// a > 0
if ( a <= 1 ) x = a + 1; else x = a;
while ( fabs(x*x a) >= DBL_EPSILON*a )
x = 0.5*(x + a/x);
// |x - a| < a
cout.precision(16);
cout << x << " " << sqrt(a) << endl;
}
else
cout << " " << endl;
}

3
: n (> 0) tk,
k = 1, 2,...n int
(kmax) .
n.
, tmax,
, kmax, . :
: n > 0
: 1 kmax n && tmax == tkmax && j: 1..n tj tmax
.
, :
cin >> t; // t == t1 }
k = 1; tmax = t; kmax = k;
. , -
, . ,
:
cin >> t; // t == t2
k = k + 1; // == 2
if ( t > tmax ) { tmax = t; kmax = k; }
. -
, . ,
:
cin >> t; // t == t3
k = k + 1; // == 3
if ( t > tmax ) { tmax = t; kmax = k; }
, 2 3
. 1 .
148 6

, ,
while:
cin >> t; // t == t1
k = 1; tmax = t; kmax = k;
k = k + 1; // == 2
while ( k <= n )
{
cin >> t; // t == tk
if (t > tmax) { tmax = t; kmax = k; }
k = k + 1;
} // while
while !(k <= n), k > n.
k 1 n > 0
: k == n + 1.
: n k-1
:
1 kmax k-1 && tmax == tkmax && j: 1.. k-1 tj tmax
I, while
.
(6-16).
:
#include <iostream>
using namespace std;
int main()
{
int t, tmax;
int n, k, kmax;

cin >> n;
if ( n > 0 )
{// n > 0
cin >> t; // t == t1
k = 1;
tmax = t; kmax = k;
k = k + 1; // == 2
while ( k <= n )
{
cin >> t; // t == tk
if ( t > tmax ) { tmax = t; kmax = k; }
k = k + 1;
} // while
// 1 kmax n && tmax == tkmax && j:1..n tj tmax
cout << " : " << tmax
<< " (" << kmax << ") " << endl;
}
else
cout << " " << endl;
}

149

. 6.4 .
if:
if ( t < tmin ) ...
, ,
. while (k
1 n). :
if (t > tmax) tmax;
tmax :
t
,
.
, tmax , .. -!
! , ;
, ,
. ..
, 0 -1 (
),
150 250,
0 10 .
,
, :
tmax = -1;
k = 1;
while ( k <= n )
{
cin >> t; // t = tk
if ( t > tmax ) { tmax = t; kmax = k; }
k = k + 1;
} // while
, (+).

6.4

t1 t
k = 1; tmax = t; kmax = k;
k = k + 1; // == 2
while ( )
{
k- tk t
if ( t > tmax ) { tmax = t; kmax = k; }
k = k + 1;
} // while


t1 t
k = 1; tmin = t; kmin = k;
k = k + 1; // == 2
while ()
{
k- tk t
if ( t < tmin ) { tmin = t; kmin = k; }
k = k + 1;
} // while
150 6

6.3
. 6.1
:
m = 1;
while ( m <= n ) {
m = m + 1; }
,
m, :
0 n < 1. m .
n n 1. m n + 1.
k- m == k.
m (control variable) .
:
m = n;
while ( m >= 1 ) {
m = m - 1; }

m = n;
while (m > 0) {
m = m - 1; }
m
.
: () (-)
m, Ma, Mt, b ( ) b > 0,

m = Ma;
while ( m <= Mt )
{
E;
m = m + b;
}
() (-) (-) n :
n = 0 Ma > Mt,
n = Trunc[(MtMa+b)/b] Ma Mt.
k- (- ) () , m Ma + (k1)b.
b (step).


, 15 sec, ,
0.5 sec, 10
m/sec2.
#include <iostream>
using namespace std;
int main()
{
double a; //
double x; //
double t; //
double step;

cout.setf(ios::fixed,ios::floatfield);
cout << " t x" << endl;
cout << " sec m" << endl;
a = 10.0; // m/sec
151

step = 0.5; // sec


t = 0.0;
while ( t <= 15.0 )
{
x = 0.5*a*t*t;
cout.width(6); cout.precision(1); cout << t << " ";
cout.width(7); cout.precision(2); cout << x << endl;
t = t + step;
} // while
}
:
t x
sec m
0.0 0.00
0.5 1.25
1.0 5.00
. . . . . .
14.5 1051.25
15.0 1125.00

6.4 for
C++ , for,
. .. :
m = Ma;
while ( m <= Mt )
{
E;
m = m + b; // b > 0
}
:
for ( m = Ma; m <= Mt; m = m + b )
{
E;
}

m = Ma;
while ( m >= Mt )
{
E;
m = m - b; // b > 0
}
:
for ( m = Ma; m >= Mt; m = m b )
{
E;
}
m .
.
Ma, Mt, b . ' ,
for ()
m, Ma, Mt, b.
Ma, Mt, b for
for.
m = m b.
152 6

; ,
for .
.
while ( for) .
while for,
, if while,
({) (}) .
1 ( 2) for:
sum = 0;
for ( m = 1; m <= n; m = m+1 )
{
cout << " : "; cin >> x; // x = tN
sum = sum + x; // (x == tm) && (sum = (j:1..m)tj)
} // for
avrg = sum / n;
:
1
for bool.
4.3 :
#include <iostream>
using namespace std;
int main()
{
bool P, Q;
int iP, iQ;

cout << "P Q !P P&&Q P||Q P<=Q P==Q P!=Q " << endl;
for ( iP = 0; iP <= 1; iP = iP+1 )
{
P = static_cast<bool>(iP);
for (iQ = 0; iQ <= 1; iQ = iQ+1)
{
Q = static_cast<bool>(iQ);
cout << P << " " << Q << " " << !P << " "
<< (P && Q) << " " << (P || Q) << " "
<< (P <= Q) << " " << (P == Q) << " "
<< (P != Q) << endl;
} // for (iQ...
} // for (iP
}

2
int.
: n
:
11 + 22 + ... + nn
() (1.. n) ()
. (. 6.2) :
cin >> n;
sum = 0;
for ( m = 1; m <= n; m = m + 1 )
{
m- mm;
sum = sum + mm;
}
153

,
sum
.
mm pow.
:
m m m ... m

m

. 6.2. mm
:
product = 1; k = 1; product = 1;
while ( k <= m ) for ( k=1; k <= m; k=k+1 )
{
product = product*m; product = product*m;
k = k + 1;
} // while (k ...
:
#include <iostream>
using namespace std;
int main()
{
int n, sum;
int m, k, product;

cin >> n;
sum = 0;
for ( m = 1; m <= n; m = m + 1 )
{
product = 1;
for ( k = 1; k <= m; k = k + 1 )
{
product = product*m;
} // for (k...
sum = sum + product;
} // for (m...
cout << " n = " << n << " o = "
<< sum << endl;
} // main

3
6.4: double.
for :
#include <iostream>
using namespace std;
int main()
{
double a; //
double x; //
double t; //
double step;

cout.setf( ios::fixed,ios::floatfield ); cout.precision( 8 );


cout << " t x" << endl;
cout << " sec m" << endl;
a = 10.0; // m/sec
step = 0.5; // sec
for ( t = 0.0; t <= 15.0; t += step )
{
154 6

x = 0.5*a*t*t;
cout.width( 6 ); cout.precision( 1 ); cout << t << " ";
cout.width( 7 ); cout.precision( 2 ); cout << x << endl;
} // for
}
, ,
31 :
int k;
. . .
t = 0.0;
for ( k = 1; t <= 31; k++ )
{
x = 0.5*a*t*t;
cout.width( 6 ); cout.precision( 1 ); cout << t << " ";
cout.width( 7 ); cout.precision( 2 ); cout << x << endl;
t = t + step;
} // for

for C++ .
.

6.5

. :
while ,
, false.
for,
.
";"
while:
while ( S );

while. while,
. . :
";" while.
, .

6.6 ( )
-


.

( )
(.. -).

:
,
155


,
, ( )
.


6-1 2 6.1.
1 n
.
6-2 ,
n .
n.
.
6-3 6.4.
, -
. (
- ).


6-4 3 cin
>> x. ;
6-5 C++ n-
, :
) a0 = 0, ak+1 = akk + k, k 1
) b0 = b1 = 0, bk = bk1 + bk2 + k, k 2
6-6
10 .
:

.
6-7 ,
.
40 40
. :
,
.
6-8 :
// n > 0
k = 1; sum = 0;
while ( k <= n ) // I: (sum = (k - 1)*k/2)
{ sum = sum + k; k = k + 1; }
// sum = (n + 1)*n/2
156 6


6-9 150
. :
,
10,
(,
).
6-10 , 3.4
:
1. 1 sec,

( 0),
,
.
2. 10 m ,
( 0) ( h)
,
,
( 0),
.
3.
tP, vP h = 100 m, 200 m, ..., 1000 m.
6-11 . n xy, (xk,
yk), k = 1..n, , y = x +, , :
n xy x y y x 2 x xy

n x 2 x2 n x 2 x
2

:
n n n n
x = xk , y = y k , x = nk2 , xy = xk yk
k 1 k 1 k 1 k 1

n
(xk, yk), k = 1..n .
6-12 :
int x, z, u;
:
// x 0
z = 0; u = 1;
while ( u <= x ) // I: (z2 x) && (u = (z+1)2)
{
z = z + 1;
u = u + z + z + 1;
}
// z2 x < (z+1)2
(z2 x) && (u = (z+1)2) while.
, z x . -
x
-
x static_cast <int>(sqrt(x)).
157

6-13 :
int x, c;
:
// x 0
c = x;
while ( c*c*c > x ) // a: x < (c + 1)3
c = c - 1;
// c3 x < (c + 1)3
6-14 : ak = k!/pk | k = 1,2,... p > 1.
p, ,
.
p ,
2p ,
.
6-15
. :
'1' ,
'2' ,
'3'
'4' .
'0' .
, : " 5 ".

.
6-16 :
1 kmax k-1 && tmax == tkmax && j: 1.. k-1 tj tmax
while :
cin >> t; // t == t1
k = 1; tmax = t; kmax = k;
k = k + 1; // == 2
while ( k <= n )
{
cin >> t; // t == tk
if ( t > tmax ) { tmax = t; kmax = k; }
k = k + 1;
} // while
6-17 ) 4.5
unsigned long.
) .
6-18 . 6.17
, , .
6-19 C++. C++ time ,
time(0),
00:00:00 GMT, 1
1970.
#include <ctime>.

0. ,
.
:
,
158 6

,
.

7

:

.
:

.

.
:
()

,


()
return
:
7.1. - ................................................................................................................... 160
7.2. return ........................................................................................................................................ 161
7.3. ............................................................................................................................. 162
7.4. ......................................................................................................................... 166
7.4.1 .................................................................................................................................166
7.4.2 ...........................................................................................................................................................167
7.4.3 .................................................................................................................................169
7.5. main ...................................................................................................................................... 170
7.6. unsigned; ............................................................................................................................ 170
7.7. .................................................................................................................................................... 171
7.7.1 exit() assert() .....................................................................................................................................................178
7.8. () .............................................................................................................. 179
7.9. * .................................................................................................................... 182
7.10. ........................................................................................................................................................ 184
7.11. .............................................................................................................................................. 185
................................................................................................................................................................... 185
.............................................................................................................................................................................185
.............................................................................................................................................................................186
.............................................................................................................................................................................186

159
160 7

:
,
-
. -
(subprograms) , C++, -
(functions)
.
C++ :
(void), .

7.1. -
, C++,
.. sqrt(), exp(), pow(), log(), cos(), sin() .,
. , ,
C++. '
(' )
.
: A B, -
(partial function) f A B (x, y), x A y
B, x y. A
(domain) B ( ) (range) f. :
f: A y B
A x (x, y) f, -
(domain of definition) f. -
f (total function) (function).
:
f: A B
(x, y), x y (image). y = f(x) x k
y.

(x, x ) :
:RyR
R R,
x < 0. :
: R0+ R
, f (x, 1/x), :
f: R y R
: 0 R, f 0.
:
f: R* R

,
.
.
, ,
x y (x, y) f. ..
161

5 fn3: Z R
y = f (x) = 2x2 +
x1
5, 5.5 x 4.5

y f ( x) 0 , 4.5 x 4.5
5, 4.5 x 5.5 double fn3( int x )
{
C++ return x/2.43 + 1;
. } // fn3
fn3: Z R
y = fn3(x) = x/2.43 + 1
x
: y = fn3(x) = +1. . 7-1 . 7-1 -
2.43
C++ -
C++.

C++.
, , -
:
R -
double
fn3
Z int.
x
, . (body) -
.

return ;
. , T
(static_cast<T>), .
; , '
, () . .
;
C++, . .. :
synist = f1*fn3(h/3) + f2 - f3*cos(phi/3+pi/2);
: (function) C++
, .
,
. -
.

7.2. return
: return
:
. return :
-
return .


:
int max( int x, int y )
{
162 7

int fvx;

if ( x > y ) fvx = x;
else fvx = y;
return fvx;
} // max
:
int max( int x, int y )
{
if ( x > y ) return x;
else return y;
} // max
.
:
int max( int x, int y )
{
if ( x > y ) return x;
return y;
} // max
; x > y return x return y -
x > y return x
return y. , .

, ;
:
(return).
.

7.3.
:
, x1, x2, x3
.
(6) .
:
,
.
; :
x1 + x2 + x3 - -
.
:
max3: Z Z Z Z
C++ -
.
:
max: Z Z Z
C++
: max( x1, x2 ) x1, x2,
x1, x2, x3 max( max(x1, x2), x3 ).

min: Z Z Z
:
163

int min( int t, int u )


{
int fvn;

if ( t < u ) fvn = t;
else fvn = u;
return fvn;
} // min
:
#include <iostream>
using namespace std;

// max --
int max( int x, int y )
{
int fvx;

if ( x > y ) fvx = x;
else fvx = y;
return fvx;
} // max

// min --
int min( int t, int u )
{
int fvn;

if ( t < u ) fvn = t;
else fvn = u;
return fvn;
} // min

int main()
{
int x1, x2, x3;

cout << " : "; cin >> x1 >> x2 >> x3;


cout << min( min(x1, x2), x3 ) << " "
<< ( x1+x2+x3 - min(min(x1,x2),x3) - max(max(x1,x2),x3) )
<< " " << max( max(x1, x2), x3 ) << endl;
} // main
.
, main.
main :
: 12 43 5<enter>
: 12 x1, 43 x2 5
x3.
cout << ... -
1. :
min( min(x1, x2), x3 )
min(x1, x2) x3 (actual parameters)
(arguments) (formal parameters) -
min: min(x1, x2) t x3 u.
-
.
:
x3 (5). min(x1, x2)

1 , .
164 7

( min()) : x1 ( 12) t
x2 ( 43) u. .
' min() :
int: t,
int: u,
int: fvn.

. , t 12 ( x1) u 43 ( x2).

return. ifelse fvn
12.
return .
(t, u, fvn). -
return ( fvn) .
min(min(x1, x2), x3) : min(12, 5).
: ( t, u, fvn), 12
t 5 u, ifelse fvn 5.
return fvn min() min(min(x1, x2), x3) -
5 ( ).
-
cout << ... , :
. . . x3 - min( min(x1,x2),x3 ) - max(. . .
max().
:
1. , :
.
, ..
-
. main() :
int main()
{
int x1, x2, x3;
int xmin, xmax;

cout<< " : "; cin >> x1 >> x2 >> x3;


xmin= min( min(x1, x2), x3 );
xmax= max( max(x1, x2), x3 );
cout<< xmin << " " << x1 + x2 + x3 - xmin - xmax << " "
<< xmax << endl;
} // main
, :
int xmin, xmax;
min(min(x1, x2), x3) max(max(x1,
x2), x3). , xmin
xmax min() max(). ,
min max, .
165

7.1

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

(, ).
, , .

return ,
.
2. C -
, :
#include <iostream>
using namespace std;

int max( int x, int y );


int min( int t, int u );

int main()
{
int x1, x2, x3;

cout << " : "; cin >> x1 >> x2 >> x3;


cout << min( min(x1, x2), x3 ) << " "
<< ( x1+x2+x3 - min(min(x1,x2),x3) - max(max(x1,x2),x3) )
<< " " << max( max(x1, x2), x3 ) << endl;
} // main
// max --
int max( int x, int y )
//

// min --
int min( int t, int u )
//
, ,
; :
,
, .
:
int max( int, int );
int min( int, int );
:
int max( int, int ), min( int, int );
166 7

7.4.
.
. :
, . -

. ,
.
C++ . -
main (
7.6).

7.4.1
( ) .
, .
,
.
(. ).
(, )
(local) . -
: -
. -
( ).
, 7.4. :
x1, x2, x3 main() .. cout << x1 <<
x2 << x3 max() ( min())
(unknown identifier ),
.
fvx max() .
fvx main() min()
. , fvn min().
min() :
int min( int x, int y )
{
int fvn;

if ( x < y ) fvn = x;
else fvn = y;
return fvn;
} // min
x, y: max()

7.2

.
.



.
167

min() ; ! min()
min(), max max().
(scope)
x1, x2, x3 main(),
x, y ( max()) fvx max
x, y ( min()) fvn min.
:
; : [ min()] '
min() : )
int t, ) int
u, ) int fvn
return . -
(t, u, fvn).
. 7.2.
. 7.2.

7.4.2
. ,

,
. ,
. . :
int ai( int x )
{ . . .
cout << x << endl; . . . }

int al( long int x )


{ . . .
cout << x << endl; . . . }

int ac( char x )


{ . . .
cout << x << endl; . . . }

int ab( bool x )


{ . . .
cout << x << endl; . . . }

int ad( double x )


{ . . .
cout << x << endl; . . . }

int af( float x )


{ . . .
cout << x << endl; . . . }
:
x = ai( 65.789 );
x = al( 65.789 );
x = ac( 65.789 );
x = ab( 65.789 );
x = ad( 65.789 );
x = af( 65.789 );
, , ,
double.
:
168 7

7.3

:

,
,
, ,

,
return.

.

65
65
A
1
65.789
65.789
, , . .. x
int(65.789) = 65, char(int(65.789)) = 'A',
bool(int(65.789)) = true = 1.
; ..
:
. . .min(x1, x2). . .
:
t = x1; u = x2;
, .
t, u :
int t( x1 ), u( x2 );
,
. ,
:
#include <iostream>
using namespace std;

long int succ( long int n )


{
n = n + 1;
return n;
} // succ

int main()
{
int x = 100, y;

y = succ( x );
cout << x << " " << y << endl;
} // main
:
100 101
: y = succ(x) x (= 100) main() n
succ(). succ() n 1 (101)
169

y main.
, x . ,
, .
,
(value parameters). -
)
2 ) .

7.4.3
. 2 C++
. .
v T :
T v( );
,
, .
-
, v.
:
#include <iostream>
#include <cmath>
using namespace std;

int f( double x )
{
return (2*x+1)/(x*x+1);
} // f

int main()
{
double x( 1.5 );
int n, a( 1 );
double q( sqrt(2) ), qp1( q + 1 + a/2.0 ), r( f(x/3) );

cout << " n = " << n << " a = " << a << endl;
cout << q << " " << qp1 << " " << f(q) << " " << r << endl;
a = 2;
cout << qp1 << endl;
} // main
:
n = 50920484 a = 1
1.41421 2.91421 1 1
2.91421
:
n a
. n . a 1.
q sqrt(2) (1.41421). qp1
q a . r
f ( (2*x+1)/(x*x+1) double (1.6)
int (1) ).
(1) f(q).

2 4.5 cin.get( a ); a.
170 7

a 2. qp1 ,
.

. max():
int max( int x, int y )
{
int fvx( y );

if (x > y) fvx = x;

return fvx;
} // max

7.5. main
main() . C++ -
:
int main
.3
return; ! , , C++
,
main() return 0. , C++ :
main() (
return) return 0. 0
.
.
main() ( ) .

7.6. unsigned;

unsigned (.. unsigned int) .

. 6-12:
unsigned int intSqrt( unsigned int x )
{
int z( 0 ), u( 1 );
// x >= 0
while ( u <= x ) // I: (z <= x) && (u = (z+1))
{
z = z + 1;
u = u + z + z + 1;
}
// z <= x < (z+1)
return z;
} // intSqrt
; unsigned int, ! :
n = 1024;
cout << n << " " << intSqrt(n) << endl;
n = -1024;
cout << n << " " << intSqrt(n) << endl;
:

3 Windows WinMain.
171

1024 32
-1024 699732
, , ... !
:
unsigned int intSqrt( unsigned int x )
{
int z( 0 ), u( 1 );
cout << x << endl;
. . .
:
4294966272
-1024 699732
, -1024 4294966272
.
.
:
unsigned int, unsigned long
int, unsigned short int, unsigned char , : int, long int, short
int, char. .
:
unsigned int intSqrt( int x )
{
int z( 0 ), u( 1 );

if ( x >= 0 )
{ // x >= 0
while ( u <= x ) // I: (z <= x) && (u = (z+1))
{ . . .
-
. .

7.7.

.
1
, m, n
m n.
, :
m m!
=
n n!( m n)!
, n! (n ), :
1 n0 1 n0
n! = : n! =
n (n 1)! n 1 1 ... (n 1) n n 1
, , factorial(),
, :
cin >> m >> n;
comb = factorial(m) / (factorial(n) * factorial(m-n));
cout << comb << endl;
, . .
:
172 7

!: N N*
N, N* C++; unsigned int
. n! , n,
unsigned long int.
:
factorial: unsigned int unsigned long int
:
factorial: int y unsigned long int
:
unsigned long int factorial( int a )
{
unsigned long int fv;

if ( a < 0 )
{
cout << " factorial " << endl;
exit( EXIT_FAILURE );
}
else
{
if ( a == 0 )
fv = 1;
else
fv = 1*2*...*(a-1)*a;
}
return fv;
} // factorial
exit( EXIT_FAILURE ) ; exit()
assert() cstdlib.
( -
). . -
,
. cstdlib
EXIT_FAILURE 1.
, :
unsigned long int factorial( int a )
{
unsigned long int fv;

if ( a < 0 )
{
cout << " factorial " << a << endl;
exit( EXIT_FAILURE );
}
if ( a == 0 )
fv = 1;
else
fv = 1*2*...*(a-1)*a;
return fv;
} // factorial

.
. 6.2 . :
fv = 1;
for ( k = 1; k <= a; k=k+1 ) fv = fv*k;
fv k , .
173

, a == 0
a > 0
a == 0.
#include <iostream>
#include <cstdlib>
using namespace std;

// factorial -- a!
unsigned long int factorial( int a )
{
unsigned long int fv;
int k;

if ( a < 0 )
{
cout << " factorial " << a << endl;
exit( EXIT_FAILURE );
}
fv = 1;
for ( k = 1; k <= a; k=k+1 ) fv = fv*k;
return fv;
} // factorial

int main()
{
int m, n, comb;

cout << " m, n <= 50, m >= n: ";


cin >> m >> n;
if ( n < 0 || m < 0 )
cout << " m >= 0 n >= 0 " << endl;
else if ( m < n )
cout << " m >= n" << endl;
else
{
comb = factorial( m ) / ( factorial(n)*factorial(m-n) );
cout << " "
<< m << " " << n << " = " << comb << endl;
}
} // main
:
comb = factorial( m ) / ( factorial(n)*factorial(m-n) );
factorial(). -
:
m <= n <= 50: 5 2
cin >> m >> n : m = 5 n = 2:
factorial( m ) : a factorial()
m = 5. factorial()
(= 120).
factorial( n ) (= 2).
, factorial( m - n ), m n
(= 3). a factorial() ,
6.
4: 120 / (2 * 6) comb
10:

4
. , .
174 7

5 2 = 10

2
(,
least common multiple, lcm) (, gratest common divisor,
gcd) .
.
, : x, y
(x, y)(x, y) = xy. ,
.
, :
5. :
x y (x % y)
(y, x % y).
., x = y N y = x % y.
( (x,y) = (y, x % y) )
, y == 0.
.
:
while ( y != 0 ) // (x,y) = (y,x % y)
{
b = y; // y
y = x % y;
x = b; // y
}
return x; // (x,0) = x
C++,
. x == y == 0. :
: N N \ { (0,0) } N
.
. ; -
!
gcd() C++ . -
(0,0).
, gcd() , , -
unsigned int int:
gcd: int int y unsigned int
:
unsigned int gcd( int x, int y )
{ // x == x0 && y == y0
unsigned int b;

if ( (x == 0 && y == 0) || x < 0 || y < 0 )


{
cout << " gcd " << x << ", " << y << endl;
exit( EXIT_FAILURE );
}
// (x != 0 || y != 0) && x >= 0 && y >= 0
while ( y != 0 ) // I: (x,y) == (x0,y0)
{
b = y; y = x % y; x = b;
} // while

5
. .
175

return x; // (x,0) = x
} // gcd
.
#include <iostream>
#include <cstdlib>
using namespace std;

// gcd --
unsigned int gcd( int x, int y )
//

// lcm -- .
// gcd
unsigned int lcm( int x, int y )
{ // (x,y)*(x,y) = x*y
unsigned int fv;

if ( (x == 0 && y == 0) || x < 0 || y < 0 )


{
cout << " lcm " << x << ", " << y << endl;
exit( EXIT_FAILURE );
}
// (x != 0 || y != 0) && x >= 0 && y >= 0
fv = x * y / gcd(x, y);
return fv;
} // lcm

int main()
{
int x1, x2;

cout << " : "; cin >> x1 >> x2;


if ( x1 <= 0 || x2 <= 0 )
cout << " : " << endl;
else
cout << " = " << lcm( x1, x2 )
<< " = " << gcd( x1, x2 ) << endl;
} // main
main() ,
, lcm(), , gcd().
:
1. x 0 || y 0
(x, y) = (|x|,|y|)
gcd() .
2. , lcm(), ,
gcd(), gcd()
. .

3
, static_cast<int> -
. static_cast<long int>.
(round) -
. :
myRound: R Z
double -
long int.6 double; !

6 cmath lround. -
. D.
176 7


( LONG_MIN - , LONG_MIN + ]
LONG_MIN . ,

[ LONG_MAX - , LONG_MAX + )
LONG_MAX .

( LONG_MIN - , LONG_MAX + )

myRound: double y long int
.
: ; 7.3,
7. : static_cast<long
int>(7.3) . 7.8;
: ( ) 0.5 (.. 0.8, 7.8)
(8) -
0.5 (8.3).
static_cast<long int>(7.8 + 0.5) (8).
7.3:
static_cast<long int>(7.3 + 0.5) == 7. 0.5:
if ( x >= 0 ) fv = static_cast<long int>(x + 0.5);
else fv = static_cast<long int>(x - 0.5);
myRound() .
#include <iostream>
#include <cstdlib>
#include <climits>
using namespace std;

// myRound --
long int myRound( double x )
{
long int fv;

if ( x <= LONG_MIN - 0.5 || LONG_MAX + 0.5 <= x )


{
cout << " myRound : " << x << endl;
exit( EXIT_FAILURE );
}
// LONG_MIN - 0.5 < x && x < LONG_MAX + 0.5
if ( x >= 0 ) fv = static_cast<long int>( x + 0.5 );
else fv = static_cast<long int>( x - 0.5 );
return fv;
} // myRound

int main()
{
double t;

cout << " . 0 : "; cin >> t;


while ( t != 0 )
{
cout << " myRound(" << t << ") = " << myRound( t ) << endl;
cout << " . 0 : "; cin >> t;
} // while
cout << " myRound(" << t << ") = " << myRound( t ) << endl;
} // main
177

myRound() , -
(. 7-18), x
myRound(x);
x 0. , (x), : 0 (x) < x
, :
myRound(x) = x - (x) (x) = x - myRound(x)
: 0 x - myRound(x) < :
myRound(x) x < myRound(x) + x - < myRound(x) x
(x) < 1 x :
x 1 - (x). :
myRound(x) = x + 1 - (x) (x) = x + 1 - myRound(x)
: x + 1 - myRound(x) < 1 :
myRound(x) - x < myRound(x) x < myRound(x) x +
x 0 :
myRound(x) - x < myRound(x) + x - < myRound(x) x +
x < 0 :
myRound(x) - < x myRound(x) + x - myRound(x) < x +

4
n
7. dRound() :
dRound: R N R
; .
1.347 n = 2 (1.35).
:
1.347 102 = 134.7
myRound(134.7) = 135
135 / 102 = 1.35
// dRound - n
// . myRound
double dRound( double x, int n )
{
double tenTo( pow(10, n) );

return myRound(x*tenTo)/tenTo;
} // dRound
; ! ,
myRound() :
LONG_MIN - 0.5 x10n LONG_MAX + 0.5
n long int ( double)
x: long int 10 x 8
n = 5.
, -
.
x, myRound(x) x,
n, dRound(x, n) (. 7-19).
. n 0. n = 0
myRound ( ), n = -1

7 :
1.11.
178 7

, n = -2 ... -
lround() myRound().

,
. .

7.7.1 exit() assert()


if exit() assert() (4.3); !
:
main() . 1 :
int main()
{
int m, n, comb;

cout << " m, n <= 50, m >= n: ";


cin >> m >> n;
comb = factorial( m ) / ( factorial(n)*factorial(m-n) );
cout << " "
<< m << " " << n << " = " << comb << endl;
} // main
:
m, n <= 50, m >= n: 2 5
factorial -3
factorial() :
unsigned long int factorial( int a )
{
unsigned long int fv;
int k;

assert( a >= 0 );

fv = 1;
for ( k = 1; k <= a; k=k+1 ) fv = fv*k;
return fv;
} // factorial
#include <cassert>. :
m, n <= 50, m >= n: 2 5
Assertion failed: a >= 0, file combA.cpp, line 12
;

!

/ .
de gustibus et coloribus non dispu-
tandum :
-
2 5; ,
, factorial() .
, , .
179

7.8. ()
,
.
. -
.
, :
,
.
, C++
. Z int (long
int), R ( ) double. -
:
2
: R R R R+
:
EuMetro: double double double double

. .., . 3 :
myRound: R Z
myRound: double y long int
. 2:
: N N \ { (0,0) } N
gcd: unsigned int unsigned int y unsigned int
;

. C++, -
(exception handling) .
;
exit()
.
"domain error"
( )
.
"domain error"
. ,
, (;) .
, -
.
: , f, ,
T, . f (x+kT) = f (x) k.
() , [a, b), (b = a + T),
.
(x)
x0, , f (x0) = f (x). :
x0 = x;
while ( x0 >= b ) x0 = x0 - T;
// (x0 < b) && (f(x0) == f(x))
while ( x0 < a ) x0 = x0 + T;
// (a x0 < b) && (f(x0) == f(x))
180 7

f (x0) == f (x) while,


x0 x
.
. C++
( , x) floor: double double,
floor(x) x.
x0 (. 7-11):
m = floor((x-a)/T);
x0 = x - m*T;
// (a x0 < b) && (f(x0) == f(x))
:
1. : double
( float long double) , x0
== v . : fabs(x0 v) <= eps.
2.
, , x - m*T 0 ().
3.
(a, b] : a
x0 < b. a == x0 b8:
m = floor( (x-a)/T );
x0 = x - m*T;
// (a x0 < b) && (f(x0) == f(x))
if (x0 <= a) x0 = x0 + T;
// (a < x0 b) && (f(x0) == f(x))
. 7.4. -
.

:
1 1 1
v( x) x[-1,1)
| x 2| | x| | x 2|
T = 2. C++.
1. [1,1) 0 ().
2, R
2k k . :
v: R\ { k Z 2k } R
: R\ { k Z 2k } R.
2. .
3. R\ { k Z 2k } R double.
4. :
double v( double x )
5. , , v , C++ :
v: double y double
.
6. : [1,1) :
m = floor( (x-(-1))/T );
x0 = x - m*T;
// (-1 x0 < 1) && (v(x0) == v(x))

8 floor, ceil. .
7-12.
181

7.4
() C++
() C++ :
1. () .
2. (f(x))
(x).
3. C++ -
.
:
N, N* int long int, ,
unsigned int unsigned long int, .
Z, Z* int long int.
R R double long double float,
4. -
.
5. 3,
( ) .
6. , (x0)
, (x), : x0
f(x0) = f(x).
7. ,
:
if ( x )
{
cout << " ... x = " << x << endl;
exit( EXIT_FAILURE );
}
else

8. C++ 2.
7. . x x0 [1,1),
V 0.
:
if ( x0 == 0 )
{
cout << " v : " << x << endl;
exit( EXIT_FAILURE );
}
x0 x. ,
x0 == 0 . fabs(x0) < eps,
eps double .
8. :
fv = -1/fabs(x0+2) - 1/fabs(x0) - 1/fabs(x0-2);
:
double v( double x )
{
const double a( -1 ), b( 1 ), T( b-a );
double x0( x ), fv, m;
182 7

m = floor( (x-a)/T );
x0 = x - m*T;
// (-1 x0 < 1) && (v(x0) == v(x))
if ( x0 == 0 )
{
cerr << " v : " << x << endl;
exit(EXIT_FAILURE);
}
// (-1 x0 < 1) && (v(x0) == v(x))
fv = -1/fabs(x0+2) - 1/fabs(x0) - 1/fabs(x0-2);
return fv;
} // v

7.9. *
, sqrt(x) ( )
x , . -
x 0.
.
:
Tf f(T1 p1, T2 p2,... Tn pn)
{
Tf fv;
:
// Pd(p1, p2,... pn)
:
// Qd(p1, p2,... pn, fv)
return fv;
} // f
( ) :
.
, , , -
.
, f, f(t1, t2,... tn),
Pd(t1, t2,... tn).
f(t1, t2,... tn) Qd(t1, t2,... tn, f(t1, t2,... tn)).
:
Qd(p1, p2,... pn, fv) p1, p2,... pn
. -
.


( , , ) .
:
(1) || + || > 0 ( ) (,) = (,),
:.
:
(2) 0 (0,) = .
unsigned int gcd( int x, int y )
{ // x == x0 && y == y0
unsigned int b;

if ( (x == 0 && y == 0) || x < 0 || y < 0 )


183

{
cout << " gcd " << x << ", " << y << endl;
exit( EXIT_FAILURE );
}
// (x == x0 && y == y0) &&
// (x != 0 || y != 0) && x >= 0 && y >= 0
while ( y != 0 ) // I: (x,y) == (x0,y0)
{
b = y; y = x % y; x = b;
} // while
return x; // (x,0) = x
} // gcd
; :
// (x == x0 && y == y0) &&
// (x != 0 || y != 0) && x >= 0 && y >= 0
while ( y != 0 ) // I: (x,y) == (x0,y0)
{
b = y; y = x % y; x = b;
} // while
// x == ( x0, y0 )
:
Pd(x0, y0) : (x0 >= 0) && (y0 >= 0) && (!(x0 == 0 && y0 == 0))
Qd(x0, y0, x) : x == (x0, y0)
if ; if -
: . if
( ) .
: (x,y) == (x0,y0)
while :
!(y != 0) && ((x,y) == (x0,y0))
:
(y == 0) && ((x,y) == (x0, y0))
(x,0) == (x0, y0) (2): x == (x0, y0).

1. (x,y) == (x0,y0) while
2. :
// (y != 0) && ((x,y) == (x0,y0))
b = y; y = x % y; x = b;
// (x,y) == (x0,y0)
1. : (x,y) == (x0,y0) x == x0 && y == y0.
(x0 >= 0) && (y0 >= 0) && (!(x0 == 0 && y0 == 0)) ;
(x0,y0).
2.:
// (y, x % y) == (x0,y0)
b = y;
// (b, x % y) == (x0,y0)
y = x % y;
// (b,y) == (x0,y0)
x = b;
// (x,y) == (x0,y0)
(y, x % y) == (x0,y0) ; ,
: (x, y) == (x0,y0) (1) : (x, y) == (y, x % y).
: (y, x % y) == (x0,y0).
.
184 7

, , gcd(1, 2), 1
2 unsigned int,
, , gcd gcd(1,2) == (1,2).

7.10.




...
. ,
C++ ,
.
n!, :
1 n0
n! =
(n 1)!n n 1
C++
(recursive function) :
// rFactorial -- a!
unsigned long int rFactorial( int a )
{
unsigned int k, fv;

if ( a < 0 )
{
cout << " rFactorial " << a << endl;
exit( EXIT_FAILURE );
}
if ( a == 0 ) fv = 1;
else fv = a*rFactorial( a-1 );
return fv;
} // rFactorial
rFactorial()
. ,
-
,
.
, , -
, -
.

. .
'
. , -
.
:
.
// rGcd --
//
unsigned int rGcd( int x, int y )
{
unsigned int fv;
185

if ( x < 0 || y < 0 || (x == 0 && y == 0) )


{
cout << " rGcd " << x << ',' << y << endl;
exit( EXIT_FAILURE );
}
if ( y == 0 ) fv = x; // (x,0) = x
else fv = rGcd(y, x % y);// (x,y) = (y,x % y)
return fv;
} // rGcd

7.11.
C++ ( )
.

(-
),
( ).
,
.
( ) -
,
.
return

.
return,
, .

.

, , ,
.


7-1 , , -
a, b, c d ( ).
7-2 )
. -
( ) 0 (). -
.
) ( )
.
( )
. .
7-3 ( . 2-9 5-5) -
2%, , . ,
186 7

30 , (3) .
3 50 .
:
double salary( double base, int years, int noOfCldr )
. , ..:
, .
, .
7-4 . 5-6, :
double resistors( char mode, double r1, double r2 )
r1, r2
(mode == 'S') (mode == 'P').
7-5 5.3, :
double elEnergyCost( double cons )
.
. 6-3 .


7-6 :
double dTrunc( double x, int n )
x, n-
.
.: dRound 2.8.
7-7 . 4-15,
C++
:
// isGAlpha -- true ch
// . false
bool isGAlpha( char ch )
// isGUpper -- true ch
// . false
bool isGUpper( char ch )
// isGLower -- true ch
// . false
bool isGLower( char ch )
. 4-15,
.
7-8 :
// upCase -- ch
// , ch
char upCase( char ch )
// loCase -- ch
// , ch
char loCase( unsigned char ch )
: gUpCase(), gLoCase().


7-9 M . 2 6.3
double nrsqrt( double a )
187

a.
sqrt C++.
7-10 , a, x3 a = 0, -
Newton-Raphson, xn = xn1 f (xn1)/f (xn1), ,
:
f (x) = x3 a, f (x) = 3x2
:
1 a
xn = 2 xn 1 2
3 xn 1
x0 = a
|xn3 a| < doublea. , a == 0 , -
.
double cbrt( double a )
.
(x) cbrt(x) pow(x, 1/3.0) C++.
*7-11 v() T b-a = T :
) :
// true
x0 = x;
while ( x0 >= b ) x0 = x0 - T; // : v(x0) == v(x)
while ( x0 < a ) x0 = x0 + T; // : v(x0) == v(x)
// (a x0 < b) && (v(x0) == v(x))
) :
// true
m = floor( (x-a)/T );
x0 = x - m*T;
// (a x0 < b) && (v(x0) == v(x))
floor() : floor(x) Z x - 1 < floor(x) x.
*7-12 v T b-a = T :
// true
m = ceil( (x-a)/T );
x0 = x - m*T;
// (a < x0 b) && (v(x0) == v(x))
ceil() : ceil(x) Z x ceil(x) < x + 1.
7-13 k, k-
, :
a0 = 0, ak+1 = akk + k, k N*
.
*7-14 Fibonacci : f0 = 0, f1 = 1 fk = fk-2 + fk-1 k > 1.
:
int rFib( int k )
fk. int fib( int k
) .
7-15
double mp( double x, int n )
:
n 1
1 1 1 1
mp ( x ,n) x k x 0 x 1 ... x (n 1) , n 1.
k 0

*7-16 .
188 7

7-17 :
1, n x 1

q( x , n) x , 1 x 1
1, 1 x n

n > 1. x 2n. -
C++.
*7-18 myRound() (7.7, . 3) , :
// true
if (x >= 0) fv = (long int) (x + 0.5);
else fv = (long int) (x - 0.5);
// (x 0 && x - < myRound(x) x + ) ||
// (x < 0 && x - myRound(x) < x + )
.: . 3-6;
*7-19 dRound() (7.7, . 4) :
x 0
x 0.510-n < dRound(x, n) x + 0.510-n
dRound(x, n) 0.510-n x < dRound(x, n) + 0.510-n
x < 0
x 0.510-n dRound(x, n) < x + 0.510-n
dRound(x, n) 0.510-n < x dRound(x, n) + 0.510-n

8
- Text
:

-.
:

.
text ( -
) .
:

- (text)
- (binary)
:
8.1 C++ ................................................................................................................................. 191
8.2 - ...................................................................................................................... 192
8.3 ............................................................................................................................ 193
8.3.1 cin.eof() .............................................................................................................................................................196
8.3.2 .............................................................................................................196
8.4 .............................................................................................................................. 197
8.5 .......................................................................................................................... 199
8.6 ............................................................................................................................... 201
8.7 ........................................................................................................................................... 204
8.8 .................................................................................................................................................... 205
8.9 -: .............................................................................................................. 205
8.10 ................................................................................................................................................... 207
8.11 ................................................................................................................................ 211
8.12 () ....................................................................................................... 212
8.13 C ...................................................................................................... 214
8.14 .............................................................................................................................................................. 217
................................................................................................................................................................... 218
.............................................................................................................................................................................218
.............................................................................................................................................................................218
.............................................................................................................................................................................219

:
, -
, ,
. , ,
189
190 8

.
, ,

.
(serial sequential file).

. 1. -
. 0.
:
(size) -
.
== .

:
< -7, -15, 0, 14, 33, -8, 16, 114, 375 >
int 9.
:
<'m', 'a', 'i', 'n', '(', ')', '{', '}'>
char 8 ( C++).
:
<true, true, false, true, false, false, true>
bool 7.

;
: -
. (text)
(formatted file)2. :
. , -
, ,
. -
(binary) (unformatted).
-:
-
.
, .
:
,
,

()
.
:

1 "<", ">", "," .


: ) )
C++. , .
: <>.
2 ascii.
- Text 191

( )
.
:
.
.
, ,
-,
. , -

-,
,
() .
-.

8.1 C++
() -
(file manager) (file system).
(directories) :
, , , -
. ,
.

,
Windows:
Volume in drive C has no label
Serial Number of Volume is 50DA-631A

Directory of C:\0809bea\t02

14/04/2009 03:10 AM <DIR> .


14/04/2009 03:10 AM <DIR> ..
13/04/2009 09:59 AM 7,875 AircraftType.cpp
13/04/2009 09:57 AM 3,319 AircraftType.h
24/03/2009 02:52 PM 250 aircraftTypes.txt
13/04/2009 09:05 AM 14,016 ask01a.cpp
13/04/2009 03:28 AM 522,116 ask01a.exe
13/04/2009 09:41 AM 14,538 ask01b.cpp
13/04/2009 09:41 AM 520,081 ask01b.exe
24/03/2009 03:36 PM 7,636 flightHours.txt
17/11/2008 10:08 PM 7,090 MyLib.cpp
13/04/2009 10:00 AM 3,856 nAircraftTypes.txt
13/04/2009 09:34 AM 3,856 nPilots.txt
13/04/2009 10:16 AM 233,472 ooPr_t02.doc
13/04/2009 10:18 AM 604 ooPr_t02.log
13/04/2009 10:20 AM 362,918 ooPr_t02.pdf
13/04/2009 10:17 AM 1,146,318 ooPr_t02.prn
13/04/2009 10:21 AM 371,671 ooPr_t02.ZIP
13/04/2009 06:50 AM 367,616 ooPr_t02b.doc
13/04/2009 03:23 AM 7,126 Pilot.cpp
13/04/2009 03:19 AM 3,441 Pilot.h
24/03/2009 04:03 PM 1,583 pilots.txt
09/04/2009 02:12 PM 677,110 t02.rar
20 file(s) 4,276,492 bytes
2 Directories 50,009,026,560 bytes free
192 8

() : , ( ),
.

:
1. ,
2. , C++, (stream)
( )
( ).
3. , .
(open) .
() C++:
ifstream (input file stream),
ofstream (output file stream),
fstream .

fstream (#include <fstream>).

. (class) .
(objects). (encapsulated)
(methods) - (member functions), -
. .. -
open . :
ifstream a;
a text1.txt :
a.open( "text1.txt" );
(inheritance)
- , .. , . -
,
text1.txt :
a >> x;
:
cin >> x;
cin istream. ifstream istream
, ios_base,
>>.
.

8.2 -
() -
.
(. 8-1).
. , ,
. , ,
, . - -
.
( ) (
) . / (read/write head).
- Text 193

. 8-1 -
a

-

-. -
. -
-

. text1.txt
. 8-1 - (text1.txt)
.
a .
-
-
buffer. - .
: . -
. /
:
( , CPU)
.
. ,
( 1 kB, 2 kB). -
(.. '-'
'7') , .., 1024 . ,
. ,
, .
, .

8.3
- text1.txt.
.
, ifstream.
:
ifstream a;
:
a.open( "text1.txt" );
. 8-1
open(). / .
:
short int x, y;
x.
:
a >> x;
-
:
a
1.
'-'.
2. -
'-' '7'
.
text1.txt
3.
. 8-2 text1.txt a
.
.
194 8

4. 7
x.
. 8-2 .
,
:
y = x*x;
cout << " x = " << x << " x^2 = " << y << endl;
:
x = -7 x^2 = 49
,
:
a >> x;
a -
'-', '1', '5'. 8.
,
'1', '4'.


. 8-3. a

a >> x -

x .


0 1 text1.txt
- . 8-3 -
. - a >> x; x .
; ! ifstream , a.eof()
eof ( - (true).
) end of
file ( ). a.eof()
-
( true)
( -
false).
, x.
-
. -
. C++ SHRT_MAX = 32767,
181 (
SHRT_MAX ) x % 181.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream a;
short int x, xr, y;

a.open( "text1.txt" );
a >> x;
while ( !a.eof() )
- Text 195

{
if ( abs(x) > 181 ) xr = x % 181;
else xr = x;
y = xr*xr;
cout << " x ="; cout.width(4); cout << x;
cout << " xr ="; cout.width(4); cout << xr;
cout << " xr^2 ="; cout.width(5); cout << y << endl;
a >> x;
} // while
a.close();
} // main
:
x = -7 xr = -7 xr^2 = 49
x = -15 xr = -15 xr^2 = 225
x = 8 xr = 8 xr^2 = 64
x = 14 xr = 14 xr^2 = 196
x = 33 xr = 33 xr^2 = 1089
x = -8 xr = -8 xr^2 = 64
x = 16 xr = 16 xr^2 = 256
x = 114 xr = 114 xr^2 =12996
x = 375 xr = 13 xr^2 = 169
:
a.close();
a text1.txt. -
.
. . 8.1
. a.open(..) -
a.eof()
.
. ,
.

1. :
( 33). :
i. (. 8-1).
ii. .
iii. .

:
( ) -
' 1 .
,
.
196 8

8.1

ifstream a;
:
a.open( );
a >> x;
while (!a.eof())
{
x
a >> x;
} // while
a.close();

2. : a
>> x !a.eof() true, -
, x. :
( ) -
eof .
3. - >>,
() , (tabs).
C++ (white spaces).
4.
(path).
Windows '\' , ,
. ..:
c:\students\datfl\text1.txt
:
a.open( "c:\\students\\datfl\\text1.txt" );
4. , ..:
ifstream a( "text1.txt" );
, a.open("text1.txt") .

8.3.1 cin.eof()
-
cin; ! eof
char(3) (End of TeXt, ETX) <ctrl-C>
char(4) (End Of Transmission, EOT) <ctrl-D>
char(26) <ctrl-Z> ( Windows).
. -
Windows ETX
( .) , -
MS-DOS, <ctrl-Z>. gcc (.. Dev C++)
BC++ 5.02.

8.3.2

ifstream a( "text1.txt" );
- Text 197

text1.txt -
a.eof(). ; 3 , ,
:
() close()!
: -
.
-
:
a.clear();
a.eof() a
, text2.txt. :
a.close();
a.open( "text2.txt" );
. :
a.clear();
a.close();
a.open( "text2.txt" );

8.4
-
text2.txt
-. - a


.
:
ofstream a;
ofstream open() . 8-4 - (text2.txt)
: a . -

a.open( "text2.txt" );
a.open('text2.txt'). -
open() .
ifstream: text2.txt ,
open() !
. . 8-4 open().
23. ;
: ifstream >>, cin, ofstream
, cout, <<. :
a << 23;
-
text2.txt
. 8-5: a
1.

'2', '3'.
2. -
.
. 8-5 - (text2.txt)
3. .
a :
: a << 23.
a << " " << 31 << endl;

3 C++ (std::ios::)bad, ...


198 8

. 8-6.
:
. - a text2.txt
: a << 31, 31
23 2331.
endl
. cout
'\n' . 8-6 -
: a << " " << 31 << endl.
ofstream, a; ! - endl
'\n' (= char(10))
- .
C++.
:
endl :

( -
) .
'\n' .
.
endl . : , ,
,
, . ,
'\n', .
close().
close() .

, - text2.txt. -
(0,0).
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ofstream a;
int x, y;

a.open( "text2.txt" );
cout << " x, y. 0,0 : "; cin >> x >> y;
while ( x != 0 || y != 0 )
{
a.width( 5 ); a << x;
a.width( 5 ); a << y << endl;
cout << " x, y. 0,0 : "; cin >> x >> y;
} // while
a.close();
} // main
:
1. a.width(5); cout.width(5).
a 5 . ,
ofstream precision setf.
2. while:
cout << " x, y. <ctrl-Z> : "; cin >> x >> y;
- Text 199

while ( !cin.eof() )
{
a.width( 5 ); a << x;
a.width( 5 ); a << y << endl;
cout << " x, y. <ctrl-Z> : ";
cin >> x >> y;
} // while
<ctrl-Z>.4 ,
!

8.5

. -
. .
exp4.txt double. T
. ,
.
: ,
10.
: , ! !. -
. . 6 (6.1.2)
4, (.
8.1) 5.
a. :
ifstream a;
- ; ! !
.
:
a.open( "exp4.txt" );
a >> x;
while ( !a.eof() )
{
E
a >> x;
} // while
a.close();
; :
n = n + 1; //
sum = sum + x; //
if ( 0 < x && x <= 10 ) // '
{
selSum = selSum + x; //
selN = selN + 1; //
} // if
5. 4
. ,
.
// : 5
#include <iostream>
#include <fstream>
using namespace std;
int main()

4
200 8

{
ifstream a;

int n; //
int selN; //
double x; //
double sum; //
double selSum; //
double avrg; //
double selAvrg; //

sum = 0; n = 0;
selSum = 0; selN = 0;
a.open( "exp4.txt" );
a >> x;
while ( !a.eof() )
{
n = n + 1; //
sum = sum + x; //
if ( 0 < x && x <= 10 ) // '
{
selSum = selSum + x; //
selN = selN + 1; //
} // if
a >> x;
} // while
a.close();
cout << " " << n << " " << endl;
if ( n > 0 )
{
avrg = sum / n;
cout << " = " << sum << " <x> = " << avrg << endl;
} // if ( n
cout << " " << selN << " (0,10]" << endl;
if ( selN > 0 )
{
selAvrg = selSum/selN;
cout << " = " << selSum
<< " <x> = " << selAvrg << endl;
} // if ( selN
} // main
.
: -
- report.txt.
5;
b ofstream,
report.txt.
, cout report.txt b.
// : 6
#include <fstream>
using namespace std;
int main()
{
ifstream a;
ofstream b;
// . . .
b.open( "report.txt" );
b << " " << n << " " << endl;
if ( n > 0 )
{
avrg = sum / n;
b << " = " << sum << " <x> = " << avrg << endl;
} // if ( n
b << " " << selN << " (0,10]" << endl;
- Text 201

if ( selN > 0 )
{
selAvrg = selSum/selN;
b << " = " << selSum
<< " <x> = " << selAvrg << endl;
} // if ( selN
! #include <iostream>! !
: cin cout .
report.txt:
37 o
= 560.767 <x> = 15.1559
12 o (0,10]
= 46.6869 <x> = 3.89057

8.6
:
x1, x2, ...
10000 fltnum.txt. :
) <x>,
x x
) : e x
xxk
. yk = e x
.
! :

. yk -
, (
), .
:


xxk
(xk) yk = e x

:
(n) :

if ( n > 0 )
{
xxk
(xk) yk = e x }
3 :
.
: 0
9999.
const double sentinel = 9999.0;
ofstream a;
// . . .
sum = 0; n = 0;
a.open( "fltnum.txt" );
cout << " - 9999 : "; cin >> x;
while ( x != sentinel )
{
//
a << x << endl;
// sum
202 8

n = n + 1;
sum = sum + x;
cout << " - 9999 : "; cin >> x;
} // while
a.close();
cout << " " << n << " " << endl;
if ( n > 0 )
{
avrg = sum / n;
cout << " = " << sum
<< " <x> = " << avrg << endl;
}
:
ifstream b; //

b.open( "fltnum.txt" ); m = 0;
b >> x;
while ( !b.eof() )
{
m = m + 1;
y = exp( (avrg - x)/avrg );
cout << " x[";
cout.width(3); cout << m << "] = ";
cout.width(6); cout << x << " y[";
cout.width(3); cout << m << "] = " ;
cout.width(6); cout << y << endl;
b >> x;
} // while
b.close();
n > 0.
:
// : 3+
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
const double sentinel = 9999.0;
ofstream a;
ifstream b; //
int n; // .
//
double x; //
double sum; // () .
// .
double avrg; // x (<x>)
int m;
double y;

sum = 0; n = 0;
a.open( "fltnum.txt" );
cout << " - 9999 : "; cin >> x;
while ( x != sentinel )
{
//
a << x << endl;
// sum
n = n + 1;
sum = sum + x;
cout << " - 9999 : "; cin >> x;
} // while
a.close();
cout << " " << n << " " << endl;
if ( n > 0 )
- Text 203

{
avrg = sum / n;
cout << " = " << sum
<< " <x> = " << avrg << endl;
b.open( "fltnum.txt" ); m = 0;
b >> x;
while ( !b.eof() )
{
m = m + 1;
y = exp( (avrg - x)/avrg );
cout << " x[";
cout.width(3); cout << m << "] = ";
cout.width(6); cout << x << " y[";
cout.width(3); cout << m << "] = " ;
cout.width(6); cout << y << endl;
b >> x;
} // while
b.close();
}
} // main
-
. -
; !
fstream. ;
:
fstream a;
: open() , -
: ios_base::in ,
ios_base::out ,
ios_base::in|ios_base::out
.5
:
a.open( "fltnum.txt", ios_base::in|ios_base::out );
: .
;
fstream ( ifstream) , seekg(), 0 -
: a.seekg(0) (-
).
:
// : 3+ inout
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
const double sentinel = 9999.0;
fstream a; //
int n; // .
//
double x; //
double sum; // () .
// .
double avrg; // x (<x>)

5 ; !
. ,
: ios_base::in+ios_base::out.
204 8

int m;
double y;

sum = 0; n = 0;
a.open( "fltnum.txt", ios_base::in|ios_base::out );
cout << " - 9999 : "; cin >> x;
while ( x != sentinel )
{
//
a << x << endl;
// sum
n = n + 1;
sum = sum + x;
cout << " - 9999 : "; cin >> x;
} // while
cout << " " << n << " " << endl;
if ( n > 0 )
{
avrg = sum / n;
cout << " = " << sum
<< " <x> = " << avrg << endl;
a.seekg( 0 );
a >> x;
while ( !a.eof() )
{
m = m + 1;
y = exp( (avrg - x)/avrg );
cout << " x[";
cout.width(3); cout << m << "] = ";
cout.width(6); cout << x << " y[";
cout.width(3); cout << m << "] = " ;
cout.width(6); cout << y << endl;
a >> x;
} // while
}
a.close();
} // main

8.7
8.5 ,
! ; ; ,
-
! ;
-
. ;
- ! , : -
, Notepad Windows ( )
, Word,
text ( ascii ).
:
.
6.
, ; !

6 ,
.
- Text 205

.
.

8.8
fstream, ifstream, ofstream, fstream, :
istream ostream
.
C++
:
istream cin;
(standard input) , ,
.
ostream cout;
(standard output) , , -
. :
ostream cerr;
(standard error)
. , :
ostream clog;
(standard log file)
.
, -
() , .

8.9 -:
- (text) :
.
.
, - ::


...
,
:
, ..., ,


.
- ,
<< >> , get(), peek(), ifstream fstream
put() ofstream fstream.
;
. ASCII, , -
(-) :
CR (Carriage Return) 13 ('\r' C++)
LF (Line Feed), 10 ('\n' C++).
206 8

:
<enter> : (CR)
(LF).
(text mode) C++ :
CR LF LF ('\n'). -
: '\n', CR LF.
-
, , LF CR.

, text ( ifstream t). 4.4
>> ,
. , get().
:
t.get( ch );
t -
ch ( char).
, -
, -
. ;
, : ch == '\n'.
:
C++
'\n' '\n'.
text :
while ( )
{


}
text, . 8.2, -
. , while,
. while
.

8.2
Text
ifstream t;
:
t.open( );
t.get( ch );
while ( !t.eof() )
{
//
while ( !t.eof() && )
{
ch
t.get( ch );
} // while (

if ( !t.eof() ) ;
t.get( ch );
}// while (!t.eof())
t.close();
- Text 207

while :
while ( !t.eof() && ch != '\n' )
{
ch
t.get(ch);
} // while (
t.get(ch) -
while.
while :
t.eof() ( ),
ch == '\n' ( ).
,
. , . 8.2 :
if ( !t.eof() ) ;
:
: , t.eof()
true, t.get(ch) ch char(-1) ( unsigned
char(255)).
, ofstream fstream put().
- s ( ,
ofstream),
s.put( ch );
ch ( char) .
get(), , istream ( cin).
put() ostream ( cout).
: - (
text1.txt) ( numdta.txt).
#include <fstream>
using namespace std;

int main()
{
ifstream s( "text1.txt" );
ofstream t( "numdta.txt" );
char ch;

s.get(ch);
while ( !s.eof() )
{ t.put(ch); s.get(ch); } // while
t.close(); s.close();
} // main

.

8.10
text.
, C.A.R.
Hoare (Hoare & Shepherdson 1985).
The strong connection between the formalization of
mathematical logic and the formalization of computer
programming languages was clearly recognized by Alan
Turing as early as 1947, when, in a talk on 20 February
to the London Mathematical Society, he reported his
208 8

expectation
'that digital computing machines will eventually
stimulate a considerable interest in symbolic logic
and mathematical philosophy. The language in which
one communicates with these machines, i.e. the language
of instruction tables, forms a sort of symbolic logic'.
,
alturing.txt.
1

: , .
. ,
, .
.
:
int main()
{
ifstream t; //
int nRows; //
int nUpCase; //
int nDigits; //
char ch; //

;
;
;
}
:
//
nRows = 0; nUpCase = 0; nDigits = 0;
:
//
cout << " " << nRows << " " << endl;
cout << " " << nUpCase << " "
<< nDigits << " " << endl;
.
text:
//
t.open( "alturing.txt" );
t.get( ch );
while ( !t.eof() )
{
//
while ( !t.eof() && ch == '\n' )
{
ch
t.get( ch );
} // while (

if ( !t.eof() ) t.get( ch );
}// while (!t.eof())
t.close();
ch
.
ch ;

. :
if ( isupper(ch) ) nUpCase = nUpCase + 1;
- Text 209

else if ( isdigit(ch) ) nDigits = nDigits + 1;


isupper isdigit ; , , . 4-3.
#include <cctype>.
, :
, 1:
nRows = nRows + 1;
:
#include <iostream>
#include <fstream>
#include <cctype>

using namespace std;

int main()
{
ifstream t; //
int nRows; //
int nUpCase; //
int nDigits; //
char ch; //
//
nRows = 0; nUpCase = 0; nDigits = 0;
//
t.open( "alturing.txt" );
t.get( ch );
while ( !t.eof() )
{
while ( !t.eof() && ch != '\n' )
{
if ( isupper(ch) ) nUpCase = nUpCase + 1;
else if ( isdigit(ch) ) nDigits = nDigits + 1;
t.get(ch);
}
nRows = nRows + 1;
if ( !t.eof() ) t.get(ch);
} // while (!t.eof())
t.close();
//
cout << " " << nRows << " " << endl;
cout << " " << nUpCase << " "
<< nDigits << " " << endl;
} // main
:
11
8 6

2
-
, :
.

:
ifstream a; //
ofstream b; //
:
a.open( "alturing.txt" );
b.open( "upcaltur.txt" );
. 7-8 ; :
210 8

// upCase -- ch
// , ch
char upCase( char ch )
, :
ch
, :
co = upCase(ch); b.put(co);
:
endl.
:
#include <iostream>
#include <fstream>
#include <cctype>
using namespace std;

char upCase( char ch );

int main()
{
ifstream a; //
ofstream b; //
char ch, co;

a.open( "alturing.txt" );
b.open( "upcaltur.txt" );
a.get( ch );
while ( !a.eof() )
{
while ( !a.eof() && (ch != '\n') )
{ co = upCase(ch); b.put(co); a.get(ch); }
b << endl;
if ( !a.eof() ) a.get( ch );
}
b.close();
a.close();
} // main

// upCase -- ch
// , ch
char upCase( char ch )
{
char fv;

if ( islower(ch) ) fv = char( int(ch)-32 );


else fv = ch;
return fv;
} // upCase
:
, :
C++ toupper upCase.
:
{ t.put(ch); s.get(ch); }
:
{ b.put(toupper(ch)); a.get(ch); }
:
a.open( "alturing.txt" );
b.open( "upcaltur.txt" );
a.get( ch );
while ( !a.eof() )
{ b.put( toupper(ch) ); a.get( ch ); }
- Text 211

b.close(); a.close();

8.11
/ (/) . ..
,
...
C++ . fail()
true / false.
:
ifstream s;
:7
s.open( "text1.txt" );
if ( s.fail() )
cerr << " text1.txt" << endl;
else // ok,
{ // . . .
s.get(ch) s >> x.
:
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
ifstream s;
ofstream t;
char ch;

s.open( "text1.txt" );
if ( s.fail() )
cerr << " text1.txt" << endl;
else // ok,
{
t.open( "numdta.txt" );
if ( t.fail() )
{
s.close();
cerr << " numdta.txt" << endl;
}
else // ok
{
s.get(ch);
while ( !s.fail() && !t.fail() )
{ t.put( ch ); s.get(ch); } // while
if ( !s.eof() )
cerr << " " << endl;
t.close();
s.close();
} // if ( t.fail
} // if ( s.fail
} // main

7 , , : s :
true,
false. , if (s.fail())... if (!s)...
212 8

:
s
.
, t .
, s .
while.
.
.
s.fail() true .
while s t.
s.eof() ! " "
while s.eof().

is_open(). true , false:
// . . .
s.open( "text1.dta" );
if ( !s.is_open() )
cerr << " text1.dta" << endl;
else
{
t.open( "numdta.txt" );
if ( !t.is_open() )
{
s.close();
cerr << " numdta.txt" << endl;
}
else // ok
// . . .

8.12 ()
open()
:
ios_base::in ( ifstream).
ios_base::out ( ofstream).
ios_base::in | ios_base::out
( ofstream).
bool, ios_base::in ios_base
::out (flags) open(). .
(ios_base::)openmode.
( ):
ios_base::binary

. .
ios_base::trunc
(
ofstream).
temp.txt -
. .
;
:
fstream temp( "temp.txt", ios_base::out );
- Text 213

temp.close();
:
fstream temp( "temp.txt", ios_base::in|ios_base::out );
ios_base::trunc: , ,
fstream temp( "temp.txt", ios_base::in|ios_base::out|ios_base::trunc );
ios_base::ate
.
ios_base::app
.
. -
temp.seekp(0) -
. seekp() ofstream fstream.

temp.txt :

:
fstream temp( "temp.txt",
ios_base::in|ios_base::out|ios_base::ate );
:
temp << "" << endl;
temp.seekp( 0 );
temp << "" << endl;
temp.close();
:

:
.
temp.seekp(0),
.
temp :
fstream temp( "temp.txt", ios_base::out|ios_base::app );
:

, temp.seekp(0),
.

:
. 8-1.
214 8

fstream, ifstream, ofstream.



fstream ios_base::in | ios_base::out.
ifstream ios_base::in.
ofstream ios_base::out.
ios_base::out
, .
ios_base::in, ios_base::app ios_base::trunc.

8.13 C
C++
, C.

.
() 6
C:
0: // : 6 C
1: #include <cstdio>
2: using namespace std;
3: int main()
4: {


ios_base
cstdio
binary in out trunk app x
+ "w"
+ + "a"
+ "a"
+ + "w"
+ "r"
+ + "r+"
+ + + "w+"
+ + + "a+"
+ + "a+"
+ + "wb"
+ + + "ab"
+ + "ab"
+ + + "wb"
+ + "rb"
+ + + "r+b"
+ + + + "w+b"
+ + + + "a+b"
+ + + "a+b"
. 8-1 ( C++)
C++ C.
: -
: open C++
ios_base::binary | ios_base::in | ios_base::app
fopen() C "a+b".
- Text 215

5: FILE* a;
6: FILE* b;
7:
8: int n; //
9: int selN; //
10: double x; //
11: double sum; //
12: double selSum; //
13: double avrg; //
14: double selAvrg;
15: //
16: sum = 0; n = 0;
17: selSum = 0; selN = 0;
18: a = fopen( "exp4.dta", "r" );
19: fscanf( a, "%lf", &x );
20: while ( !feof(a) )
21: {
22: n = n + 1; //
23: sum = sum + x; //
24: if ( 0 < x && x <= 10 ) // '
25: {
26: selSum = selSum + x; //
27: selN = selN + 1; //
28: } // if
29: fscanf( a, "%lf", &x );
30: } // while
31: fclose( a );
32: b = fopen( "report.txt", "w" );
33: fprintf( b, " %d \n", n );
34: if ( n > 0 )
35: {
36: avrg = sum / n;
37: fprintf( b, " = %lf <x> = %lf\n",
38: sum, avrg );
39: }
40: fprintf( b, " %d (0,10]\n", selN );
41: if ( selN > 0 )
42: {
43: selAvrg = selSum/selN;
44: fprintf( b, " = %lf <x> = %lf\n",
45: selSum, selAvrg );
46: }
47: fclose( b );
48: } // main
:
. 1 #include <cstdio> #include <fstream>.
printf (1.12)
scanf (2.12).
. 5-6 :
FILE* a;
FILE* b;
.
FILE.
. 18 a = fopen( "exp4.dta", "r" )
a. fopen() :
( "exp4.dta")
( "r").
FILE*.
0 (NULL). 8.1 C
216 8

C++. ("r")
ios_base::in.
. 19 : fscanf( a, "%lf", &x ).
scanf (2.12) , ,
( scanf stdin). . 29
.
. 20, while, feof.
, a, .
. 31 fclose( a ).
. 32 report.txt b = fopen(
"report.txt", "w" ). ("w")
ios_base::out.
. 33, 37, 40, 44 fprintf.
printf .
a, b; , :
FILE* a( fopen("exp4.dta", "r") );
FILE* b( fopen("report.txt", "w") );
()
C:
0: #include <cstdio>
1: using namespace std;
2:
3: int main()
4: {
5: FILE* s;
6: FILE* t;
7: int ch, res( 0 );
8:
9: s = fopen( "text1.dta", "r" );
10: if ( !s )
11: fprintf( stderr,
12: " text1.dta\n" );
13: else
14: {
15: t = fopen( "numdta.txt", "w" );
16: if ( !t )
17: {
18: fclose( s );
19: fprintf( stderr,
20: " numdta.txt\n" );
21: }
22: else // ok
23: {
24: ch = getc( s );
25: while ( ch != EOF && res != EOF )
26: { res = putc( ch, t ); ch = getc( s ); } // while
27: if ( !feof(s) )
28: fprintf( stderr,
29: " \n" );
30: fclose( t );
31: fclose( s );
32: } // if ( t.fail
33: } // if ( s.fail
34: } // main
, . 24, 25, 26:
getc() ( -
) int.
EOF (-1).
- Text 217

/ ,

>> ifstream . 8.3, 2.3, 4.5, 4.6


<< ofstream . 8.4, 1.2, 1.11, 4.4.1
clear ifstream, eof
ofstream
. 8.3.2
close ifstream, . 8.3, 8.4
ofstream
endl ofstream -
. 8.4
eof ifstream . 8.3,
8.3.1, 8.11
fail ifstream, true
ofstream
. 8.11
get ifstream . 8.9,
8.12, 4.5
open ifstream, . 8.1, 8.3, 8.4
ofstream
is_open ifstream, true ,
ofstream
false, 8.11.
peek ifstream get(). 8.9
put ofstream . 8.9
seekg(0) ifstream .
8.6
seekp(0) ofstream . 8.12
. 8-2 .
fstream. ifstream istream ( cin).
ofstream ostream ( cout, cerr, clog).

putc() :
. .
EOF. , res
putc(). EOF res ch (while (ch != EOF
&& res != EOF)) .

8.14
- (text)
.
ifstream, ofstream fstream
. 8-2.
.
( ) -
' 1 .
.
( ) -
eof() fail() .
. 8-5, 8-6 ( 9-13) -
. (, , -
) :
218 8


8-1 text .
, 1.
8-2 -, real.txt, .
:
4.5 5.5 ,
5.0
,
.
8-3 text, 'mydata.txt', 'moredata.txt' -
, , .
text, comb.txt, -
- :
- ,
- ,
,
.
8-4 text, protmet.txt, -
. testmet.txt
-
.
k k
.
k : 0.95 1.05
, 5%.

(k) 5% k,
,
5%
" ".


8-5 ( ) -,
idid.txt, (
) ( ), .
. (5)
1000 11
10 . .
(k) (i)
:
- Text 219

double correctI( int k, double i )


(i) correctI(k, i), k (1,
2, 3 ) i.
idid.txt ,
midid.txt, , (i) correctI(k, i)
.
8-6 ( )
idid. , (16)
.
,
didid.txt, ( 17
). , :
xidid.txt.
8-7 text, misthoi.txt, :
. ,
.
.
.
.
:
800 3500,
0 35,
0 12.
, ,
. ..:
7 . : 35650
7 . : -4
10 . : 51
23 . : 955000
8-8 , dmisthoi.txt,
, :
2% ,
(3) 30
, , (4) 50
.

.


8-9 text.
, . ,
, .
8-10 C++
. .. :
1: #include <iostream>
2: #include <math>
3:
4: int main()
5: {
220 8

6: int a[100], b[25];


. . .
8-11 C++
:
) ,
//.
) .
8-12 , ,
q u : q = u. -
: q = g(u), g , -
2, [-,] :
4
2 u(u ), u 0
g(u) =
4
2 u(u ), 0 u

g C++.
text, irnapr.txt, -
. : -
u, q.
, ,
.

uk qk. uk g(uk) :
g |g(uk) - qk| < |uk - qk|

.

:
( )
g,
N N
|g(uk)-qk| = 1
N g(u k ) q k |uk-qk| = 1
N u k q k N
k 1 k 1
.
, text
girnapr.txt, sirnapr.txt, :
g
girnapr.txt. : uk, qk, g(uk), |g(uk) - qk|.

uk, qk, uk, |uk - qk| sirnapr.txt.
8-13
. ..
if <x, f, x'> is a state transition
8 2, 1, 1, 1, 2, 1, 5, 10 .
- alturing.txt.
) ) .

9

:

.
.
:
.
.
:

,




:
9.1 ........................................................................................................................................ 222
9.2 ............................................................................................................ 226
9.2.1 ............................................................................................................................................226
9.2.2 .......................................................................................................................228
9.2.3 ...............................................................................................................................................229
9.2.4 .............................................................................................................................................230
9.3 - ................................................................................................................................. 231
9.4 ................................................................................................................. 235
9.5 .......................................................................................... 241
9.5.1 .........................................................................................................................242
9.5.2 ............................................................................................................................245
9.5.3 ..........................................................................................................................................247
9.6 - - .................................................................................................... 249
9.6.1 binSearch ..................................................................................................................254
9.7 ........................................................................................................................................... 254
................................................................................................................................................................... 255
.............................................................................................................................................................................255
B .............................................................................................................................................................................255
.............................................................................................................................................................................256

:
100 x1, x2,
..., x100

221
222 9

) <x>,
x x
) : e x
x xk
. yk = e x .
, 100
!
<x>, .
; .
100
.
.
, , 100 : x1, x2, ...,x100
double 100 :
cin >> x1; cin >> x2; ... ; cin >> x100;
.
C++, ,
.
.

9.1
(array, matrix) . C++
, .
. - .
, , , ..
pinA, pinB flNm :
int pinA [ 20 ];
double pinB [ 50 ];
char flNm [ 120 ];
pinA 20
int,
pinB 50 -
double flNm 120
char.
, .. pinA, -
20 20 . .
9-1 .
(elements) (components)
-
(index).
n , -
0 n - 1.
, -
:
pinA[1], pinA[5], pinA[15]
pinB[2], pinB[10], pinB[49]
, ,
pinA.
, pinB. pinA[k] -
223

. . .

pinA[0] pinA[1] pinA[2] pinA[19]


pinA

. 9-1 .

(k+1)- pinA, k = 0, 1,... 19.


pinB[k] (k+1)- pinB, k = 0, 1,... 49.
:
, , "[", , "]"
, (component type),
, .. int, double, char, bool, .
.
,
, -
. 0.
.
:
const int N( 50 ), N1( 63 ), N2( 114 );

typedef int PinAk[ N+1 ];


enum DecDigit { zero = 48, one, two, three, four, five, six,
seven, eight, nine };

PinAk p, q, r;
int l[ N+1 ], m[ N2-N1+1 ];
bool signal[ (N1+1)/4 ];
ifstream keimena[ 4 ];
DecDigit bv[ N/2+1 ];
PinAk mat[ 11 ];
, PinAk ,
p, q, r , 51 (= N + 1) int,
0 50, .. p[0], p[1], , p[50].
DecDigit . 4 -
bv 26 (= N/2 + 1) DecDigit.
l 51 int PinAk l.
m 52 int.
keimena ifstream.
, , mat 11 -
PinAk . -
.
.
..:
int monthLength[ 12 ] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
(
). :
int monthLength[] = { 31,28,31,30,31,30,31,31,30,31,30,31 };

. ..
int monthLength[ 12 ] = { 31,28,31,30,31,30,31,31 };
:
224 9

int monthLength[ 12 ] = { 31,28,31,30,31,30,31,31, 0, 0, 0, 0 };


, 0
0 :
double x[ 100 ] = { 0.0 };
, . ;
, :

.
, .. l[17] int.
:
l[17] = 3215;
:
cin >> l[17];
l[17] :
x = l[17] / 5 + 100;
:
cout << l[17] << endl;
signal[11] bool true false, ..:
signal[11] = ( l[17] >= x );
if ( signal[11] && x > 1000 ) { ...
, .
, , .
. :
int metr[ 26 ];
:
metr[0] = -16;
, :
metr[27] = 24; metr[-5] = 33;
, , . , c == 22,
:
metr[c+1] = c - 17;
, c == 25, : metr[26] !
, , ,
. , , (
).
n
( 0 n - 1).
,
, , . -
, .
, -
.
C++ . -
. :
int a[5], b[5];
a b.
: b = a :
225

for ( k = 0; k <= 4; k = k+1 ) b[k] = a[k];


,
.

. -
x . -
, x ,
.
x :
double x[ N ];
() for
x. <x>, 100 x
:
// : 1+
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
int main()
{
const int N( 100 );//
double x[ N ]; //
double sum; // () .
// .
double avrg; // x (<x>)
int m;
double y;

sum = 0;
for ( m = 0; m <= N-1; m = m+1 )
{
cout << " : "; cin >> x[m];
// sum
sum = sum + x[m];
} // for
avrg = sum / N;
cout.setf( ios::fixed,ios::floatfield ); cout.precision( 3 );
cout << " = " << sum
<< " <x> = " << avrg << endl;
for ( m = 0; m <= N-1; m = m+1 )
{
y = exp( (avrg - x[m])/avrg );
cout << " x[";
cout.width(3); cout << m << "] = ";
cout.width(6); cout << x[m] << " y[";
cout.width(3); cout << m << "] = " ;
cout.width(6); cout << y << endl;
} // for
} // main
for, m .
:
) for
) ( : 0 .. -1).
.
-
/ .
226 9

, yk =
xxk
e x y . x , y...
, ! , ,
yk. . y -
double. ,
, :
= 1772.217 <x> = 17.722
x[ 0] = -2.217 y[ 0] = 3.081
x[ 1] = 58.900 y[ 1] = 0.098
x[ 2] = 35.850 y[ 2] = 0.360
x[ 3] = -0.879 y[ 3] = 2.857
. . .
100 double .
:
! , . 100
. , , ;
; !
!

:
, , -
.

9.2
. -
:
const int N(...);
double x[N];
, double, int, char .
: ,
unsigned int. ,
, int. ; ,
,
=.

9.2.1

.
:
for ( m = 0; m <= N-1; m = m+1 )
{
cout << " " << m << " : ";
cin >> x[m];
} // for
, -
. :
0 : 5.5
1 : 6.3
2 : 4
227

. . .
-
(9999). ;
m = 0; cin >> x[m];
while ( x[m] != 9999 && m < N-1 )
{
m = m + 1; cin >> x[m];
} // while
, m 0 1 m < N-1.
N-1. while
: x[m] == 9999 || m >= N-1.
x[m] == 9999 x[m] ,
. m x[0] .. x[m-1].
m >= N1 m == N1 ( m
0 1 ).
N (= m + 1) x[0] .. x[N-1].
, count,
:
if ( x[m] == 9999 ) count = m;
else count = m + 1;

:
cout << " : "; cin >> m;
cout << " " << m << " : "; cin >> x[m];
:
0
-1. m
x[m].
. -
for.
(.. -1 m).
cout << " (0.." << (N-1)
<< ") (-1 ): ";
cin >> m;
while ( m != -1 )
{
if ( 0<= m && m <= N-1 )
{
cout << " " << m << " : ";
cin >> x[m];
}
else
cout << "*** ***" << endl;
cout << " (0.." << (N-1)
<< ") (-1 ): ";
cin >> m;
} // while
:
(0..8) (-1 ): 7
7 : -15.7
(0..8) (-1 ): 3
3 : -3
(0..8) (-1 ): 11
*** ***
(0..8) (-1 ): 1
1 : 6.3
228 9

. . .
:
7
7 ( -
0;!).
2 ,
.
, ,
. : 1 :
for ( m = 0; m <= N-1; m = m+1 ) cin >> x[m];
.. = 5 :
5.5 6.3 4.0 -3 5.1<Enter>

9.2.2
. :
.
.
= 9, :
ifstream t( "text1.dta" );
text1.dta :
-7 -15 8
14 33
-8 16 114
375
N , :
for ( m = 0; m <= N-1; m = m+1 )
{
t >> x[m];
} // for
, , -
( !t.eof()):
m = 0; t >> x[m];
while ( !t.eof() && m < N-1 )
{
m = m + 1; t >> x[m];
} // while
if ( t.eof() ) count = m;
else count = m+1;
N = 9 arrval.txt :
7 -15.7
3 -3
8 3.75
2 4.0
6 0
11 6.3
4 5.1
5 -13
0 5.5
,
. , 2 , :
ifstream t( "arrval.txt" );
double y;
int rNum;
229

rNum = 0;
t >> m;
while ( !t.eof() )
{
rNum = rNum + 1;
if ( 0<= m && m <= N-1 )
t >> x[m];
else
{
cout << " " << rNum << endl;
t >> y;
}
t >> m;
} // while
t.close();
x[1].
:
6
11.

9.2.3
. x
. :
for ( m = 0; m <= N-1; m = m+1 ) cout << x[m] << " ";
cout << endl;
:
5.5 6.3 4 -3 5.1 -13 0 -15.7 3.75
<< " " .
:
5.56.34-35.1-130-15.73.75
t (ofstream) - :
for ( m = 0; m <= N-1; m = m+1 ) t << x[m] << " ";
t << endl;
.
endl
:
for ( m = 0; m <= N-1; m = m+1 ) cout << x[m] << endl;
:
for ( m = 0; m <= N-1; m = m+1 ) t << x[m] << endl;
x . 9.2.
:
const int N( 50 );
int z[N];
z . 9-2. ;
10 , ( 1 )
0 9. :
for ( r = 0; r <= 9; r =r + 1 )
{
r
} // for (r = ...
r.
0 1 ; :
230 9

0 35 10 9 20 872 30 232 40 347


1 18 11 34 21 0 31 667 41 61
2 15 12 21 22 23 32 139 42 753
3 80 13 57 23 -34 33 -45 43 73
4 10 14 239 24 -32 34 -9 44 6
5 40 15 909 25 56 35 -89 45 -37
6 23 16 213 26 787 36 34 46 43
7 789 17 576 27 146 37 576 47 -99
8 563 18 903 28 589 38 122 48 344
9 1 19 239 29 568 39 99 49 572
. 9-2 z. -
. .. 0 35 z[0] 35.

0, z[0], 10, z[10], 20, z[20], 30, z[30], 40, z[40] ( 0)


1, z[1], 11, z[11], 21, z[21], 31, z[31], 41, z[41] ( 1)
r :
cout << r << z[r] << (r+10) << z[r+10] << (r+20) << z[r+20]
<< (r+30) << z[r+30] << (r+40) << z[r+40] << endl;
( .)
:
for ( r = 0; r <= 9; r = r + 1 )
{
cout << r << z[r] << (r+10) << z[r+10] << (r+20) << z[r+20]
<< (r+30) << z[r+30] << (r+40) << z[r+40] << endl;
} // for (r =
: for;
1:
for ( c = 0; c <= 40; c = c + 10 )
cout << (r + c) << z[r+c];

:
for (r = 0; r <= 9; r = r + 1)
{
for (c = 0; c <= 40; c = c + 10)
{
cout.width(7); cout << (r + c);
cout.width(5); cout << z[r+c];
} // for (c =...
cout << endl;
} // for (r =...

9.2.4
:
sum = 0;
for ( m = 0; m <= N-1; m = m + 1 )
sum = sum + x[m];//

1 :
for (r = 0; r <= 9; r = r + 1)
{
for (c = 0; c <= 4; c = c + 1)
{
cout.width(7); cout << (r + c*10);
cout.width(5); cout << z[r+c*10];
} // for (c =...
cout << endl;
} // for (r =...
c (0 .. 4).
231

product = 1;
for ( m = 0; m <= N-1; m = m + 1 )
product = product * x[m];//
()
() : ()
0:
maxNdx = 0; xMax = x[maxNdx];
for ( m = 1; m <= N-1; m = m + 1 )
{
if ( x[m] > xMax )
{ maxNdx = m; xMax = x[m]; }
} // for (m
xMax maxNdx
. :
(maxNdx). , ,
:
maxNdx = 0;
for ( m = 1; m <= N-1; m = m + 1 )
{
if ( x[m] > x[maxNdx] ) maxNdx = m;
} // for (m
xMax = x[maxNdx];
:
minNdx = 0;
for ( m = 1; m <= N-1; m = m + 1 )
{
if ( x[m] < x[minNdx] ) minNdx = m;
} // for (m
xmin = x[minNdx];

9.3 -
- -
.
. :
double vectorSum( double x[], int n )
{
int m;
double sum( 0 );

for ( m = 0; m <= n-1; m = m + 1 )


sum = sum + x[m];
return sum;
} // vectorSum

double.
,
double. x
. n
.
-
.
int maxNdx( int x[], int n )
{
int m;
232 9

int mxp( 0 );

for ( m = 1; m <= n-1; m = m + 1 )


{
if (x[m] > x[mxp]) mxp = m;
} // for (m ...
return mxp;
} // maxNdx
:
const int N( 9 ), Nd2( N/2 );

double x[N] = { 5.5, 6.3, 4, -3, 5.1, -13, 0, -15.7, 3.75 },


u[Nd2] = { 5.5, 4, 5.1, 0 };
int ix[N] = { 5, 6, 4, -3, 1, -13, 0, -15, 3 },
iu[Nd2] = { 5, 4, 1, 0 };
:
cout << " x: " << vectorSum( x, N ) << endl;
cout << " u: " << vectorSum( u, Nd2 ) << endl;

cout << " max(ix): " << ix[maxNdx(ix, N)]


<< " : " << maxNdx( ix, N ) << endl;
cout << " max(iu): " << iu[maxNdx(iu, Nd2)]
<< " : " << maxNdx( iu, Nd2 ) << endl;
:
x: -7.05
u: 14.6
max(ix): 6 : 1
max(iu): 5 : 0
:

x vectorSum(x, N)
u vectorSum(u, Nd2).
:
maxNdx(ix, N) ix
ix[maxNdx(ix, N)].
iu : maxNdx(iu, Nd2) :
iu[maxNdx(iu, Nd2)].
, , vectorSum double. -
ix . -
, maxNdx int .
.
maxNdx int unsigned int;
, .

x. -
vectorSum :
q = vectorSum( x, 5 );
;
vectorSum .
:
, -
. / /
. ..:
double vectorSum( double x[], int n, int from, int upto )
233

{
int m;
double sum( 0 );

for ( m = from; m <= upto; m = m + 1 )


sum = sum + x[m];
return sum;
} // vectorSum
, :
0 from upto n1
; exit().
n == 0 upto <
from 0, :
if ( 0 <= from && from <= upto && upto < n )
{
for ( m = from; m <= upto; m = m + 1 ) sum = sum + x[m];
}
:
int maxNdx( int x[], int n, int from, int upto )
{
int m;
int mxp;

if ( from < 0 || upto < from || n <= upto )


mxp = -1;
else // 0 <= from <= upto <= n1
{
mxp = from;
for ( m = from+1; m <= upto; m = m + 1 )
{
if (x[m] > x[mxp]) mxp = m;
} // for (m ...
}
return mxp;
} // maxNdx
exit

(1) .2
:
-
. , !
- -
.

vectorSum :
double vectorSum( double x[], int n, int from, int upto )
{
int m;
double sum( 0 );

for ( m = from; m <= upto; m = m + 1 ) sum = sum + x[m];

for ( m = 0; m <= n-1; m = m + 1 ) x[m] = 0;

return sum;

2 int
unsigned int.
234 9

} // vectorSum
, , 0.
:
cout << " x: ";
for (m = 0; m <= N-1; m = m + 1) cout << x[m] << " ";
cout << endl;

cout << " x: " << vectorSum( x, N, 0, N-1 ) << endl;

cout << " x: ";


for (m = 0; m <= N-1; m = m + 1) cout << x[m] << " ";
cout << endl;
:
x: 5.5 6.3 4 -3 5.1 -13 0 -15.7 3.75
x: -7.05
x: 0 0 0 0 0 0 0 0 0

C++
. const (). -
:
double vectorSum( const double x[], int n, int from, int upto )
{ . . . }
int maxNdx( const int x[], int n, int from, int upto )
{ . . . }

x : Cannot modify a const object ( -
const).
:
-
. -
:
double rVectorSum( const double x[], int n, int from, int upto)
{
double sum( 0 );

if ( 0 <= from && from <= upto && upto < n )


{
sum = x[upto] + rVectorSum( x, n, from, upto-1 );
}
return sum;
} // rVectorSum
1 upto
upto < from sum 0 .
int rMaxNdx( const int x[], int n, int from, int upto )
{
int mxp;

if ( from < 0 || upto < from || n <= upto )


mxp = -1;
else // 0 <= from <= upto <= n-1
{
if ( from == upto )
mxp = from;
else
{
mxp = rMaxNdx( x, n, from+1, upto );
if ( x[from] > x[mxp]) mxp = from;
}
}
235

return mxp;
} // rMaxNdx
from.

9.4
, -
. -
.
, .
.

,
! :
text.
, .
.
1 - ( Horner)
, ,
:
m
p(x) = a0 + a1x + a2x2 + + amxm = ak x k
k 0

(ak, k = 0..m) x.
, x
p(x).

double m +1 (0 .. m). :
double p1( const double a[], int m, double x )
,
:
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

double p1( const double a[], int m, double x );

int main()
{
const int N( 20 );

double a[N]; //
int b; //
double x, y;
int k, pa;
ifstream syntFl; // Text

syntFl.open( "syntFl.txt" );
syntFl >> b;
if ( syntFl.eof() )
{
syntFl.close();
cout << " " << endl;
}
else if ( b < 0 || b > N-1 )
236 9

{
syntFl.close();
cout << " " << endl;
}
else // b+1
{ // a[0]..a[b]
k = 0; syntFl >> a[k];
while ( !syntFl.eof() && k <= b-1 )
{
k = k + 1; syntFl >> a[k];
} // while
if ( syntFl.eof() ) pa = k;
else pa = k + 1;
syntFl.close();
// pa
if ( pa < b + 1 )
cout << " " << pa << " " << endl;
else //
{
cout << " YNTEETE TOY OYNYMOY :" << endl;
for ( k = 0; k <= b; k = k+1 ) cout << a[k] << " ";
cout << endl;

cout << "E x = "; cin >> x;


while ( x != 0 )
{
cout << " AOTEEMA: p(" << x << ")= "
<< p1( a, b, x ) << endl;
cout << "E x = "; cin >> x;
} // while
cout << " AOTEEMA: p(" << x << ")= "
<< p1( a, b, x ) << endl;
} // if (pa ...
} // !syntFl.eof ...
} // main
syntfl.txt text, , ,
.
a 9.1.1
9.1.2. ,
: 0 b N 1.
, 10 ,
11 ( 11 ):
p(x) = 10 + 9.5x + 7.2x2 + 6.8x3 6.1x4 + 5.3x5 4.6x6 + 3.5x7 + 2.7x8 x9 + 0.8x10
:
10
-10 9.5 7.2 6.8 -6.1 5.3 -4.6 3.5 2.7 -1 0.8
while 0 x.
p(0) .
, ,
. :
px = a[0];
for ( k = 1; k <= m; k = k+1 )
{
xk
px = px + a[k]*xk
}
xk; , : pow(x, k). ,
:
double p1( const double a[], int m, double x )
{
237

double px;
int k;

px = a[0];
for ( k = 1; k <= m; k = k+1 )
px = px + a[k]*pow(x, k);
return px;
} // p1
:
YNTEETE TOY OYNYMOY :
-10 9.5 7.2 6.8 -6.1 5.3 -4.6 3.5 2.7 -1 0.8
E x = 0.3562
AOTEEMA: p(0.3562)= -5.46928
E x = -0.45
AOTEEMA: p(-0.45)= -13.8303
E x = 0
AOTEEMA: p(0)= -10
. :
m (pow),
m a[k] * ...
m px + a[k] * ...
for.
; : xk = xk1x -
xk . . p2()
:
double p2( const double a[], int m, double x )
{
double px, xPow;
int k;

px = a[0]; xPow = 1;
for ( k = 1; k <= m; k = k+1 ) // xPow = x^(k-1)
{
xPow = xPow * x; // xPow = x^k
px = px + a[k]*xPow;
}
return px;
} // p2
xk xk1 -
.
p2() , p1 p2.
. :
2m (xPow * x a[k] * xPow),
m (px + a[k] ...),
.
! ; -
, :
p(x) = ax3 + bx2 + cx + d
p2(), 6 3
.
p(x) :
p(x) = ((ax + b)x + c)x + d
:
p(x) a;
p(x) p(x)x + b;
238 9

p(x) p(x)x + c;
p(x) p(x)x + d;
: 3 3 . ! -
, Horner -
(nested multiplication) ph:
// ph -- , m,
// Horner.
double ph( const double a[], int m, double x )
{
double px;
int k;

px = a[m];
for ( k = m-1; k >= 0; k = k-1 ) px = px*x + a[k];
return px;
} // ph
, :
m (px*x),
m (px*x + a[k]),
; ,
. , -
-
:
, .
double,
, double .
Horner .
500
: 210:71:42. , -
, 3:1. -
, 7:4.

; :
!
; , .
; p1()
; !
: p1() -
, ph() 3. p2(),
.
, ,
, ,
( : -
). ,
, -
.

. ,
ph()!4

3 , , .
4 .
239

2 -
xk, k = 0,... N - 1, :
N 1
x = 1
N xk
k 0

: = Var(x) , :
N 1
Var(x) = 1
N xk x 2 (A)
k 0
:
N 1
Var(x) = 1
N xk2 - x2 (B)
k 0
( ) text
stat.dta xk double x .
() ,
().
. ;
1 : ,
vectorAvrg, , stdDev.
vectorSum . :
double vectorAvrg( const double x[], int n, int from, int upto)
{
int m;
double fv( 0 );

if ( 0 <= from && from <= upto && upto < n )


{
for ( m = from; m <= upto; m = m + 1 ) fv = fv + x[m];
fv = fv/(upto-from+1);
}
return fv;
} // vectorAvrg
:
double stdDev( const double x[], int n, int from, int upto )
{
int m;
double fv( 0 ), vAvg;

if ( 0 <= from && from <= upto && upto < n )


{
vAvg = vectorAvrg( x, n, from, upto );
for ( m = from; m <= upto; m = m + 1 )
fv = fv + pow( x[m]-vAvg, 2 );
fv = sqrt( fv/(upto-from+1) );
}
return fv;
} // stdDev
N 1

1
N xk x 2 :
k 0

for ( m = 0; m <= n-1; m = m + 1 )


sum = sum + pow( x[m]vectorAvrg(x, n, from, upto), 2 );
, n vectorAvrg .
, , vAvg. , -
.
main :
#include <iostream>
240 9

#include <fstream>
#include <cmath>
using namespace std;

double vectorAvrg(const double x[], int n, int from, int upto);


double stdDev( const double x[], int n, int from, int upto );

int main()
{
const int Nmax = 100;

double x[Nmax], y;
int n, k;
ifstream t("stat.dta");

k = 0; t >> x[k];
while ( !t.eof() && k <= Nmax-2 )
{ k = k + 1; t >> x[k]; } // while
if ( t.eof() ) n = k;
else n = k + 1;
t.close();

cout << " <x> = " << vectorAvrg( x, Nmax, 0, n-1 ) << endl;
cout << " = " << stdDev( x, Nmax, 0, n-1 ) << endl;
} // main
2 : stdDev
N 1 . .
N 1 N 1
xk xk2 .
k 0 k 0
!
.
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;

int main()
{
double x, vAvg, sigma, sx, sx2;
int n, k;
ifstream t( "stat.dta" );

sx = 0; sx2 = 0;
k = 0; t >> x;
while ( !t.eof() )
{
k = k + 1;
sx = sx + x; sx2 = sx2 + x*x;
t >> x;
} // while
n = k;
t.close();
cout << " " << n << " " << endl;
if ( n > 0 )
{
vAvg = sx/n;
sigma = sqrt( sx2/n - vAvg*vAvg );
cout << " <x> = " << vAvg << endl;
cout << " = " << sigma << endl;
} // if
} // main
, .
241

k v[k] k v[k] k v[k] k v[k] k v[k]


1 35 11 9 21 872 31 232 41 347
2 18 12 34 22 0 32 667 42 61
3 15 13 21 23 23 33 139 43 753
4 80 14 57 24 -34 34 -45 44 73
5 10 15 239 25 -32 35 -9 45 6
6 40 16 909 26 56 36 -89 46 -37
7 23 17 213 27 787 37 34 47 43
8 789 18 576 28 146 38 576 48 -99
9 563 19 903 29 589 39 122 49 344
10 1 20 239 30 568 40 99 50 572
. 9-3
. . 9-2 v[0] == INT_MIN
v[51] == INT_MAX.

2 ( -
).

.

9.5

:
(searching) .
(sorting), , -
.
(merging) .
.

()
(!)5.
.
, .
50 int.
:
const int N( 50 );

int v[N+2];
v[1] v[N].
v[0] - (INT_MIN) v[N+1] + (INT_MAX).
(. 9-3) text, pin.txt
, , :
ifstream a;
:
a.open( "pin.txt" );
for ( k = 1; k <= N; k = k+1 ) //
a >> v[k];
a.close();
v[0] = INT_MIN; v[N+1] = INT_MAX; //

5 ;
. ' .
242 9

. 9-3
9.2.3 for :
for ( c = 0; c <= 4; c = c+1 ) cout << " k v[k]";
cout << endl;
for ( r = 1; r <= 10; r = r+1 ) // r-
{
for ( c = 0; c <= 40; c = c+10 )
{
cout.width(7); cout << (r + c);
cout.width(5); cout << v[r+c];
} // for ( c = ...
cout << endl; // ...
} // for ( r = ...

9.5.1
:
T v[N] x ( T). v
x ;
:
,
.
x ( ) v;
int .
:
int linSearch( int v[], int n, int from, int upto, int x )
v[from], v[from+1],..., v[upto] x. ,
, -
1. :
thesi = linSearch( v, N+2, n1, n2, x );
0 < n1 n2 < N + 2 :
(n1 linSearch(v, N+2, n1, n2, x) n2 && v[linSearch(v, N+2, n1, n2, x)] == x)
|| (linSearch(v, N+2, n1, n2, x) == -1 && (j: n1..n2 v[j] != x))
:
(from)
( ) ( ) :
{
:
(from) k = from
k <= upto
v[k] != x
k = k+1
:
k = from;
while ( k < upto && v[k] != x ) k = k+1;
: while :
!(k < upto) k >= upto ( k == upto
k 1), ,
!(v[k] != x) v[k] == x,
v[k].
, while:
if ( v[k] == x ) fv = k;
243

else fv = -1;
linSearch:
// linSearch -- v[from],... v[upto]
// x.
//
//
// -1
int linSearch( const int v[], int n, int from, int upto, int x)
{
int k, fv( -1 );

if ( 0 <= from && from <= upto && upto < n )


{
k = from;
while ( k < upto && v[k] != x ) k = k+1;
if ( v[k] == x ) fv = k;
else fv = -1;
// (from <= fv <= upto && v[fv] == x) ||
// (fv == -1 && ( j:from..upto " v[j] != x))
}
return fv;
} // linSearch
(linear search).
:
#include <iostream>
#include <fstream>
#include <climits>
#include <cstdlib>
using namespace std;

int linSearch( const int v[], int n, int from, int upto, int x );

int main()
{
const int N( 50 );

int v[N+2]; //
int x; //
int ndx; // ,
int k;
ifstream a;

//
//

cout << "E THN TIMH X (9999 ): "; cin >> x;


while ( x != 9999 )
{
ndx = linSearch( v, N+2, 1, N, x );
if ( ndx > 0 )
cout << " : " << ndx << endl;
else
cout << " " << endl;
cout << "E THN TIMH X (9999 ): "; cin >> x;
} // while
} // main
:
E THN TIMH X (9999 ): 23
: 7
E THN TIMH X (9999 ): -121

E THN TIMH X (9999 ): 6
: 45
E THN TIMH X (9999 ): 9999
244 9


1. x = 23 7. , .
9-3, 23 23.
. (multiset,
bag). B x B;
x B; (. 9-10)
2. , (exit(1))
.
(from > upto) :
. , if fv -1
.
linSearch(); while. -
2 , 1 &&, 1 1 (k = k+1).
-
( upto-from+1).

. . -:
; v[k] != x. -
! k < upto -
; . x
; !
, ; , , x
v[upto+1]. while (v[k] != x) k = k+1 ,
k: k upto x , , k > upto
x v[upto+1]. , ;
! ; - .
:
save = v[upto+1]; // v[upto+1]
v[upto+1] = x; //
k = from;
while ( v[k] != x ) k = k+1;
if ( k <= upto ) fv = k;
else fv = -1;
v[upto+1] = save; //
(x) v[upto + 1]
(save)
. upto N -
( +).
, , : Cannot modify a const object
in function linSearch. ; const -
. . -
: const!
int linSearch( int v[], int n, int from, int upto, int x )
{
int save;
int k, fv( -1 );

if ( 0 <= from && from <= upto && upto < n )


{
save = v[upto+1]; // v[upto+1]
v[upto+1] = x; //
k = from;
while ( v[k] != x ) k = k+1;
if ( k <= upto ) fv = k;
else fv = -1;
245

9 34 21 57 239 909 213 576

9 34 21 57 239 576 213 909

9 34 21 57 239 213 576 909

# 9 34 21 57 213 239 576 909

# 9 34 21 57 213 239 576 909

9 34 21 57 213 239 576 909

# 9 21 34 57 213 239 576 909

9 21 34 57 213 239 576 909

9 21 34 57 213 239 576 909

. 9-4 ' . -
. ,
[ . -
( #) -
, , (mxp == k).
v[upto+1] = save; //
// (from <= fv <= upto && v[fv] == x) ||
// (fv == -1 && ( j:from..upto " v[j] != x))
}
return fv;
} // linSearch

9.5.2
6 , .
( v[0] v[N+1] - +):
j: 1..n v[j] v[j+1]
:
v[1]...v[N]
v[N]
v[1]...v[N-1]
v[N-1]
:
v[1]...v[2]
v[2]
:
for (k = N; k >= 2; k = k-1)
{
v[1]...v[k]
v[k]
}
! "":
v[1]...v[k]
. maxNdx 9.3 -
:

6 ,
. ,
!
246 9

mxp = maxNdx( v, N+2, 1, k );


"":
v[k]
:
sv = v[mxp]; v[mxp] = v[k]; v[k] = sv;
' (straight selection sort).
. 9-4 8 .
:
v pin.txt,
,

pinsrt.txt.
, maxNdx .
#include <iostream>
#include <fstream>
#include <climits>
using namespace std;

int maxNdx( int x[], int n, int from, int upto );

int main()
{
const int N( 50 );

int v[N+2], sv;


int k, mxp, r, c;
fstream a;

a.open( "pin.txt", ios_base::in );


//

//
for ( k = N; k >= 2; k = k-1 )
{
mxp = maxNdx( v, N+2, 1, k );
sv = v[mxp]; v[mxp] = v[k]; v[k] = sv;
} // for

//
//
a.open( "pinsrt.txt", ios_base::out );
for ( k = 1; k <= N; k = k+1 ) a << v[k] << endl;
a.close();
} // main
:
TOIXEIA TOY INAKA v
k v[k] k v[k] k v[k] k v[k] k v[k]
1 -99 11 9 21 40 31 146 41 576
2 -89 12 10 22 43 32 213 42 576
3 -45 13 15 23 56 33 232 43 589
4 -37 14 18 24 57 34 239 44 667
5 -34 15 21 25 61 35 239 45 753
6 -32 16 23 26 73 36 344 46 787
7 -9 17 23 27 80 37 347 47 789
8 0 18 34 28 99 38 563 48 872
9 1 19 34 29 122 39 568 49 903
10 6 20 35 30 139 40 572 50 909
. for, -1
maxNdx v. maxNdx (from = 1, upto
247
v z w

-99 -99 -91

-89 -91 -88

-45 -89 -57

-37 -88 -54

-34 -57 -42

-32 -54 -38

-9 -45 -21

. 9-5 . v
, -
. w .

= k), for , k, , k - 1 v[m] >


v[mxp]. :
(-1) + (-2) + . . . + 2 + 1 = (-1) = N2 - N
. , N N2.
N2.
, . ..
mxp = m;
v[m] > v[mxp] ( N-1
).
N
.

9.5.3
v w, ,
int, V W .
. z, N ( V +
W) , z
.
( ) :
NV z v, NW
w z -
. ,
. (NV+NW)2,
v w.
.
:
v
w
z
while ( v w )
{
if ( v < w )
{
z v
A v
}
else // if v >= w
{
248 9

z w
A w
}
z
}
. 9-5, .
: while
v w. z
, . ; !
. -
:
z
, ,
v, pinsrt.txt, -
, . , ,
(20) w pinw.dta, .
z.
dv, dw, dz v, w, z . dv,
dw v w , dz
z . 1:
dv = 1; dw = 1; dz = 1;
while :
while ( dv <= NV && dw <= NW )
{
if (v[dv] < w[dw]) { z[dz] = v[dv]; dv = dv + 1; }
else { z[dz] = w[dw]; dw = dw + 1; }
dz = dz + 1;
} // while
, , v (dv > NV)
w, z :
while ( dw <= NW )
{ z[dz] = w[dw]; dw = dw + 1; dz = dz + 1; }
dz dw while
. z
v, w.
.
#include <fstream>
using namespace std;

int main()
{
const int N( 50 ), NV( N ), NW( 20 ), NZ( 70 );

int v[N+2], w[NW+2], z[NZ+2];


int k;
int dv, dw, dz;
fstream a;

a.open( "pinsrt.txt", ios_base::in );


for (k = 1; k <= NV; k = k+1) a >> v[k];
a.close();
a.open( "pinw.txt", ios_base::in);
for (k = 1; k <= NW; k = k+1) a >> w[k];
a.close();

//
dv = 1; dw = 1; dz = 1;
249

while ( dv <= NV && dw <= NW )


{
if (v[dv] < w[dw]) { z[dz] = v[dv]; dv = dv + 1; }
else { z[dz] = w[dw]; dw = dw + 1; }
dz = dz + 1;
} // while
if ( dv > NV )
while ( dw <= NW )
{ z[dz] = w[dw]; dw = dw + 1; dz = dz + 1; }
else
while ( dv <= NV )
{ z[dz] = v[dv]; dv = dv + 1; dz = dz + 1; }

a.open( "pinz.txt", ios_base::out );


for ( k = 1; k <= NZ; k = k+1 ) a << z[k] << endl;
a.close();
} // main

V+W.

9.6 - -
.
. : ..
, v, int,
x ( int). v[from],
v[from+1], ..., v[upto] x.
.
.
: -
. ,
.
, . -
. ,
. ,
!
, , v[from] x v[upto]. v[k] x:
v[k] == x .
, v[k] > x,
v[k], x.
k = from;
while ( v[k] < x ) // I: j:from-1..k-1 v[j] < x
k = k+1;
// (j:0..k-1 v[j] < x) && (x v[k])
if ( v[k] == x ) fv = k;
else fv = -1;
while x > v[upto]
(+) v[upto+1]. (-) v[from-1]
m == from, .
, :
k = upto;
while ( x < v[k] ) // I: j:k+1..upto+1 x < v[j]
k = k-1;
// (v[k] x) && (j:k+1..upto+1 x < v[j])
if ( v[k] == x ) fv = k;
else fv = -1;
250 9

, (-) v[from-1] -
while x < v[from]. ,
(+) v[upto+1],
m == upto.
.
; . ,
,
. , . -
... .
,
middle = (from+upto)/2. v[middle] == x, , -
. v[middle] < x , ,
v[from],... v[middle], < x. : v[middle+1],...
v[upto]. v[middle] > x
v[from],... v[middle-1]. ; !
.
. 9-4, 8 -
100.
, from = 1; upto = 8; middle = 4: v[middle] = 57.
100 57. ,
from = middle + 1; (= 5). middle = 6. -
: v[middle] = 239. 100 , 239. , -
, upto = middle 1; (= 5).
. : middle = 5, v[middle] = 213. 100,
. upto = middle 1; (= 4).
: (upto = 4) -
(from = 5). . -
100 .
:
x (v[middle] == x)
(from > upto).
middle = (from + upto) / 2;
while ( from <= upto && v[middle] != x )
{
if (v[middle] < x) from = middle + 1;
else if (v[middle] > x) upto = middle - 1;
middle = (from + upto) / 2;
} // while
,
:
if (v[middle] == x) x Meso
(binary search).
,
x .
from upto (
). , ,
(from = 1 upto = N).
1 (upto < from).
(, ). l , -
:
/ 2l .
251
1 2 3 4 5 6 7 8

9 21 34 57 213 239 576 909


from middle upto

9 21 34 57 213 239 576 909


from middle upto

9 21 34 57 213 239 576 909


from
upto
middle

9 21 34 57 213 239 576 909


upto from
. 9-6 100
.

1 2 l , :
l > log2
,
( ) . ; ..
= 1024, 10 (log21024 = 10) while,
1024!
binSearch(), , -
linSearch() : !
:
, ,
v[1] v[last], last < N
x .
binSearch() k x -
while v[k-1] < x v[k].
binSearch:
ndx = binSearch( v, last, x );
if ( v[ndx] == x )
cout << " : " << ndx << endl;
else
{
for ( k = last+1; k >= ndx; --k ) v[k+1] = v[k];
v[ndx] = x;
last = last + 1;
cout << " : " << ndx << endl;
}
ndx
x
if ( v[ndx] == x )
: for
.
binSearch:
// binSearch -- v[1],...v[last]
// fv :
// v[fv-1] < x <= v[fv]
// fv.
// v '
//
// v[0] == -inf, v[last+1] == +inf
unsigned int binSearch( const int v[], int last, int x )
{
unsigned int l( 1 ), r( last+1 );
unsigned int middle;
252 9

while ( l < r ) // I: (k:[0..l) v[k] < x) &&


{ // (k:[r..last+1) v[k] >= x)
middle = (l + r) / 2;
if ( v[middle] < x ) l = middle + 1;
else r = middle;
} // while
// v[l-1] < x <= v[l]
return l;
} // binSearch
( ) binSearch.
(from, upto) -
;
. . :
0 1 2 3 4 6 7 8 9 10 11 12 13 14 15 16 17
- 2 7 11 15 17 19 23 29 31 37 41 44 53 +
12 from = 7 upto = 12.
from = 7 . ,
61 upto+1 = 13.
v[from-1] < x < v[upto+1].
binSearch -
( )
pinsrt.txt:
#include <iostream>
#include <fstream>
#include <climits>
using namespace std;

unsigned int binSearch( const int v[], int n, int x );

int main()
{
const unsigned int N( 60 );

int v[N]; //
unsigned int last(N-10); // v[1]...v[last]
int x; //
unsigned int ndx; //
int k;
ifstream a( "pinsrt.txt" );

for ( k = 1; k <= last; k = k+1 )


a >> v[k]; //
a.close();
v[0] = INT_MIN; v[last+1] = INT_MAX; //

cout << "E THN TIMH X (9999 ): "; cin >> x;


while ( x != 9999 )
{
ndx = binSearch( v, last, x );
if ( v[ndx] == x )
cout << " : " << ndx << endl;
else
{
for ( k = last+1; k >= ndx; --k ) v[k+1] = v[k];
v[ndx] = x;
last = last + 1;
cout << " : " << ndx << endl;
}
cout << "E THN TIMH X (9999 ): "; cin >> x;
} // while
} // main
253

, 60 1..50.
0 51 .
E THN TIMH X (9999 ): 40
: 21
E THN TIMH X (9999 ): 43
: 22
E THN TIMH X (9999 ): 41
: 22
E THN TIMH X (9999 ): 40
: 21
E THN TIMH X (9999 ): 43
: 23
E THN TIMH X (9999 ): 41
: 22
E THN TIMH X (9999 ): 9999
:
.
. -
, , .
,
. , -
. , ,
: -

. -
.
, . , -
. , -
.
, . ,
, N2. :
. .
, ()2 = N2. : N2.
, , , -
N2.
:
middle = (from + upto) / 2;
v[from] v[middle]
v[middle+1] v[upto]
z
. -
; ( z). ,
: ; ;
(merge sort)
NlogN,
N2. -
.
NlogN, .
(divide and
conquer) :
() .
254 9

9.6.1 binSearch
.
, [0..l) - - < x.
: [last+1..last+1) k: [r..last+1) v[k] x ()
.
v[middle] < x l = middle + 1. v[k] <
x k [0..middle] [0..middle+1) [0..l). k:
[r..last+1) v[k] x .
v[middle] x r = middle. v[k] x
k [middle..last] [middle..last+1) [r..last+1). k:
[0..l) v[k] < x .
while :
(l >= r) && (k: [0..l) v[k] < x) && (k: [r..last+1) v[k] x)
l [r..last+1) : v[l] x. , l-1 [0..l) : v[l-1]
< x. v[l-1] < x v[l].
d = r l
( while).
l < r l middle < r ( = (l+r)/2
.)
l = middle + 1 d = r (l+r)/2 1 < d.
r = middle d = (l+r)/2 l < d.
r l while
.

9.7
, , :
.

, -
1.7


.
0..1.

.
-
.
( )
.
.
.
, .

7 .
255


9-1
double a[10];
.
:
(a[0] a[9]) (a[1] a[8]) (a[2] a[7]) (a[3] a[6]) (a[4] a[5])
9-2 ,
0 - 1, :
= |0| + |1| +. . . + |-1|
( = 5)
.
, 0, ,
. , .
: = A02 A12 ... AN2 1 .
: = m ax (|Ak|).
k 0..N 1
-1, -2 -
.
9-3 norm1, norm2
normInf .
9-4 w -
. ! w.
9-5
double vectorSumIf( const double x[], int n,
double lb, double ub )
x[k] x : lb
x[k] ub.

B
9-6 x, y n . x -
y k, 0 n-1, : xk < yk xj ==
yj j 0 k-1.
:
bool lt( int x[], int y[], int n)
:
true x y
false .
9-7 . . 6-11.
text, lsq.txt, (xk, yk), k = 0 .. N-1
. xk, yk.
100. xk, yk
x, y 100 .
256 9


(multiple correlation coefficient) R2
:
N 1

(x k y )2 N 1
R2 = k 0
N 1
: <y> = N1 Yk
( y y )
k 0
k
2 k 0

R2 0 ( ) 1.
R2.
*9-8 maxNdx ,
// 0 <= from <= upto <= n1
mxp = from;
m = from+1;
while ( m <= upto ) )
{
if ( x[m] > x[mxp] ) mxp = m;
m = m + 1;
}
// from mxp upto && j: from..upto x[j] x[mxp]
.:
from mxp m - 1 && j: from..m-1 x[j] x[mxp]
while.
9-9 :
int linSearchSrt( const int v, int n, int from, int upto, int x )
, , v x.
.
9-10 :
unsigned int linSearchMult( const int v, int n,
int from, int upto, int x )
v x
v x.
9-11 , ( v[0] v[N+1]
- +)8:
// N > 0
k = N;
while ( k >= 2 ) // j: k..N v[j] v[j+1]
{
mxp = maxNdx( v, N+2, 1, k );
sv = v[mxp]; v[mxp] = v[k]; v[k] = sv;
k = k - 1;
} // for
// j: 1..N v[j] v[j+1]


9-12 . 7-15; :
double mp( double a[], int N, double x )
:

8
. -
.
257

N 1
1 1 1 1
mp(x) = xak x a0 . x a1 ... x aN 1 , 1
k 0

9-13 :
const int N = 50;

int v[N+2];
v[0] v[N+2] - + .
v[1] v[l] (l < ),
. x
v[m] m l + 1, :
,
.
9-14 ( )
: (straight insertion
sort):
for ( i = 2; i <= N; i = i+1 ) //I: v[1]v[i-1]
{
v[i] v[1]v[i-1]
} // for
.
9-15 text, int1.txt int2.txt,
. -
(int3.txt) .
258 9

10

:
- .
.
:

, .
.
:

() string





:
10.1 string .......................................................................................................... 260
10.2 ....................................................................................................................... 262
10.3 ........................................................................................................... 262
10.4 .................................................................................................................................. 263
10.5 .................................................................................................................................................... 265
10.6 - ............................................................................................................. 268
10.6.1 ...............................................................................................................................268
10.6.2 size_type ....................................................................................................................................269
10.7 - ................................................................................................................................. 269
10.8 .................................................................................................................................................... 270
10.9 - - .................................................................................................... 273
10.10 ............................................................................................................................. 274
10.11 ................................................................................................................................................. 276
10.12 string ..................................................................................................................... 277
10.12.1 ............................................................................................................................................278
10.13 C: .......................................................................................... 281
10.13.1 C .........................................................................................................................................283
10.14 * std::wstring ............................................................................................................................. 284
10.15 ... ........................................................................................................................................... 285
................................................................................................................................................................... 285
.............................................................................................................................................................................285
B .............................................................................................................................................................................286
.............................................................................................................................................................................287

259
260 10

:
:
cout << " " << endl;
, ,



cout.
.
, ,
:
char a[] = { '','','',' ','','','','','','',' ',
'','','','','',' ','','','','','','' };
! :
cout << a << endl;
:

( .)
C++ :
char b[] = " ";
:
cout << b << endl;
:

; . :
cout << (sizeof a) << " " << (sizeof b) << endl;
:
23 24
char(0) ( : '\0'),
b. C, -
.
char(0)
.
:
char. C -
. -
C++. , C++ ()
string ()
.
string
string (#include <string>).

10.1 string
1:

1 using namespace std "std::string".


261

#include <iostream>
#include <string>
using namespace std;
int main()
{
string s0;
s0 , .
, .
, , :
string s1( " C++" );
,
"\" ( . 4-3).
..:
string path( "f:\\cwork\\prog7_1.cpp" );
string quest( "what\'s this\?" );
:
cout << " s0: " << s0 << endl;
cout << " s1: " << s1 << endl;
cout << " path: " << path << endl;
cout << " quest: " << quest << endl;
:
s0:
s1: C++
path: f:\cwork\prog7_1.cpp
quest: what's this?
char. , :
string a( 'a' );
!
:
string a( 10,'a' );
:
cout << " a: " << a << endl;
:
a: aaaaaaaaaa
a 10 'a'.
'a' :
string a( 1,'a' );
string a( "a" );
char:
char b[] = " ";
string s2( b );

string:
string s2( a );
string:
string s3( s1, 5, 7 );
s3 s1
5 ( 0) 7 . s1
, , s3,
:

262 10

10.2
,
string, char. ' : c_str
data .
:
const int sz = 50;
string s1( " C++" );
char ac[sz];
s1.c_str(). char(0) . ,
C, .. ac:
strcpy( ac, s1.c_str() );
strcpy() .
s1.data(); char(0) .
,
strcpy( ac, s1.data() );
. -
s1.c_str().
: -
. :
(c1.c_str())[3] = '';

10.3
= , -
string:
string,
char,

, :
string s0;
string s1( " C++" );
char b[] = " ";
:
s0 = s1; cout << " s0: " << s0 << endl;
s0 = 'a'; cout << " s0: " << s0 << endl;
s0 = b[4]; cout << " s0: " << s0 << endl;
s0 = "what\'s this\?"; cout << " s0: " << s0 << endl;
:
s0: C++
s0: a
s0:
s0: what's this?
"=",
assign(): :
string s1( " C++" );
char b[] = "0123456789";
string s2;
1. : s2.assign(s1) s2 = s1.
s2.assign( s1 ); cout << s2 << endl;
:
263

C++
2. : s2.assign(s1, p, n) : s2
s1 n () p. ..
s2.assign( s1, 5, 7 ); cout << s2 << endl;
:

3. : s2.assign(cs) cs
char. .. :
s2.assign( b ); cout << s2 << endl;
s2.assign( "0123456789" ); cout << s2 << endl;
:
0123456789
0123456789
3. : s2.assign(cs, n) cs
char n , 0 cs. s2 n
cs. .. :
s2.assign( b, 5 ); cout << s2 << endl;
s2.assign( "0123456789", 5 ); cout << s2 << endl;
:
01234
01234
4. , s2.assign(n, c) n c char.
s2 n c. .. :
s2.assign( 5, 'a' ); cout << s2 << endl;
:
aaaaa
! string -
: swap().
:
cout << " s1: " << s1 << " s2: " << s2 << endl;
s2.swap( s1 );
cout << " s1: " << s1 << " s2: " << s2 << endl;
:
s1: C++ s2: aaaaa
s1: aaaaa s2: C++
: s2.swap(s1) -
s1 s2. , , swap() -
.

10.4
, . -
<< string,
cout , ofstream text.
a string -
; , a
cin >>; , ... . :
cout << " ;" << endl;
cin >> a;
cout << a << endl;
264 10

:
;
<enter>

,
('\n') ('\t').
2:
getline( cin, a, '\n' );
:
cin,
a,
('\n').
ifstream,
.
, getline(cin, a, '\n'), <enter>, -
, a .
getline() text.
inpData.txt :
873\t537\t\t2510 997 799\n
( \t \n tab newline .)
:
ifstream tin( "inpData.txt" );
string s1, s2, s3, s4;
:
getline( tin, s1, '\t' );
getline( tin, s2, '\t' );
getline( tin, s3, '\t' );
getline( tin, s4, '\n' );
, , , s1 s2 string. -
int. ,

19.11.2008
:
getline( tin, s1, '.' );
getline( tin, s2, '.' );
getline( tin, s3, '\n' );
(std::)getline()
C getline cin. , , :
char q[100];
q
a, :
cin.getline( q, 100 );
a.assign( q );
q
99 (= 100 - 1) . (100) -
char(0) q. -
, a.assign(q), q ( char(0)) a.

2 std::getline ...
265

<enter> cin.getline()
std::getline: q ( char(0) q[0]).


. 8.
:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
ifstream s;
ofstream t;
string sFlNm, tFlNm;
char ch;

cout << " : "; getline( cin, sFlNm, '\n' );


s.open( sFlNm.c_str() );
if ( s.fail() )
cerr << " " << sFlNm << endl;
else
{
cout << " : "; getline( cin, tFlNm, '\n' );
t.open( tFlNm.c_str() );
if ( t.fail() )
{
s.close();
cerr << " " << tFlNm << endl;
}
else // ok
{
s.get( ch );
while ( !s.fail() && !t.fail() )
{ t.put( ch ); s.get( ch ); } // while
if ( !s.eof() )
cerr << " " << endl;
t.close();
s.close();
} // if ( t.fail
} // if ( s.fail
} // main
, string, -
open -
char. , sFlNm.c_str()
tFlNm.c_str().

10.5
compare()
(<, >, == ).
s1.compare(s2)
s1 s2,
s1 s2,
(0) s1 s2 .
:
266 10

string s1( "abc" );


string s2( "bce" );
string s3( "abcd" );
string s4( "abc" );
:
cout << s1.compare(s2) << " " << s2.compare(s1) << endl;
cout << s1.compare(s3) << " " << s3.compare(s1) << endl;
cout << s1.compare(s4) << " " << s4.compare(s1) << endl;
:
-1 1
-1 1
0 0
:
s1 ("abc") s2 ("bce"),
s2 s1. ,
s1 s3 ("abcd"),
s3 s1. ,
s1 s4 .
string
char. ,
char a[] = "abd";
:
cout << s1.compare( "cdef" ) << endl;
cout << s2.compare( a ) << endl;
:
-2
1
:
if ( s1.compare(s2) < 0 )
cout << " " << s1 << " "
<< s2 << endl;
else if ( s1.compare(s2) > 0 )
cout << " " << s1 << " "
<< s2 << endl;
else
cout << " " << s1 << " " << s2
<< " " << endl;
:
s1.compare(s2) 0 s1 s2
>, >=, <, <=, ==, !=.
, if :
if ( s1 < s2 )
cout << " " << s1 << " "
<< s2 << endl;
else if ( s1 > s2 )
cout << " " << s1 << " "
<< s2 << endl;
else
cout << " " << s1 << " " << s2
<< " " << endl;
:
if ( s1 == "abc" ) cout << "eq" << endl;
.
267


string:
string v[N] = { "PASCAL", "BASIC", "FORTRAN", "COBOL", "RPG",
"ALGOL", "LISP", "PROLOG", "LOGO", "C++",
"PL/I", "ADA", "BCPL", "SNOBOL", "APL", "C" };
' .
9.5.2:
//
for ( k = N; k >= 2; k = k-1 )
{
meg = maxNdx( v, 1, k );
sv = v[meg]; v[meg] = v[k]; v[k] = sv;
} // for
3 v[0] v[N-1].
v[mxp] v[k] swap:
//
for ( k = N-1; k >= 1; k = k-1 )
{
mxp = maxNdx( v, N, 0, k );
v[mxp].swap( v[k] );
} // for
maxNdx ;
int string:
int maxNdx( const string x[], int n, int from, int upto )
:
#include <iostream>
#include <string>
using namespace std;

int maxNdx( const string x[], int n, int from, int upto );

int main()
{
const int N = 16;

string v[N] = { "PASCAL", "BASIC", "FORTRAN", "COBOL", "RPG",


"ALGOL", "LISP", "PROLOG", "LOGO", "C++",
"PL/I", "ADA", "BCPL", "SNOBOL", "APL", "C" };
int k, mxp;
//
for ( k = N-1; k >= 1; k = k-1 )
{
mxp = maxNdx( v, N, 0, k );
v[mxp].swap( v[k] );
} // for
//
for ( k = 0; k <= N-1; k=k+1 ) cout << v[k] << endl;
} // main
:
ADA
ALGOL
APL

3 .
:
string v[N+2] = { " ", "PASCAL",... "C", " " };
:
v[0].assign(5, char(0)); v[N+1].assign(5,char(255));
268 10

BASIC
BCPL
C
C++
COBOL
FORTRAN
LISP
LOGO
PASCAL
PL/I
PROLOG
RPG
SNOBOL

10.6 -
string ,
, .
length ().
:
string s0, s1( " C++" );
string path( "f:\\cwork\\prog7_1.cpp" ),
quest( "what\'s this\?" );
string a( 10,'a' ), c( "a" );
:
cout << s0.length() << " " << s1.length() << " "
<< path.length() << " " << quest.length() << " "
<< a.length() << " " << c.length() << endl;
:
0 20 20 12 10 1
path \\ . -
\' \? quest.
length() size() . -
:
cout << s0.size() << " " << s1.size() << " "
<< path.size() << " " << quest.size() << " "
<< a.size() << " " << c.size() << endl;
s0 . s0 ,
. empty(), true
( ) false
. .. :
if ( s0.empty() ) cout << " s0 !" << endl;
else cout << " s0 " << endl;
if ( s1.empty() ) cout << " s1 !" << endl;
else cout << " s1 " << endl;
:
s0 !
s1

10.6.1
string;
max_size():
string s1;
269

cout << "max_size = " << s1.max_size() << endl;


(BC++ v.5.5):
max_size = 4294967281

10.6.2 size_type
length(), size() max_size() string::size_type,
C++
string.
C size_t -
sizeof. cstddef ( stddef.h)
:
typedef unsigned int size_t;
.
.4

10.7 -
(concatenate) .
+. , ,
:
string s1( "" ), s2( " " ), s3;
:
cout << (" " + s1 + " " + s2 + " ")
<< endl;
s3 = " " + s1 + " " + s2 + " ";
cout << s3 << endl;
:


+ :
string,
string ,
string char (
'\0'.)
string.
(append)
string. ..
:
s3 = " ";
s3 = s3 + s1; s3 = s3 + " "; s3 = s3 + s2;
s3 = s3 + " ";
string , append(). -
5:

4 , C++ size_t .
5 :
s3 = " "; s3 += s1; s3 += " ";
s3 += s2; s3 += " ";
270 10

s3 = " ";
s3.append( s1 ); s3.append( " " ); s3.append( s2 );
s3.append( " " );

10.8
-
. -
, find ( -
) . string
.
find (). string s t
string


char

s.find(t) s, ,
t. s, o
t.
s.find(t, i), i string::size_type, s,
, i, t.
, s, o t.
t s find .
string::npos. string::size_type.

:





string text1;
: 6
text1 = " \n"
" \n"
" \n"
" ";
'\n' .
:
char a[] = "";
:
if ( text1.find("") == string::npos )

. 2 , +, v += a : v = v + a.
+ .
6 :
text1 = " \n";
text1.append( " \n" );
text1.append( " \n" );
text1.append( " " );
271

cout << " " << endl;


else
cout << text1.find("") << endl;
if ( text1.find("") == string::npos )
cout << " " << endl;
else
cout << text1.find( "" ) << endl;
cout << text1.find(a) << endl;
cout << text1.find('') << endl;
cout << text1.find(a[0]) << endl;
:
54

54
54
54
:
"" 54 ( 1 3).
'' 54 ( 4 5).
"" text1 ( 2).
:
( ) : -
:
size_t pos;
// . . .
pos = text1.find("");
if ( pos == string::npos ) cout << " " << endl;
else cout << pos << endl;
pos = text1.find("");
if ( pos == string::npos ) cout << " " << endl;
else cout << pos << endl;
cout << text1.find(a) << endl;
cout << text1.find('') << endl;
cout << text1.find(a[0]) << endl;

( ) .
100 .
:
cout << text1.find( "" ) << endl;
cout << text1.find( "", 40 ) << endl;
:
39
110
: 39.
40, 110.
:

, !
:
string text2;
// . . .
text2 = " \n"
" \n\n"
" , !";
272 10

:
int ndx;

:
ndx = text2.find( "" );
while ( 0 <= ndx && ndx < text2.length() )
{
cout << ndx << " ";
ndx = text2.find( "", ndx+1 );
}
cout << endl;
:
0 25 51 55

, rfind(), find(),
( ). ,
, :
cout << text1.rfind("") << endl;
cout << text1.rfind("", 108) << endl;
:
110
39
: text2

. :
cout << text2.find_first_of("") << endl;
:
10
, 10 '' ().
:
cout << text2.find_first_of("", 11) << endl;
:
22
22 '' ().
, find_first_of() -
, . -
,
.
, rfind() find() find_last_of() find_first_of():
, ,
.
find_first_not_of() -
-.
find_last_not_of().
:
: , !
!
. , wstring, string
wchar_t. Unicode,
.
273

10.9 - -
, ,
(replace ), .
string replace().
.
:
string target( "" ), text1;
text1 =" \n"
" \n")
" .";
:
cout << text1 << endl << endl;
text1.replace( text1.find(target), target.length(), "");
cout << text1 << endl;
:


.



.
replace :
-
.
text1 target ( "")
(text1.find(target)).
-
. target (-
"" 4).
.
: char string.
("" "")
. .
"" ,
find:7
ndx = text1.find( target );
while ( 0 <= ndx && ndx < text1.length() )
{
text1.replace( ndx, target.length(), "" );
ndx = text1.find( target, ndx+1 );
}
:


.
replace() . , ..:
text1.replace( text1.find(target), target.length(), "" );
target,
text1, , . .

7 ndx+1 . , . ndx+("").
!
274 10

erase() .
:
.
:
text1.erase( text1.find(target), target.length() );
,
insert(). append() :
append() ,
insert() -
.
append(), -
. :
string s1( "" ), s2( " " ), s3;
:
s3 = " "; cout << s3 << endl;
s3.insert( 0, s1 ); cout << s3 << endl;
s3.insert( 5, s2 ); cout << s3 << endl;
s3.insert( 0, " " ); cout << s3 << endl;
s3.insert( 12, " " ); cout << s3 << endl;
:




10.10
, string,
.
:
string s3;
:
if ( s3[0] == '' ) s3[0] = '';
, :
0 s3.length()-1.
:
string char
.
,
string: at.
:
if ( s3.at(0) == '' ) s3.at( 0 ) = '';
,
, .

, , .
, !
:
275

at(), string,
(strIn.at(k))
length(), ,
(for (k = strIn.length()-1; k>=0; k=k-1)),
compare(), (strIn.compare(strOut) == 0)
string != (strIn != "T" && strIn
!= "t" && ...),
append(), string, -
. .
; strIn
strOut strIn
.
for ( k = strIn.length()-1; k >= 0; k = k-1 )

(strIn[k]) at (strIn.at(k)). append;
append .
;
string str1( "x" );
x (place holder) 1.
strIn:
str1[0] = strIn.at(k);
.
.
#include <iostream>
#include <string>
using namespace std;
int main()
{
const string msg( "E (T IA TEO): " );

int k;
string strIn, strOut, str1( "x" );

cout << msg; getline( cin, strIn, '\n' );


while ( strIn != "T" && strIn != "t" &&
strIn != "" && strIn != "" )
{
strOut = ""; //
for ( k = strIn.length()-1; k >= 0; k=k-1 )
{
str1[0] = strIn.at( k );
strOut.append( str1 );
}
cout << " : " << strIn
<< " : " << endl;
cout << strOut << endl;
if ( strIn == strOut )
cout << " !" << endl;
cout << endl;
cout << msg; getline( cin, strIn, '\n' );
} // while
cout << " " << endl;
} // main
.
:
E (T IA TEO): ABCDEFGHJIK
: ABCDEFGHJIK :
276 10

KIJHGFEDCBA

E (T IA TEO): NION ANOMHMATA MH MONAN OIN


: :

E (T IA TEO):
: :

E (T IA TEO): MADAM IN EDEN I'M ADAM


: MADAM IN EDEN I'M ADAM :
MADA M'I NEDE NI MADAM

E (T IA TEO): MADAMINEDENIMADAM
: MADAMINEDENIMADAM :
MADAMINEDENIMADAM
!

E (T IA TEO): T

10.11
(substring), -
, . substr() :
string
.
s1 string,
:

.
substr(). :
string s1 = " C++", s2;

s2 = s1.substr( 5, 7 );
cout << s2 << endl;
:

, ,
:
s2 = s1.substr( 5 );
cout << s2 << endl;
:
C++

1
, strIn strOut
:
strOut = ""; //
for ( k = strIn.length()-1; k >= 0; k = k-1 )
strOut.append( strIn.substr(k,1) );

277

2
:
string s1, s2, s3;
:
s1 = " ";
s2 = s1.substr( 8, 8 );
s3 = s1.substr( s1.find(''), 10 );
cout << s2 << s3 << endl;
s2 = s1.substr( 20, 20 );
cout << s2 << endl;
:


,
substr .

10.12 string
/ C++ -
string (string streams). , :


.
()
text.
#include <sstream>
:
istringstream ssin( aString );
ostringstream ssout;
ssin -

string aString( "17 -375 145.78 31e4" );
(2.3) :
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int k, j;
double x, y, t;
string aString( "17 -375 145.78 31e4" ), outString;
istringstream ssin( aString );
ostringstream ssout;

ssin >> k >> j >> x >> y;


ssout << k << ' ' << j << ' ' << x << ' ' << y;
outString = ssout.str();
cout << outString << endl;
}
:
ssin >> k >> j >> x >> y;
278 10

17, -375, 145.78, 31e4 k, j, x, y .


(ssin >> t) . ssin.eof()
true.

ssout << k << ' ' << j << ' ' << x << ' ' << y;
string ssout.
ssout.str()
string. :
cout << ssout.str() << endl;
/ string ( )
/ . str :
ssin.str(aString) ssout.str(aString) (
) aString. ssout ,
, .
as = ssin.str() as = ssout.str() as ( string)
( ).
.
.

10.12.1
-
text . -
-
. ;
, .. , .
, e .
, ( ) -
.
!
.
string .

string aString;
// . . .
getline( cin, aString, '\n' );
-
(int) k 7 &.
aString. aString k :
istringstream ssin;
aString:
ssin.str( aString );
:
ssin >> k;
if ( ssin.fail() ) //
, fail, .
-
.
279

"1&" aString.
ssin.fail() false, : ! k
1. ; 1 .
k
aString. . ssin.eof()
.
:
istringstream ssin;
int k;
string aString;
char c;
:
getline( cin, aString, '\n' );
ssin.str( aString );
ssin >> k;
if ( ssin.fail() )
//
else //
{
ssin >> c;
if ( ssin.eof() ) // OK, ,
cout << k << endl;
else
//
}
.

.

, 2.12,
:
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
using namespace std;
int main()
{
const double g( 9.81 ); // m/sec2,
double h, // m,
tP, // sec,
vP; // m/sec,
string s;
istringstream ssin;
bool done( false );
char c;

// o h
while ( !done || h < 0 )
{
cout << " o (h >= 0) m: ";
getline( cin, s, '\n' );
ssin.clear();
ssin.str( s ); ssin >> h;
if ( ssin.fail() )
cout << " (" << s << ")" << endl;
else
{
ssin >> c;
if ( ssin.eof() )
280 10

done = true;
else
cout << " (\'" << c << "\')"
<< endl;
} // if ( !ssin.fail
} // while

// (g == 9.81) && (0 <= h <= DBL_MAX)


// tP, vP
//
, cin >> h :
getline( cin, s, '\n' );
ssin.clear();
ssin.str( s ); ssin >> h;
. ssin.clear(): , -
*), ssin.clear(),
, .
while (
). .
(.. <esc>).
:
o (h >= 0) m: *)
(*))
o (h >= 0) m: 8o
('o')
o (h >= 0) m: -80
o (h >= 0) m: 80
= 80 m
= 4.03855 sec
= -39.6182 m/sec

, string, . -
. 1 :
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ostringstream sout;
string aString;

sout.precision( 8 );
sout << 1234.5 << " " << 123456.78 << " "
<< 123456789.0123 << endl;

sout.setf( ios_base::scientific, ios_base::floatfield );


sout.precision(8);
sout << 1234.5 << " " << 123456.78 << " "
<< 123456789.0123 << endl;

sout.setf( ios_base::fixed, ios_base::floatfield );


sout.precision(8);
sout << 1234.5 << " " << 123456.78 << " "
<< 123456789.0123 << endl;
aString = sout.str();
cout << aString << endl;
}
, cout, sout. ,
sout aString. :
281

1234.5 123456.78 1.2345679e+008


1.23450000e+003 1.23456780e+005 1.23456789e+008
1234.50000000 123456.78000000 123456789.01230000

string.

10.13 C:
C :
1. C++ (
)
2. string.
:
char,
char(0) -
.
:
char a[100] = " ";

char a[] = " ";


char(0) . :
char a[] = { '','','',' ','','','','','','',' ',
'','','','','',' ',
'','','','','','','\0' };
char(0) .8
:
cout << a << endl;
cin.getline().
char a[100];
, a, :
cin.getline( a, 100 );
, istream cin, get()
:
cin.get( a, 100 );
, , .
, char(0). ,
get (<enter>, '\n'):
cin.get( a, 100 ); cin.get( ceol );
ceol char.
C++ ( C)
.
:9
#include <string>
a :

8 '\0' . char(0) 0 .
9 #include <cstring> C. c
.
282 10

a = " demod";
! a C++, strcpy() (string
copy):
strcpy( a, " demod" );
:
strcpy( a, b );
b , ..:
char b[] = " ";
strncpy() strcpy(),

. :
char a[50] = "abcdefghijklmnopq";

strncpy( a, "123456789", 15 );
cout << a << endl;
strcpy( a, "abcdefghijklmnopq" );
strncpy( a, "123456789", 5 );
cout << a << endl;
:
123456789
12345fghijklmnopq
15
9. char(0)
a 123456789.
5 . 5
a. a 12345 :
strncpy ( a, "123456789", 5 ); a[5] = char( 0 );
:
string cpps;
char cs[ L ];
L cs cpps ,
, . :
strncpy ( cs, cpps.c_str(), L-1 ); cs[L-1] = char( 0 );
: L - 1
cs . cpps
L - 1 char(0) .
, strcmp(),
compare. strcmp(a, b)
a b,
a b,
(0) a b .
strncmp strcmp , ,
. :
char a[50] = "abcdefghijklmnopq", b[] = "abcdrstuvwxyz";
cout << strcmp(a, b) << " " << strncmp(a, b, 3) << endl;
:
-13 0
: a b (strcmp(a, b) == -13 < 0),
(strncmp(a, b, 3) == 0).
283

stricmp() strcmp()
() . :
char a[] = "firstName", b[] = "FirstName", c[] = "firstname";
cout << strcmp(a, b) << " " << strcmp(a, c) << endl;
cout << stricmp(a, b) << " " << stricmp(a, c) << endl;
:
1 -1
0 0
strnicmp() stricmp() , strncmp strcmp.
strlen() (string length), size_t
, char(0):
char a[100], b[] = " ";

strcpy( a, " demod" );


cout << strlen(a) << " " << strlen(b) << endl;
cout << strlen( " " ) << endl;
:
39 23
14
a :
"" (strcmp(a, "") == 0)
(strlen(a) == 0)
char(0) (a[0] == char(0)).
.
strcat(a, b) a.append(b):
a b. :
char s1[] = "", s2[] = " ", s3[50];

strcpy( s3, " " );


strcat( s3, s1 ); strcat( s3, " " ); strcat( s3, s2 );
strcat( s3, " " );
cout << s3 << endl;
:

strncat(), , , -
.
C++ "C-style strings".
. -
.
string, .

10.13.1 C
C ( ) .
-
.
cstdlib , .
atof() (alphanumeric to float), atoi() (alphanu-
meric to int) atoll() (alphanumeric to long). (
) double, , int
long . .. :
#include <iostream>
284 10

#include <cstdlib>
using namespace std;
int main()
{
char s1[] = "12345", s2[] = "1.23456789e10",
s3[] = "1.23ab45678";
long l;
double d;

l = atol( s1 ); d = atof( s2 );
cout << l << " " << d << endl;
:
12345 1.23457e+10
-
. .. :
l = atol( s3 ); d = atof( s3 );
cout << l << " " << d << endl;
:
1 1.23
; atoll(),
1.23ab45678, 1, '.',
long. , 1. atof()
1.23 'a'. , 1.23.

.
, , strtod() strtol()
.

10.14 * std::wstring
4.7 wchar_t 16 .
, , 65536 , 256 char -
Unicode. wchar_t
char L, ..:
L'a' L'%' L''
wchar_t
wchar_t :
wchar_t w[5]= L"";
:
wcscpy( w, L"wsx" );
:
char L wchar_t,
char L
wchar_t.
char strcpy,
wchar_t wcscpy.
, strX wcsX
wchar_t.
C++ std::wstring, std::string,
wchar_t. , :
wchar_t w[5]= L"";
wstring w0, w1( L"abc" ), w2( 4, L'q' ), w3( w );
285

wstring :
wstring string
wstring <<.
w1 :
int ndx;
for ( ndx = 0; ndx < w1.length(); ndx = ndx+1 )
cout << static_cast<unsigned char>(w1[ndx]);
cout << endl;
w0 w1, w2 w3
:
abc
qqqq

, ..:
w0 = L"qazw";
c_str wcscpy -
wchar_t:
wcscpy( w, w1.c_str() );
, , :
cout << typeid(w1[0]).name() << " " << sizeof(w1[0]) << endl;
:10
wchar_t 2

10.15 ...
C++ .
( ) string. :
string.
.
( cin, cout)
string.
string.
.
string .
C
.


10-1
qq. .. "", "zppquzppqu" qq,
"", "zppqqppz" .
10-2 10.5,
text.

10 Borland C++ 5.5.


286 10

10-3 . 1 8.10
.
10-4 . 2 8.10.

B
10-5 :
string getRight( string s, int n )
n () s. n 0
, n s.length() s.
10-6
:


. . 10-1
MASTERCARD 51-55 16 mod 10
. VISA 4 13, 16 mod 10

AMEX 34, 37 15 mod 10


. Diners Club/ 300-305
14 mod 10
Carte Blanche 36, 38
.
Discover 6011 16 mod 10

2014
(check digit) enRoute 15 any
2149
-
JCB 3 16 mod 10
LUHN.
2131
LUHN - JCB 15
1800
mod 10
:
. 10-1 -
1: -
( 1 .
, 2 ...)
2: -
.
10 .

:
49927398716
1:
4 9 9 2 7 3 9 8 7 1 6
x2 x2 x2 x2 x2
------------------------------
18 4 6 16 2
2: 4 +(1+8)+ 9 + (4) + 7 + (6) + 9 +(1+6) + 7 + (2) + 6 = 70
.

) isValidCrCardNum ( ) string
,
true ( ) false .
) appendChkDigit ( ) string
.
.
.
287

10-7 text -
string.
().
.
zzz.


10-8 ( . 8-7) text,
misthoi.txt, :
:
\t1234.5\t7\t2\n
( \t tab \n .)
() 1234.5 , 7
2
. .
. , :
( ).
.
:
.
800 3500,
0 35,
0 12.
log.txt
. ..:
Line 7 salary: 35650
Line 7 number of children: -4
Line 11 number of years: 51
Line 18 empty
Line 26 salary: 955000
Line 28 incomplete line
Line 36 name empty
.: ( \n) getline.
\t 3 .
288 10


11. ....................................................................................................................................... 291
12. I ............................................................................................................................................ 315
13. I ................................................................................................................................................. 343
14. II ................................................................................................................................................ 389
15. - II ............................................................................................................................................. 431
project 1: ............................................................................................................... 477
project 2: 3 .................................................................................................... 485
16. .................................................................................................................. 493
17. * .......................................................................................................... 539
18. ...................................................................................................................... 581

11

:

.
.
.
:
:
C++.

,

:


for
do-while
n+
break
switch
- goto
:
11.1 ................................................................................................................................ 292
11.2 ..................................................................................................................................... 294
11.3 ........................................................................... 294
11.3.1 * ++ bool ............................................................................................................................297
11.4 ......................................................................................... 297
11.5 ........................................................................................................................... 298
11.6 for .......................................................................................................................................... 299
11.7 do-while ............................................................................................................................. 302
11.8 n+ - break.............................................................................................. 304
11.9 switch .................................................................................................................................. 305
11.9.1 switch ...............................................................................................................307
11.10 * - goto .................................................................................................................... 308
11.10.1 goto ................................................................................................309
11.11 * continue ........................................................................................................................... 310
11.12 * ........................................................................................................................ 310

291
292 11

11.13 ........................................................................................................................ 311


11.14 ... ............................................................................................................................................ 312
................................................................................................................................................................... 312
.............................................................................................................................................................................312

:

. :
,
.
,
.
,
.
,
.
if, ifelse,
.
while,
.
for, .
,
-.
, : -
(+, -, *, /, %), (==, !=, <, <=, >, >=), (&&, ||, !)
:
+ -,
&, ,
*,
,
sizeof, ""
typeid, .
, , -
.

,
.
.
. .
-
/ .

11.1
,
-
. .

.
293

, C++
. -
:
int main()
{
MyType v1;

cout << "going into block" << endl;


{ // <--- block start
MyType v2( 5 );

cout << " chkpoint 1" << endl;

MyType v3( 15 );

cout << " chkpoint 2" << endl;


} // <--- block end
cout << "coming out of block" << endl;
}
MyType int
1.
:
creating a MyType variable. Initializing with 0
going into block
creating a MyType variable. Initializing with 5
chkpoint 1
creating a MyType variable. Initializing with 15
chkpoint 2
destroying a MyType variable having value 15
destroying a MyType variable having value 5
coming out of block
destroying a MyType variable having value 0
, :
-
(block)
.
.
: ,
, (
),
(automatic) (stack), -

2 (dynamic) .
-
. , -
.
:
.
:
. , ...

1 .
2 (heap).
294 11

(-
) (CERT 2009) :3

.

11.2

(type qualification).
2.4 :
const double g( 9.81 ); // m/sec
const (type qualifier)
double.
C++ , volatile ().
:
volatile int flags;
flags -
(.. ). -
,
( ) .
const volatile
cv (cv-qualified).

11.3
, ! :
:
T v;
v = :

static_type<T>().
static_type<T>() .
v.4
; , :
( )
M C++.
v = ,
.
, :
w = v = u = 0;
C++ :
w = (v = (u = 0));

3 DCL07: Use as minimal scope as possible for all variables and methods. !;
...
4 : v v. ...
295

: u 0, , 0, v. ,
, 0, w. , ,
, ( : 0) -
( : ). -
.
, :
cout << (v = 1.5) << endl;
, static_type<T>(1.5) v
( v) . .
(Borland C++) :
int v( 0 );
cout << v << " " << (v = 1.5) << endl;
:
0 1
:
1 1
cout << .
, v = 1.5 v 1.
, =
. : =
-l (lvalue)5, , .
, -
. -
(modifiable) -l.
, , :
-l, :
. ,
...

:
int k;
double a[5];
// . . .
a[0] = 5; a[1] = 10.5;
// . . .
k = 0;
a[k] = a[k] + (k = k+1);
cout << a[0] << " " << a[1] << endl;
gcc (Dev-C++) :
6 10.5
: , a[k] a[0]
. : k = k+1 k
1 1 . ,
: a[0] = (a[0] + 1) 1
a[0].
MS Visual C++ v5, :
5 6

5 l , left part ( ). , -
-r (rvalue) (right) .
296 11

: a[k] + (k = k+1) VC++


a[k] a[0]. k =
k+1 k 1 1
a[k] + (k = k+1) a[0] + 1. -l,
a[k]. k 1 : a[1] =
a[0]+1. : 1
a[1].
Borland C++ v5, :
5 11.5
: , a[k] + (k = k+1) -
: k = k+1 k 1 1
. , : a[1]
= (a[1] + 1) 1 a[1].
BC++v5 gcc a[k]
a[1] (BC++) a[0] (gcc).

-l.
.
2.10, C++ -
. .., x, b , :
x = x + b;
:
x += b;
:
x += ; : x = x + ;
x -= ; : x = x - ;
x *= ; : x = x * ;
x /= ; : x = x / ;
x %= ; : x = x % ;
/= %= . :
x .

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

, . 8-9, y x (5) .

(-l); C++ :
x = y x = x y x .
, , :
k = 0;
a[k] += (k = k+1);
cout << a[0] << " " << a[1] << endl;
(gcc):
6 10.5
(Borland C++ v5)6:
5 11.5
,
, .
. , -
. 11.1.

11.3.1 * ++ bool
, ++ -- (: -l) -
.
bool. b , ++b ( b++),
true.
... 7

11.4
:
// x == 5 && k == 0 && q > 0
y = (x += q) + ++k;
; . 2. -
if
while ( ) -
.
, : :
// x == 5 && k == 0 && q > 0
x += q; ++k;
y = x + (k-1);
, ;
; :
.
, , .
. 11.1.
:
, ( ++k, --k)
(k++, k--). :

6 , MS VC++ : 5 6, a[k] a[0]


a[1].
7 C++11 ++ bool .
298 11

11.1
:
1) x = y = z = ,
, , ) )
.
2) :
++k;
j++;
p += (q+4);
.
:
y = ++p + (x = q/2);
x = (y += p+1);
. ,
:
a[k] += (k = k+1);
!

++k k += 1 k = k + 1
--k k -= 1 k = k - 1
, .

11.5
. 5 : o o o,
x, y, ( ) o
, maxxy. :
if ( x > y ) maxxy = x;
else maxxy = y;
C++ ,
?:
maxxy = (x > y) ? x : y;
= (conditional expression).

x:

11.2

? , :
, "?", -1, ":", -2
: -
.
: .
-1
( ) -2
. , -1
-2 , , .
299

int xSign( int x )


{
int fv( 0 );
if ( x < 0 ) fv = -1;
else if ( x > 0 ) fv = 1;
return fv;
} // xSign
:
int xSign( int x )
{
return ( x < 0 ) ? -1 : ( x == 0 ) ? 0 : 1;
} // sign
x
, :
cout << ( (x < 0) ? -1 : (x == 0) ? 0 : 1 ) << endl;

11.6 for
(6.4) for C++ .
.
.
for
:
for ( v = a; v <= t; v = v + b ) E;

for ( v = a; v >= t; v = v b ) E;
b > 0,
v a, a+b, ... a+nb n : a
+ nb t < a + (n+1)b,
v a, a-b, ... a-nb n : a
- (n+1)b < t a - nb.
, v .
for .
:
"for", "(", for, [ , ] ";", [ , ] ")", ";"
:
for = { - | } ";"
true.

.
for, , .
for .
1

double a[50], b[80], m( 0 );
a[0]..a[9] b[10]..b[19]
, m, . :
for ( int k(0), j(10); k < 10; ++k, ++j )
{
300 11

b[j] = a[k]; m += a[k];


} // for
m /= 10;
for.
:
int k(0), j(10);
. : k j
for .
: k <= 9.
; ++k, ++j, ( -
11.11). ; ! -
k j.

: -
.
.
11.11.
:
, for, )
for ) for.
for
.
for - -
.
2
1 5.1:
0: #include <iostream>
1: // : 1
2: using namespace std;
3:
4: int main()
5: {
6: const int n( 10 );
7:
8: int m; //
9: double x; // o
10: double sum; // o (o) o.
11: // o o o o.
12: double avrg;// x (<x>)
13:
14: for ( sum = 0, m = 1; m <= n; m = m + 1 )
15: {
16: cout << " : "; cin >> x; // x == tm
17: sum = sum + x; // (x == tN) && (sum = (j:1..m)tj)
18: } // for
19: avrg = sum / n;
20: cout << " = " << sum << " <x> = "
21: << avrg << endl;
22: }
; while, :
sum = 0; m = 1;
for (. 14). ;
(,) .
while for.
301

, , m = m + 1,
.
:
for ( sum = 0, m = 1; m <= n; )
{
cout << " : "; cin >> x; // x = tm
sum = sum + x; // (x == tm) && (sum = (j:1..m)tj)
m = m + 1;
} // for
: ,
m = m + 1, sum = sum + x:
for ( sum = 0, m = 1; m <= n; sum = sum + x, m = m + 1 )
{
cout << " : "; cin >> x; // x = tm
} // for
, , ;
for ( sum = 0, m = 1;
m <= n;
cout << " : ", cin >> x,
sum = sum + x, m = m + 1 );
, :
for ( sum = 0, m = 1;
m <= n;
cout << " : ", cin >> x,
sum += x, ++m );
!
for while
.
: sum for
for. m for.
:
for ( sum = 0, int m( 1 ); m <= n; . . . );
! for - .
.
-

:
// : 1 for
#include <iostream>
using namespace std;
int main()
{
const int n( 10 );

double sum( 0 ); // () .
// .
for ( int m(1); m <= n; ++m )
{
double x; //
cout << " : "; cin >> x; // x = tm
sum += x; // (x == tm) && (sum = (j:1..m)tj)
} // while

double avrg( sum / n ); // x (<x>)


cout << " = " << sum << " <x> = " << avrg << endl;
} // main

302 11

, :
Ep1; Ep2; ... Epn;
while ( S )
{ Er1; Er2; ... Erk; Er(k+1); Er(k+2); ... Er(k+m); }
:
for ( Ep1, Ep2, ... Epn; S; Er(k+1), Er(k+2), ... Er(k+m) )
{ Er1; Er2; ... Erk; }
! for
-
. if, ifelse, while for,
8. , for
4 (5.1.2) :
for ( sum = 0, n = 0, selSum = 0, selN = 0,
cout << " - 0 : ", cin >> x;
x != FROUROS;
cout << " - 0 : ", cin >> x )
{
n = n + 1; // o
sum = sum + x; // o
if (0 < x && x <= 10) // 'o o
{
selSum = selSum + x; // o o
selN = selN + 1; // o
} // if
} // for
.

for . -
for : .
for, while. ,
, :
// P
for (Ep1, Ep2, ... Epn; S; Er(k+1), Er(k+2), ... Er(k+m))
{ Er1; Er2; ... Erk; }
// Q
(I ):
1. // P
Ep1; Ep2; ... Epn;
// I
2. // I && S
Er1; Er2; ... Erk; Er(k+1), Er(k+2), ... Er(k+m);
// I
3. (I && !S) Q

11.7 do-while
while for, C++ , do-while.
. 11.3 . 11-1.
while
while ,
do-while .
:

8 - ; , ! ...
303

while
, do-while -
.

do-
while. -

while. S
. false

while: true
cout << " : "; cin >> x;
while ( x <= 0 )
{
cout << " : "; cin >> x;
} // while . 11-1
do-while : do-while.

do {
cout << " : "; cin >> x;
} while ( x <= 0 );
do-while
while.
. , . :
// I
do E while ( S );
// I && !S
:
I{E}Q
E S E. Q
&& S . , do-
while:
I { E}Q, Q & & S I
I {do E while(S)} I & & !S
while do-while; -
while ,
do-while .
E.

11.3
do-while
"do", , "while", "(", , ")" ;
:


false do-while
, true


false do-while
, true


...
304 11

if. , :
while ( S ) if ( S )
{ {
E do { E } while ( S );
} }
.

11.8 n+ - break

, while for,
, do-while, -
. , 1
. .. Ada -
:

loop
S
E1
false
when St exit;
E2 true
endloop
, E1 2
St:
true
-
endloop,
false 2 . 11-2
1, St ... n+.

n+,
(1).
C++ .

. if.
C++ break
.
n+ :
while ( true ) for ( ; ; ) do

{ { {
E1 E1 E1
if ( !S ) break; if ( !S ) break; if ( !S ) break;
E2 E2 E2
} // while } // for } while ( true );
, Ada, :
if S ,
C++.
, I, : I &&
(!S). E1 :
I { E1 } Q
E2 E1 E2
:
Q && S { E2 } I
E1 S . -
:
305

(Q && !S) (I && !S)


Q I
:
I { E1} I , I & & S{ E2} I
I { while(true){ E1 if(!S)break;E2}} I & &(!S )
break: ,
, break
. , :
while ( S1 )
{
:
do {
. . .
for (...)
{
:
... break; ...
} // for
A ------> . . .
} while ( S2 );
. . .
} // while
, break.
; for
.

11.9 switch
. 1 2 5.3 -
, , , :
(oper) -
.
C++ ,
switch:
switch ( )
{
case c1: E1
case c2: E2
:
default: Ed
}
switch, - switch, , ,
(int, long int, char, bool ).
() . "case",
. default.
switch:
' .

.

default ( ).
, default -
.
306 11

! c1.
E1 E2 .
E1 break.
switch:
#include <iostream>
using namespace std;
int main()
{
double x1, x2; //
char oper; //

cin >> oper >> x1 >> x2;


switch ( oper )
{
case '+': cout << (x1 + x2) << endl; break;
case '-': cout << (x1 - x2) << endl; break;
case '*': cout << (x1 * x2) << endl; break;
case '/': if ( x2 != 0 ) cout << (x1 / x2) << endl;
else cout << " " << endl;
break;
default: cout << " (+,-,*,/) "
<< endl;
} // switch
} // main
oper char.
() . case '+', case '-
', case '*', case '/', default. switch '
oper. : '*'.
cout << (x1 * x2) << endl break ,
switch.
, (-
) 'x' , , "-
'*'". :
switch ( oper )
{
case '+': cout << (x1 + x2) << endl; break;
case '-': cout << (x1 - x2) << endl; break;
case 'x': cout << " \'*\'" << endl;
case '*': cout << (x1 * x2) << endl; break;
case '/': if ( x2 != 0 ) cout << (x1 / x2) << endl;
else cout << " " << endl;
break;
default: cout << " (+,-,*,/) "
<< endl;
} // switch
:
* 3 4
:
12
:
x 3 4
:
'*'
12
;
. switch 'x', '*' -
'/', ':' :
307

. . .
case '-': cout << (x1 - x2) << endl; break;
case 'x':
case '*': cout << (x1 * x2) << endl; break;
case ':':
case '/': if ( x2 != 0 ) cout << (x1 / x2) << endl;
else cout << " " << endl;
break;
. . .
if ifelse switch; -
bool , :
if ( S ) switch ( S )
{ {
Et case true: Et;
} }
if ( S ) switch ( S )
{ {
Et case true: Et; break;
}
else case false: Ef;
{ }
Ef
}

() -
switch ifelse.

11.9.1 switch
switch ( { }).
! ; :
switch ( oper )
{
int q( 5 );

case '+': . . .
case '-': . . .
. . .
} // switch
: -
q { ( ...). q -
} ( ...).
! ; oper -
case
q.
:
switch ( oper )
{
case '+': int q( 5 ); . . .
case '-': . . .
. . .
} // switch
+.
, :
switch ( oper )
{
case '+': { int q( 5 ); . . . }
case '-': . . .
. . .
308 11

} // switch

11.10 * - goto
(
) goto (Dijkstra 1988) C++. -
, -
. , ,
. ,
, Bohm-Jacopini (Bohm &
Jacopini 1966).
(labels),
goto.
"default" "case", ,
switch, C++ ,
..:
gvl: cout << " - 0 : "; cin >> x;
gvl
cout << " ...: "
C++ ,
':'.
goto .
:
.
:
: ( )
. : ,
! , , .
:
if ( x < 0 ) goto ts;
absX = x;
goto nxt;
ts: absX = -x;
nxt: cout << x << " " << absX << endl;
; :
if ( x >= 0 ) absX = x;
else absX = -x;
cout << x << " " << absX << endl;
(
) goto,
.
(scope) .

.
: goto
.
C++ goto,
, . -
:
goto ' .
:
309

. . .
goto lb55;
. . .
while ( i <= n )
{
. . .
lb55: x = x - 1;
. . .
} // while
( goto lb55 while)
. . .
if (x <= 0) goto lb66;
. . .
if (x == 1)
a = a + 1;
else
lb66: n = n + 1;
( goto lb66 ifelse)
, , goto -
. '
, goto
.
goto, , :
,
.
.

11.10.1 goto
() :
. . .
A
goto lb75;
. . .
B
lb75: . . .
. . .
lb75
goto lb75 , () ,
. , -
PA PB.
. ,
.
goto ,
.
goto; ,
-
.
(), ..
lb99: switch ( errCode )
{
case 1: cout << " 0" << endl;

case 2: cout << " " << endl;

case 3: cout << " "


310 11

<< endl;
. . .
} // switch
exit( EXIT_FAILURE );
goto lb99; H errCode -
, . ... exit(EXIT_FAILURE).
goto .
!
C++ goto -
.
: .
goto.
, goto,
.
. -
goto! ,
...
, D. Knuth, , ,
goto (Knuth 1977). .

11.11 * continue
continue while do-
while for .
while do-while: ( ) continue
.
for: continue (
for) .
1, for 11.7,
:
for ( sum = 0, n = 0, selSum = 0, selN = 0,
cout << " - 0 : ", cin >> x;
x != FROUROS;
cout << " - 0 : ", cin >> x )
{
n = n + 1; // o
sum = sum + x; // o
if ( x <= 0 || 10 < x ) continue; // o - o
selSum = selSum + x; // o o
selN = selN + 1; // o
} // for
, , if -
.
, continue.

11.12 *
C++ C : -
, (,). :
double x( 0.1 ), y( 3.7 ), z( 7.4 ), q;
:
q = (x, y, z);
311

cout << q << endl;


( ) .
: : 0.1, 3.7 7.4

q. , :
7.4
; ! :
q = x, y, z;
cout << q << endl;
:
0.1
; = ","
x q
( 7.4).
:
q = (x = 8.3, y = x - 4, z = y - 4);
cout << q << " " << x << " " << y << " " << z << endl;
:
0.3 8.3 4.3 0.3
, for .
, .

11.13
. E
. , '
:
, ,
,

.
: a + b + c (a + b) + c, a = b = c
a = (b = c).
! a*b + c/d + f(e)
: (a*b + c/d) + f(e).
(a*b + c/d) f(e).
a*b c/d.
C++ .
-
.
:
&& false
,
false.
|| true
,
true.
. E (), -
-
312 11

. +, -, *, /
.

11.14 ...
, C++ . ;
:

.
:
1.
. , x +=
y*a/q ++p y = ++p + (x = q/2).
.
: x = y = z = , -
, , .
2. for . ,
, .
.
while.
3. switch break. break (
11.10) .
4. goto.
-
. -, ... de gustibus et
coloribus non disputandum est.9


11-1 . 5-4 ( ) -
( a, b, c d int):
if ( a > b ) y = a; else y = b;
if ( c > y ) y = c;
if ( d > y ) y = d;
, y , , a, b, c, d.
y ;
11-2 . 5-6 ( ) switch:
R1 R2 ( ) -
R. , -
, , .
:
'P' p ,
'S' s .
.

9 ( ) .
313

11-3 . 6-15 ( )
:
. :
'1' ,
'2' ,
'3'
'4' .
'0' .
, : " 5 ".

.
11-4 N -
, t :
m = 0; t >> x[m];
while ( !t.eof() && m < N-1 )
{
m = m + 1; t >> x[m];
} // while
if ( t.eof() ) count = m;
else count = m + 1;
for, for.
11-5 . 9-1 :

double a[10];
.
:
(a[0] a[9]) (a[1] a[8]) (a[2] a[7]) (a[3] a[6]) (a[4] a[5])
314 11

12
I
:
( ) .
...
:
.
( ).
:


-
(pointer)

const
main
:
12.1 .......................................................................................................................................... 316
12.2 const .................................................................................................................... 318
12.2.1 const ...................................................................................................................................318
12.3 ........................................................................................................................................... 320
12.3.1 ....................................................................................................................................321
12.3.2 ...............................................................................................................................321
12.3.3 ....................................................................................................................................323
12.3.4 ptrdiff_t...................................................................................................................................326
12.3.5 ...........................................................................................................................................................326
12.4 ............................................................................................................................... 327
12.5 ................................................................................................................................. 333
12.5.1 ......................................................................................................334
12.6 () ....................................................................................................................... 335
12.6.1 ........................................................................................................................................337
12.7 main ............................................................................................................................ 338
12.8 ... ..................................................................................................................................................... 339
................................................................................................................................................................... 339
.............................................................................................................................................................................339
B .............................................................................................................................................................................340
.............................................................................................................................................................................340

315
316 12

:
, , -
. ,
.
-
. C++ ( C) :
.
(pointer).

,

12.1
10.13 :
char a[] = { '','','',' ','','','','','','',' ',
'','','','','',' ','','','','','','','\0' };
:
cout << a << endl;
:

, , :
double x[] = { 0.1, 1.2, 2.3, 3.4, 4.5, 5.6, 6.7, 7.8, 8.9 };
:
cout << x << endl;
! :
0x22ff20
( .)
; , ... 2.7.1.
, -,
() . ;
(x[0]) &:
cout << &(x[0]) << endl;
:
0x22ff20
!
( char) -
.
. C++:
( ) -
.
. 12-1 . 9-1 .
, ,
x[0]:
cout << (*x) << endl;
I - 317

:
pinA 0.1
x
p :
. . .
double* p;
pinA[0] pinA[1] pinA[2] pinA[19] x
. 12-1 . 9-1. p -.
:
(pinA[0]) . double r1, r2;
:
p = &r1; p = &r2;
x.
, vectorSum() 9.3:
double vectorSum( const double* x, int n, int from, int upto )
{
int m;
double sum( 0 );

for ( m = from; m <= upto; m = m + 1 )


sum = sum + x[m];
return sum;
} // vectorSum
, :
double vectorSum( const double x[], int n, int from, int upto )
. , .
:
1.
:
double vectorSum( const double x[], int n, int from, int upto )
{
double sum( 0 );

for ( int m(from); m <= upto; ++m ) sum += x[m];


return sum;
} // vectorSum
2. .
(-
) .
-
.
, ,
- .
- .
C
'\0'
.
9.3 : -
[ ]; vectorSum() [
] .
. vectorSum() :
double vectorSum( const double* x, int n )
{
318 12

double sum( 0 );

for ( int m(0); m < n; ++m ) sum += x[m];


return sum;
} // vectorSum
, x[4], x[5],
x[6], x[7], x[8].
:
cout << vectorSum( &x[4], 5 ) << endl;
, x[4].
:
C++ ( C)1. (const double
x[], int n) (int from, int upto) .

12.2 const
, double x[] = {...}: x
[...] x. ,
:
double r1;
x = &r1 .
,
(2.4):
const double g( 9.81 ); // m/sec
g = 5.32.
,
, const
9.3, - :
double vectorSum( const double x[], int n, int from, int upto )
: const double* x.
, , ,
: (
).
:
double* const x( &r1 );
, :
const double* const x( &g );
. -

.

12.2.1 const
9.5.1. linSearch() ( )
const int v[] int v[]
:
v[upto+1] = x; //
// . . .

1 ... , .
I - 319

v[upto+1] = save; //
const int v[] const int* v
:
int* ncv( v );
ncv int, v, const. ncv
v v .
-
. const:
int* ncv( const_cast<int*>(v) );
: ncv v, , const
(const_cast<int*>) .
linSearch():
0: int linSearch( const int v[], int n,
1: int from, int upto, int x )
2: {
3: int fv( -1 );
4:
5: if ( 0 <= from && from <= upto && upto < n )
6: {
7: int* ncv( const_cast<int*>(v) );
8: int save( v[upto+1] ); // v[upto+1]
9: ncv[upto+1] = x; //
10: int k( from );
11: while ( v[k] != x ) ++k;
12: if ( k <= upto )
13: fv = k;
14: ncv[upto+1] = save; //
15: // (from <= fv <= upto && v[fv] == x) ||
16: // (fv == -1 && ( j:from..upto v[j] != x))
17: }
18: return fv;
19: } // linSearch
:
(. 0) int v[] int* v. ,
.
save (. 8) k (. 10)
.
. 7 ncv const.
, . 9 . 14 ncv[upto+1]
v[upto+1].
const
const ( volatile). ,
-
. , .
. -
:
double xf[100];
// xf
const double* x( const_cast<const double*>(xf) );
, x, -
. xf
.
o :
const double x[100] = { 0 };
double* xf( const_cast<double*>(x) );
320 12

// xf
xf = 0;
xf x,
const. , 0
x. 0 .
const
volatile
.

12.3
:
, . , x+1,
x+2,... x[1], x[2],... (*(x+1),
*(x+2),...) :
cout << (*x) << " " << (*(x+1)) << " " << (*(x+2)) << endl;
:
0.1 1.2 2.3
: -
.
cout << (*x+1) << " " << (*(x+1)) << endl;
:
1.1 1.2
1.1 : *x+1
x[0]+1.
:
T x[N];
k 0 N-1, :
x[k] == *(x + k)
: *(x+k)
( -l). :
*(x+3) = 7.77;
x[3].
-
:
double sum( 0 );
for ( int m(0); m < N; ++m ) sum += x[m]; //
.
- p double. p
: p = x. *p x[0]. p
1 (p=p+1 ++p) p x[1] (*p)
. . 12-2. :
double sum( 0 );
for ( double* p(x); p != &x[N]; ++p ) sum += *p;
: p *p double.
x[0] x (p(x)).
(++p)
(&x[N]). for -
.
I - 321

p = x;

...
x[0] x[1] x[2] x[9]

x p

p = p+1;

...
x[0] x[1] x[2] x[9]

x p

p = p+1;

...
x[0] x[1] x[2] x[9]

x p

. 12-2 . (x) -
(x[0]). ,
x[0], x 0x0064fdbc ( -
),. p = x
p. p 1 (p=p+1) p
(x[1]). p
1 p (x[2]) ....

! -.

12.3.1
:
&x[N]. ; 0
N-1. ! C++ x[N] (past the end
pointer), :
.
(..: p != &x[N])

12.3.2
double* p(x). -
- .
:
- p1 double*: double* p(p1),
p p1 (p == p1 *p *p1
)
, : double* p(x) , p
(p == &x[0])
, ..: double* p(&sum), p -
sum (p == &sum *p sum).
, :
(0): double* p( 0 ),
322 12

, ..: double* p(x+1).


!
const T* T*, ..:
int a[17];
const int* pa( a );
. ,
..:
unsigned int myStrLen( const char* cs )
{
char* p( const_cast<char*>(cs) );
// . . .
( .)
, -
.
. ,
. (0)2 :
-,
( ): ( )

(if (p == 0)...), .
, ,
. 0
- . :
p = p1;
p = x;
p = &sum;
p = 0;
p = x + 1;
, , 12.2, xf x
xf = 0.
const,
.
: :
int a( 10 ), b( 20 );
int* pa;
int* pb;
:
pa = &a; pb = &b;
. 12-3(): pa
a, 10, pb b 20.
a = b. . 12-
3 (). a 20, .
, (), :
pa = pb. a b , -
pa: pa pb: b (. 12-3 ()).
, , :
cout << *pa << " " << *pb << endl;

2 C 0 () NULL
#define NULL 0. B. Stroustrup 0.
C++11 (std::)nullptr.
I - 323

a 10 b 20 a 20 b 20 a 10 b 20

pa pb pa pb pa pb

() () ()
. 12-3 , pa = &a; pb = &b;
(). ()
: a = b. () , (),
pa = pb.

:
20 20
:
. , :
double v;
3: pa = &v.
!

. :
int* pa;
int* pb;
, :
int *pa, *pb;
:
int* pa, pb;
pa int pb int!

12.3.3
:
const unsigned int N = ...;
T x[N];
o : +: T*int y T* -: T*int y T* , :
+: [ &x[0] .. &x[N] ] [-N .. N] y [ &x[0] .. &x[N] ]
+: [-N .. N] [ &x[0] .. &x[N] ] y [ &x[0] .. &x[N] ]
-: [ &x[0] .. &x[N] ] [-N .. N] y [ &x[0] .. &x[N] ]
-: [-N .. N] [ &x[0] .. &x[N] ] y [ &x[0] .. &x[N] ]
p x[0] .. x[N-1],
p+1 . , p
x[1] .. x[N], p-1 .
, p x[0] .. x[N-1],
p + k (k: ) k
p.
p - k (k: ) k
p.

3 , ,
( "" );
324 12

!
1. .
.
2. p p + 1
(.. ). -
.
; , , p
x[2] p6 p+(-5).
-

.
++, --, +=, -=
. , p x[2] ++p
p x[3] ( --p x[1]). p +=
2, p x[2] x[4].
() :
-: [ &x[0] .. &x[N] ] [ &x[0] .. &x[N] ] [-N .. N]
, p1, p2, , x[k1] x[k2],
p1-p2, -
k1k2.
.
1 C
. 10 (10.13), C
char ( ) '\0'. -
C strlen() -
. , myStrLen().
l cs
cs[l], :
size_t myStrLen( const char cs[] )
{
unsigned int l( 0 );
while ( cs[l] != '\0' ) ++l;
return l;
} // myStrLen
, :
size_t myStrLen( const char cs[] )
{
const char* p( cs );
while ( *p != '\0' ) ++p;
return p-cs;
} // myStrLen
p cs[0] ( &cs[0]
cs). , ; const char* p(cs)! -
, 12.2. -
.
const :
char* p(cs) cs const char. const
:
char* p( const_cast<char*>(cs) );
p ++p (*p != '\0').
I - 325

, -
.
C
++:
size_t myStrLen( const char cs[] )
{
unsigned int l( 0 );
while ( cs[l++] != '\0' );
return l-1;
} // myStrLen
l cs[l] -
l. , ()
while, l ,
. l-1.
; :
size_t myStrLen( const char cs[] )
{
const char* p( cs );
while ( *(p++) != '\0' );
return p-cs-1;
} // myStrLen
++ . ,
1.
, C -
:
size_t myStrLen( const char cs[] )
{
const char* p( cs );
while ( *(p++) );
return p-cs-1;
} // myStrLen

2 C
10.13 strcat: strcat(a, b)
a.append(b): a b.
:
char* strcat( char* dest, const char* src )
strcat, dest src, -
dest.
myStrCat :
char* myStrCat( char* dest, const char* src )
{
int j( 0 );
while ( dest[j] != '\0' ) ++j;
int k(0); // : dest[j] == '\0'
while ( src[k] != '\0' )
{
dest[j] = src[k];
++j; ++k;
} // for
dest[j] = '\0';
return dest;
} // myStrCat
. , , -
.
:
326 12

char* myStrCat( char* dest, const char* src )


{
char* pd( dest );
while ( *(pd++) != '\0' );
--pd; // pd
const char* ps( src );
while ( *ps != '\0' )
{
*pd = *ps;
++pd; ++ps;
}
*pd = '\0';
return dest;
} // myStrCat
--pd; ...

12.3.4 ptrdiff_t
. 1 , C++,
size_t.

-: [ &x[0] .. &x[N] ] [ &x[0] .. &x[N] ] [-N .. N]
std::ptrdiff_t (pointer difference) . cstddef ( stddef.h)
:
typedef int ptrdiff_t;
.
return p-cs ptrdiff_t.
size_t.

12.3.5
(==)
(!=). , for : p != x+N p !=
&x[N].
.
.
.

vectorSum . , n 0, from /
upto 0..n-1. .
: , vectorSum
0 (), . n == 0 -
. n > 0 -
. :
double vectorSum( const double x[], int n, int from, int upto )
{
if ( x == 0 && n > 0 )
{ cerr << " vectorSum " << endl;
exit( EXIT_FAILURE ); }
//
double sum( 0 );
for ( int m(from); m <= upto; ++m ) sum += x[m];
return sum;
} // vectorSum
I - 327

12.4
:
typedef int intArr [ 51 ];
:
intArr mat [ 11 ];
mat, .. mat[7]; 51
int. 23 ;
mat[7] 23 :
(mat[7])[23]. C++ : mat[7][23].
mat :
int mat[ 11 ][ 51 ];
mat (two-dimensional array) 1151
int.
, ,
. , pinA, pinB, pinC pinD,
, , , -
.
int pinA[ 10 ];
char pinB[ 10 ][ 30 ];
double pinC[ 5 ][ 10 ][ 20 ];
bool pinD[ 5 ][ 10 ][ 20 ][ 8 ];
pin 10 int,
pinB 300 (= 1030) char,
pinC 1000 (= 51020) double
pinD 8000 (= 510208) bool.
,
:
) pinB[1][1], pinB[1][29], pinB[2][1], pinB[2][29],
pinB[9][1], pinB[9][29]
) pinC[1][1][1], pinC[5][1][1], pinC[1][9][1],
pinC[1][1][19], pinC[5][9][19]
) pinD[1][1][1][1], pinD[1][1][1][2], pinD[4][9][19][7],
pinD[4][9][19][8]
. , , -
()
:
double x[4][2] = { {0.1, 1.2}, {2.3, 3.4}, {4.5, 5.6},
{6.7, 7.8} };
, !
; x[0], x[3]. :
for ( int r(0); r < 4; ++r )
cout << x[r] << " " << &x[r][0] << endl;
:
0x22ff30 0x22ff30
0x22ff40 0x22ff40
0x22ff50 0x22ff50
0x22ff60 0x22ff60
328 12

, x[r] x[r][0].
C++ :
0, 1 .
-
. -
. -
.
:
1 -
:
double pinC[ 5 ][ 10 ][ 20 ];
for , sum,
pinC:
sum = 0;
for ( int k(0); k < 5; ++k ) // ETEPIKH
{
for ( int l(0); l < 10; ++l ) // ENIAMEH
{
for ( int m(0); m < 20; ++m ) // ETEPIKH
{
sum += pinC[k][l][m];
} // for ( int m . . .
} // for ( int l . . .
} // for ( int k . . .
, , m,
for. m
, . 0 19,
k l (. 50 ). , for 1000 (=2050)
. , k (
0 4), l 5 ( 0 9). , for
5 .
:
sum = 0;
for ( int m(0); m < 20; ++m ) // ETEPIKH
{
for ( int l(0); l < 10; ++l ) // ENIAMEH
{
for ( int k(0); k < 5; ++k ) // ETEPIKH
{
sum += pinC[k][l][m];
} // for ( int k . . .
} // for ( int l . . .
} // for ( int m . . .
, , k,
200 , . 0 4. m
(0 19) l 20 ( 0 9).
, :
sum = 0;
for ( int m(19); m >= 0; --m ) // ETEPIKH
{
for ( int l(9); l >= 0; --l ) // ENIAMEH
{
for ( int k(4); k >= 0; --k ) // ETEPIKH
{
sum += pinC[k][l][m];
} // for ( int k . . .
} // for ( int l . . .
I - 329

} // for ( int m . . .
,
.

2 -
: , -
ins, :
double a[ 5 ][ 7 ];
. ;
() . 1
0 , 2
1 ... ;
for ( int r(0); r < 5; ++r )
{
for ( int c(0); c < 7; ++c )
{
ins >> a[r][c];
} // for ( int c . . .
} // for ( int r . . .
r
r . :
for ( int c(0); c < 7; ++c )
{
ins >> a[r][s];
} // for ( int s . . .
() for.
, . -
, ()
:
for ( int c(0); c < 7; ++c )
{
for ( int r(0); r < 5; ++r )
{
cin >> a[r][c];
} // for ( int r . . .
} // for ( int c . . .
,
for ( int r(0); r < 5; ++r )
{
cin >> a[r][c];
} // for ( int r . . .
c .


(. 8-4).
3 -
:
( )
arc == acr.
double a[N][N];
( N int ) :
symmet = true;
for ( int r(0); r < N; ++r )
330 12

{
for ( int c(0); c < N; ++c )
{
if( a[r][c] != a[c][r] ) symmet = false;
} // for ( int c . . .
} // for ( int r . . .
, a (symmet = true)
arc, acr arc acr
symmet false.
,
:
, .. a23 a32,
a32 a23, .

.
-
. r
arr, :
symmet = true;
for ( int r(0); r < N; ++r )
{
for ( int c(r+1); c < N; ++c )
{
if( a[r][c] != a[c][r] ) symmet = false;
} // for ( int c . . .
} // for ( int r . . .
if( a[r][c] !=
a[c][r] )... N(N-1)2 , 2
.
: arc, acr arc acr,
.
:
symmet = true;
for ( int r(0); symmet && r < N; ++r )
{
for ( int c(r+1); symmet && c < N; ++c )
{
if ( a[r][c] != a[c][r] ) symmet = false;
} // for ( int c . . .
} // for ( int r . . .
,
,
.
for , -
break:
symmet = true;
for ( int r(0); r < N; ++r )
{
for ( int c(r+1); c < N; ++c )
{
if ( a[r][c] != a[c][r] )
{ symmet = false; break; }
} // for ( int c . . .
if ( !symmet ) break;
} // for ( int r . . .
I - 331

break for. -
break
symmet false.
for .
goto,
:
symmet = true;
for ( int r(0); r < N; ++r )
{
for ( int c(r+1); c < N; ++c )
{
if ( a[r][c] != a[c][r] )
{ symmet = false; goto lb99; }
} // for ( int c . . .
} // for ( int r . . .
lb99: .....
goto
. , :
lb99 for
.
, for,
( r c).
. -
,
.

4 -
a l m ,
b m n .
c, l n .
c, r c (crc), ,
, :
m 1
c rc a rk b kc
k 0

: r = 0..l-1, c = 0..n-1.
, crc arkbkc, k
0..m-1.
C++ for :
c[r][c] = 0;
for ( int k(0); k < m; ++k )
c[r][c] += a[r][k]*b[k][c];
a b,
, . c
c ( a b), :
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
const int l = 3, m = 5, n = 2;

int a[ l ][ m ], b[ m ][ n ];
int c[ l ][ n ];
332 12

ifstream atx( "arr.txt" );


// a
for ( int r(0); r < l; ++r )
for ( int c(0); c < m; ++c ) atx >> a[r][c];
// b
for ( int r(0); r < m; ++r )
for ( int c(0); c < n; ++c ) atx >> b[r][c];
atx.close();

//
for ( int r(0); r < l; ++r )
{
for ( int c(0); c < n; ++c )
{
c[r][c] = 0;
for ( int k(0); k < m; ++k )
c[r][c] += a[r][k]*b[k][c];
} // for (c . . .
} // for (r . . .

// a, b, c
cout << " a" << endl;
for ( int r(0); r < l; ++r )
{
for ( int c(0); c < m; ++c )
{
cout.width(3); cout << a[r][c] << " ";
}
cout << endl;
}
cout << " b" << endl;
for ( int r(0); r < m; ++r )
{
for ( int c(0); c < n; ++c )
{
cout.width(3); cout << b[r][c] << " ";
}
cout << endl;
}
cout << " c" << endl;
for ( int r(0); r < l; ++r )
{
for ( int c(0); c < n; ++c )
{
cout.width(3); cout << c[r][c] << " ";
}
cout << endl;
}
}

:
1 2 3 4 5
6 7 8 9 1
1 4 7 2 5
10 10
12 45
47 18
12 31
18 29
"arr.txt" ( text).
:
a
1 2 3 4 5
6 7 8 9 1
1 4 7 2 5
I - 333

b
10 10
12 45
47 18
12 31
18 29
c
313 423
646 827
501 523

12.5
,
. , -
, . .
, -
. .
:
double a[5][7];
a[0][0]. a[0][1],
a[0][2] ... a[0][0]
0, a[0][6]. a[1][0],
1. , a[r][c] 7r + c a[0][0].
:
, 12.3.2,
, ,
double ( 8 ).
.
a :
for ( int r(0); r <= 4; ++r )
{
for ( int c(0); c <= 6; ++c )
{
a[r][c] = r + 0.1*c;
} // for ( int c . . .
} // for ( int r . . .
, ( 4) : 4.0, 4.1, 4.2, 4.3, 4.4,
4.5, 4.6.
, a . :
double* p;
:
p = &a[0][0];
C++ ,
p , double, a[0][0].
a! p a
.
, 4 a -
74 + 0 74 + 6 a[0][0].
p:
r = 4;
for ( int c(0); c <= 6; ++c )
{
334 12

cout << p[r*7+c] << " ";


}
cout << endl;
; :
4 4.1 4.2 4.3 4.4 4.5 4.6
:
T a[Nr][Nc];
:
a[r][c] rNc + c ( T) a[0][0].

12.5.1
, :
T a[N1][N2]...[Nm];
:
a[k1][k2]...[km]
(...(k1N2 + k2)N3 + ... + km-1)Nm + km
( T) a[0][0]...[0].
:
#include <iostream>
using namespace std;
int main()
{
int a[2][2][2];
int* ip;

for ( int l(0); l < 2; ++l )


for ( int r(0); r < 2; ++r )
for ( int c(0); c < 2; ++c )
a[l][r][c] = 100*(l+1) + 10*(r+1) + c+1;
ip = &a[0][0][0];
for ( int k(0); k < 8; ++k )
cout << ip[k] << " ";
cout << endl;
}
:
111 112 121 122 211 212 221 222
, l(+1),
1. l = 0
l = 1. r = 0
l = 0.
a[1][0][1], 212, ip[((12 + 0)2 + 1],
ip[5].
a[1][0] ; a[1];
:
for ( int l(0); l < 2; ++l )
{
cout << a[l] << " " << &a[l][0][0] << endl;
for ( int r(0); r < 2; ++r )
cout << " " << a[l][r] << " " << &a[l][r][0] << endl;
}
:
0x22ff50 0x22ff50
0x22ff50 0x22ff50
I - 335

0x22ff58 0x22ff58
0x22ff60 0x22ff60
0x22ff60 0x22ff60
0x22ff68 0x22ff68
: a[l] a[l][0][0] a[l][r]
a[l][r][0].

12.6 ()
:
typedef char ProSthlh[13];
.
..:
ProSthlh c;
:
c[0] = '1'; c[1] = '1'; c[2] = 'X';...
c[11] = 'X'; c[12] = '2';
, , N ,
:
ProSthlh deltio[N];

, , (
11 ).
:
int winners( ProSthlh deltio[], int N, ProSthlh nik )
{
int es, ne;

es = 0; // 11
for ( int k(0); k < N; ++k )
{
ne deltio[k]
if ( ne >= 11 ) ++es;
} // for
return es;
} // winners
ne deltio[k] :
ne = 0;
for ( int j(0); j <= 12; ++j )
if ( deltio[k][j] == nik[j] ) ++ne;
:
int winners( ProSthlh deltio[], int N, ProSthlh nik )
{
int es, ne;

es = 0; // 11
for ( int k(0); k < N; ++k )
{
// ne deltio[k]
ne = 0;
for ( int j(0); j <= 12; ++j )
{
if ( deltio[k][j] == nik[j] ) ++ne;
} // for ( int j . . .
if ( ne >= 11 ) ++es;
} // for ( int k . . .
return es;
336 12

} // winners
; main:
ProSthlh c, d[138];
:
cout << winners(d, 138, c) << endl;
(;) , -
: . -
ProSthlh ;
int winners2( char deltio[][13], int N, char nik[] )
{
int es, ne;

es = 0; // 11
for ( int k(0); k < N; ++k )
{
// ne deltio[k]
ne = 0;
for ( int j(0); j <= 12; ++j )
if ( deltio[k][j] == nik[j] ) ++ne;
if (ne >= 11) ++es;
} // for ( int k...
return es;
} // winners2
- :
(13) , . -
.
main:
char c[13], d[138][13];
:
cout << winners2(d, 138, c) << endl;
. .


. ; -
. . .

a
double true a false .
:
N .
a[r][c] a[r*n+c].
bool isSymmetric( const double* a, int n ) // double a[n][n]
{
bool symmet( true );

for ( int r(0); r < n; ++r )


{
for ( int c(r+1); c < n; ++c )
{
// if ( a[r][c] != a[c][r] ) { symmet = false; break; }
if ( a[r*n+c] != a[c*n+r] ) { symmet = false; break; }
} // for ( int c . . .
if ( !symmet ) break;
} // for ( int r . . .
return symmet;
} // isSymmetric
I - 337

. :
double p1[2][2] = { {1,2}, {3,4} },
p2[3][3] = { {1, 0, 1.5}, {0, 1.8, 2}, {1.5, 2, 4.1} };
p1 p2
:
if ( isSymmetric(&p1[0][0], 2) ) cout << " p1 " << endl;
else cout << " p1 " << endl;
if ( isSymmetric(&p2[0][0], 3) ) cout << " p2 " << endl;
else cout << " p2 " << endl;


-
. . 4

12.6.1
. 9-6 rawSum()
r1
r1.
: ,
vectorSum! ,
double a[5][7], z;
2 :
z = vectorSum( a[2], 7, 0, 6 );

z = vectorSum( &a[2][0], 7, 0, 6 );
C++/C -
. . 9-6 .
.
:
double p3[6][9] = { {1, 2, 4, 0, 5, 2, 7, 9, 0},
{2, 2, 0, 3, 4, 5, 9, 7, 8},
{4, 0, 2, 6, 3, 4, 0, 5, 7},
{3, 4, 8, 3, 5, 7, 0, 4, 1},
{4, 5, 1, 4, 7, 9, 0, 5, 7},
{1, 1, 5, 0, 0, 0, 8, 8, 6} };
() p3[0][0] p3[2][2]
p3[2][3] p3[5][6] .
isSymmetric(&p3[0][0], 3) isSymmetric(&p3[2][3], 4); !
isSymmetric -
:

) ) .
isSymmetric :
bool isPartSymmetric( const double* a, int nRow, int nCol,
int rUL, int cUL, int rLR, int cLR )
: , ,
.
: (rUL) (cUL) -

4 .
338 12

(rLR) (cLR) . -
:
. . . isPartSymmetric( &p3[0][0], 6, 9,
0, 0, 2, 2 ) . . .

. . . isPartSymmetric( &p3[0][0], 6, 9,
2, 3, 5, 6 ) . . .

12.7 main
mainargs.exe. -
:
D:\>mainargs<enter>
, -
, .
; !
mainargs.exe :
#include <iostream>
using namespace std;
int main( int argc, char* argv[] )
{
cout << " argc " << argc << endl;
cout << " int main:"
<< endl;

for ( int k(0); k <= argc; ++k )


cout << " argv[" << k << "]: " << argv[k] << endl;
} // main

main.
C-style string char** argv.
(+1)
.
char* argv[]; ,
char*. , -
char; , -
. .
,
. : :
E:\cpp2bk\progs>mainargs 1 a\b " 3" 4 5.5 c\d?'ef<enter>
:
argc 7
int main:
argv[0]: mainargs
argv[1]: 1
argv[2]: a\b
argv[3]: 3
argv[4]: 4
argv[5]: 5.5
argv[6]: c\d?'ef
argv[7]:
argv:
argv[0] ()
( (path) ).
I - 339

argv[1] ,
( : 1).
argv[k] k- .
argv[argc-1] ( ).
argv[argc] : () 0.
, - .
3, . '
: " 3".

12.8 ...
.
( )
( ).
.
( )
.

. :

) ) .


12-1 ; ( , )
#include <iostream>
using namespace std;

int qaw( int* p )


{
*p = 5;
return *p;
} // qaw

int main()
{
int x( 0 );
cout << " the value of x is " << x << endl;
int y( qaw(&x) );
cout << " the new value of x is " << x << endl;
cout << " the value of y is " << y << endl;
} // main
12-2 :
#include <iostream>
using namespace std;
int main()
{
char a[] = "abcdefgh";
for ( char* p(a); *p != 0; ++p ) cout << p << endl;
} // main
340 12

12-3 .
() (trace) . -
trace .
12-4 trace2 -
-
.
12-5 c1, c2 -
. r1, r2.
12-6 rawSum() -
r1
r1.
colSum() c1.
12-7 isDiagonal() -
true
( ).

B
12-8 . 9-2 :
h
gh
fgh
efgh
defgh
cdefgh
bcdefgh
abcdefgh
.: , -
.
12-9 periphSum() -
nR nC
( 0 nR-1 0 nC-
1.)
12-10 matrix2Sum() -

.
matrix3Sum() -
.
.
12-11 ()
:
,
.


12-12 k
k .
r c r c.
I - 341

12-13 isPartSymmetric() 12.6.1.


342 12

13
I -
:
-
C++ -
void.
.
:

.
:
void
-
- (pointer)
-
- /

--


:
13.1 ..................................................................................................................... 344
13.2 I .................................................................................................. 346
13.3 II ................................................................................................. 348
13.3.1 unsigned; () ......................................................................................................................350
13.4 ....................................................................................................................................... 350
13.5 return () ........................................................................................................................ 353
13.6 ................................................................................................ 353
13.6.1 * ........................................................................................................................................357
13.6.2 ............................................................................................................358
13.7 * () ................................................................................................. 359
13.8 C () .................................................................................................................. 360
13.9 ............................................................................................ 362
13.9.1 ...............................................................................................................................................363
13.9.2 ..........................................................................................................................................364
13.9.3 ......................................................................................................................................................365
13.10 ..................................................................................................................... 370
13.11 ! ........................................................................................................................ 371
13.11.1 ....................................................................................................................374
13.11.2 E ....................................................................................................................................................376

343
344 13

13.11.3 ..........................................................................................................................................382
13.11.4 ..................................................................................................................................382
13.12 ........................................................................................................... 383
................................................................................................................................................................... 385
.............................................................................................................................................................................385
.............................................................................................................................................................................385
.............................................................................................................................................................................386

:
. 9-1; :
#include <iostream>
using namespace std;

int qaw( int* p )


{
*p = 5;
return *p;
} // qaw

int main()
{
int x( 0 );
cout << " the value of x is " << x << endl;
int y( qaw(&x) );
cout << " the new value of x is " << x << endl;
cout << " the value of y is " << y << endl;
} // main
H qaw int. qaw
int y( qaw(&x) ) x p.
*p 5 x.
, :
the value of x is 0
the new value of x is 5
the value of y is 5

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

13.1
2.7 :
h o . o
o oo o h oo
:
) o
) .
o o . : g = 9.81 m/sec2.
:
I - 345

h
o tP, vP
tP, vP
.
: ,
main , ;
.
. -
tP vP (
). , :
, ;
, , ..:
int displayResults( double h, double t, double v )
{
cout << " o = " << h << " m" << endl;
cout << " o = " << t << " sec" << endl;
cout << " o = "
<< v << " m/sec";
return 0;
} // displayResults
. C++ -
:
void displayResults( double h, double t, double v )
{
cout << " o = " << h << " m" << endl;
cout << " o = " << t << " sec" << endl;
cout << " o = "
<< v << " m/sec" << endl;
} // displayResults
void .1
; , :
int main()
{
const double g( 9.81 ); // m/sec2,

double h, // m, o
tP, // sec, o
vP; // m/sec, o

// o h
cout << " o o o m: "; cin >> h;
if (h >= 0) { // o tP, vP
// (g == 9.81) && (0 h DBL_MAX)
tP = sqrt((2/g)*h);
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))

displayResults( h, tP, vP );
}
else
// false
cout << " " << endl;
} // main

1 , . C++ void
.
346 13

main

h 80 tP ??? vP ???

&tP &vP

compute

h 80 t v

. 13-1 compute main. h


main h compute(). -
- t - &tP. t -
tP main, *t tP,
*t -
tP. *v vP.

13.2 I
, , compute,
(h) tP, vP.
: , -
! ! ;
; ; -
: -! , -
:
void compute( double h, double* t, double* v )
:
compute( h, &tP, &vP );
void; -
. .
, . 13-1, : h main
h compute(). &tP
t compute(). &tP;
tP main. , , t compute(),
(double* t), tP main.
vP v. , compute(), *t *v -
tP vP ! :
void compute( double h, double* t, double* v )
{
const double g = 9.81; // m/sec2,

// (g == 9.81) && (0 h DBL_MAX)


*t = sqrt((2/g)*h);
*v = -g*(*t);
// (*t (2h/g)) && (*v -(2hg))
} // compute
main:
int main()
{
double h, // m, o
tP, // sec, o
I - 347

vP; // m/sec, o

// o h
cout << " o o o m: "; cin >> h;
if ( h >= 0 )
{
compute( h, &tP, &vP );
displayResults( h, tP, vP );
}
else
// false
cout << " " << endl;
} // main
displayResults(), compute (void). -
, .
; :
,
(&tP &vP)
.
, inputH(),
main, .2
.
void inputH( double* h )
{
cout << " o o o m: "; cin >> *h;
if ( *h < 0 )
{ cout << " ! "; cin >> *h; }
} // inputH
:
#include <iostream>
#include <cmath>
using namespace std;

void inputH( double* h )


//
void compute( double h, double* t, double* v )
//
void displayResults( double h, double tP, double vP )
//

int main()
{
double h, // m, o
tP, // sec, o
vP; // m/sec, o

inputH( &h );
if ( h >= 0 )
{
compute( h, &tP, &vP );
displayResults( h, tP, vP );

2 , inputH() :
double inputH()
{
double locH;
cout << " o o o m: "; cin >> locH;
if ( locH < 0 )
{ cout << " ! "; cin >> locH; }
return locH;
} // inputH
, , ... .
348 13

}
else
// false
cout << " " << endl;
} // main
, main
. -
, .
; ,
:
( 60 ). ,
:
. , .
.
.
, -
C.
C++. , C
.

13.3 II
, :
& -
-
, ,
.
(reference parameters).
,

,
-l, .. .
-
, , :
#include <iostream>
#include <cmath>
using namespace std;

void inputH( double& h )


{
cout << " o o o m: "; cin >> h;
if ( h < 0 )
{ cout << " ! "; cin >> h; }
} // inputH

void compute( double h, double& t, double& v )


{
const double g = 9.81; // m/sec2,

// (g == 9.81) && (0 h DBL_MAX)


t = sqrt( (2/g)*h );
v = -g*t;
// (t (2h/g)) && (v -(2hg))
} // compute
I - 349

main

h 80
tP vP

compute ??? ???

80 t v
h

. 13-2 compute(), (h
main) (h compute). -
: -
, tP, vP main.
(compute)
.
void displayResults(double h, double tP, double vP)
//

int main()
{
double h, // m, o
tP, // sec, o
vP; // m/sec, o

inputH( h );
if ( h >= 0 )
{
compute( h, tP, vP );
displayResults( h, tP, vP );
}
else
// false
cout << " " << endl;
} // main
compute():
void compute( double h, double& t, double& v )
t v double&. :
compute( h, tP, vP );

: tP, vP.
compute(): t v *t
*v .
inputH().
,
. , ' ,
.
, compute(),
( h) (
g) . : -
.
compute() tP : tP main t
compute(). , vP main v compute(). ,
-
. . 13-2.
:
tP vP main t v compute() .
350 13

:
,
void inputH( double& h )
:
int i;
double d;
:
inputH( d );
, h, double& , d,
double.
:
inputH( i );
, h, double& , i, int.
:
inputH( 1.0 + sqrt(d) );
, h, double& , 1.0 + sqrt(d),
.
, ,
.
-.
:
,
,
,
, -
, .

13.3.1 unsigned; ()
, , , 7.6:
unsigned int, unsigned
long int, unsigned short int, unsigned char , : int, long int,
short int, char. .
:
(-
).

13.4
, (reference type)
( ).
:
int x;
int& r( x );
; x r . ,
:
r = 10;
cout << " x = " << x << " r = " << r << endl;
x = 15;
I - 351

cout << " x = " << x << " r = " << r << endl;
:
x = 10 r = 10
x = 15 r = 15
, r(x) r x .
; ! -
:
int* p( &x );
*p = 10;
cout << " x = " << x << " *p = " << *p << endl;
x = 15;
cout << " x = " << x << " *p = " << *p << endl;
:
x = 10 *p = 10
x = 15 *p = 15
;
p &x x.
, p
(*p).
,
, .
.

maxNdx 9.3:
int& maxElmn( int x[], int n )
{
int mxP( 0 );

for ( int m(1); m < n; ++m )


{
if ( x[m] > x[mxP] ) mxP = m;
} // for (m

return x[mxP];
} // maxElmn
maxElmn
.
:
int& int. return
x[mxP], int.
int x[] const int x[].
.
; . :
int zm, z[] = { 12, 4, -3, 24, 33, 2, 4, 7 };
:
zm = maxElmn( z, 8 );
cout << zm << " " << maxElmnD(z, 8) << endl;
:
33 33
int int&.

352 13

const;
:
for ( int k(0); k < 8; ++k ) cout << z[k] << " ";
cout << endl;
maxElmn( z, 8 ) = 17;
for ( int k(0); k < 8; ++k ) cout << z[k] << " ";
cout << endl;
:
12 4 -3 24 33 2 4 7
12 4 -3 24 17 2 4 7
, maxElmn(z, 8) = 17 -
z[4]!
int& (-l)
. . ; :
const int& maxElmn( const int x[], int n )
!
; -
. , zm
= maxElmn(z, 8), :
mxP
return x[mxP] , ,
x[mxP].
, zm
.
int int& ; -
, return, x[mxP]
. :
T&
T
T T.
! T int. T
kB : -
T& !
.
! maxNdx :
int& maxPosD( const int x[], int n )
{
int mxP( 0 );

for ( int m(1); m < n; ++m )


{
if ( x[m] > x[mxP] ) mxP = m;
} // for (m

return mxP;
} // maxNdx
! : :
p = maxNdx( z, 8 );
return mxP mxP, -
.
p, mxP ! :
I - 353

13.5 return ()
7.2 : return
. return : -

.
, , -
, return; , .
-
.

(mnxy) (mxxy)
:
void minmax(int x, int y, int& mnxy, int& mxxy)
{
if (x < y) { mnxy = x; mxxy = y; return; }
mnxy = y; mxxy = x;
} // minmax
x < y mnxy = x; mxxy = y; ,
return mnxy = y; mxxy =
x;, , .
mnxy = y; mxxy = x; .

, return, , -
. -
.

13.6
. 7,
C++ .
main -
.
( ) -
. ,
. ,
.

(. ).
:
().
(
).

.
#include <iostream>
#include <cmath>
354 13

using namespace std;

const double g = 9.81; // m/sec2,

double h, // m, o
tP, // sec, o
vP; // m/sec, o

void inputH()
{
cout << " o o o m: "; cin >> h;
if ( h < 0 )
{ cout << " ! "; cin >> h; }
} // inputH

void compute()
{
// (g == 9.81) && (0 <= h <= DBL_MAX)
tP = sqrt( (2/g)*h );
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))
} // compute

void displayResults()
{
cout << " o = " << h << " m" << endl;
cout << " o = " << tP << " sec" << endl;
cout << " o = "
<< vP << " m/sec" << endl;
} // displayResults

int main()
{
inputH();
if ( h >= 0 )
{
compute();
displayResults();
}
else
// false
cout << " " << endl;
} // main
:

.
, , (global) -
.
; , , x x
; , x,
. x ::x.
:
int x;

void q( double x )
{
cout << x << " " << ::x << endl;
// . . .
} // q

int main()
{
// . . .
I - 355

x = 4; q( 2.5 );
// . . .
}
main, x 4 q -
2.5. x, q.
cout << x << " " << ::x << endl x
, ::x. ,
:
2.5 4
, , -
: ,
.
. -
11.1.
C++, (block) (compound statement),
, { }. ,
.
C++:
,
.

.
. :
#include <iostream>
using namespace std;
int main()
{ // 1
{ // 1.1
int x( 5 );
cout << "p2: x = " << x << endl;
}
cout << "p3: x = " << x << endl;
// . . .
:
Error line 9: Undefined symbol 'x' in function main()
; 9 (cout << "p3: x = " << x << endl) 1,
. x 1.1, '
cout << "p2: x = " << x << endl
9 (
8).

. .. :
#include <iostream>
using namespace std;
int main()
{ // 1
int y;

{ // 1.1
y = 19;
cout << "p1: y = " << y << endl;
}
cout << "p2: y = " << y << endl;
. . .
:
356 13

13.1

-
. -
( ) . -

.
:

(local)
(global). -

.



.
static
.

p1: y = 19
p2: y = 19
1.1 , y,
1. (p2: y = 19)
y 1.1
.
, x,
; , x
. , :
#include <iostream>
using namespace std;
int main()
{ // 1
int x( 1 );

cout << "p1: x = " << x << endl;


{ // 1.1
const int x( 5 );
cout << "p2: x = " << x << endl;
}
cout << "p3: x = " << x << endl;
}
:
p1: x = 1
p2: x = 5
p3: x = 1
p1: x = 1 : cout << "p1: x = "
<< x << endl, int x = 1, 1.
p2: x = 5 cout << "p1: x = " << x << endl
1.1. x x -
1. 1.1 x
x 1.
I - 357

p3: x = 1 : cout << "p3: x = "


<< x << endl, 1 int x = 1,
1.
:
, , . .. -
x 1 main. x
1.1 1.1
1.1.
1.1 x
1 1.1.
cout << "p3: x = " << x << endl, 1.1,
x .
. 13.1.
:
1.
.
2. , for.
-
-
.

; ! .

13.6.1 *

static, a
3:
double rnd01()
{
static double a( 0.13579246801357924680 );

cout << " rnd01 arxh: a = " << a << endl;


a = 37*a;
a = a - static_cast<int>(a);
cout << " rnd01 telos: a = " << a << endl;
return a;
} // rnd01
:
double f( double x )
{
double z;

cout << " f arxh: z = " << z << endl;


z = pow( x, 0.25 );
cout << " f telos: z = " << z << endl;
return x + z;
} // f
, z, static.

. :
for ( int k(1); k <= 3; ++k )

3 (0,1).
358 13

cout << k << " " << f(rnd01()) << endl;


:
rnd01 arxh: a = 0.135792
rnd01 telos: a = 0.0243213
f arxh: z = 4.97035e-219
f telos: z = 0.394909
1 0.41923
rnd01 arxh: a = 0.0243213
rnd01 telos: a = 0.899889
f arxh: z = 4.97035e-219
f telos: z = 0.973974
2 1.87386
rnd01 arxh: a = 0.899889
rnd01 telos: a = 0.295882
f arxh: z = 4.97035e-219
f telos: z = 0.73753
3 1.03341
, rnd01, a 0.0243213
.
f, , z 0.394909
4.97035e-219.
; z (automatic) -
f . a
rnd01
.
:
(default) .
C++ 0 ().

13.6.2
. -


.
.
.
. ,
.
.
.
:
.
:
.
, -
:
:
.
I - 359

13.7 * ()
7.9
.
(void) .
:
1
minmax() x, y
:
void minmax( int x, int y, int& mnxy, int& mxxy )
{
if ( x < y )
{
mnxy = x; mxxy = y;
}
else
{
mnxy = y; mxxy = x;
}
} // minmax
:
minmax( a, b, p, q );
; a, b ,
p q.
minmax():
// true
minmax( a, b, p, q );
// ((p == a && q == b) || (p == b && q == a)) &&
// (p <= a && p <= b) && (q >= a && q >= b)
, , x, y,
a, b, mnxy, mxxy -
p, q. , :
// true
if (x < y)
{
mnxy = x; mxxy = y;
}
else
{
mnxy = y; mxxy = x;
}
// ((mnxy == x && mxxy == y) || (mnxy == y && mxxy == x)) &&
// (mnxy <= x && mnxy <= y) && (mxxy >= x && mxxy >= y)
-
. , .

2
swap(), ( int)
:
void swap( int& x, int& y )
{
int s( x );
x = y; y = s;
} // swap
swap(); (
. 3):
360 13

// a == a0 && b == b0
swap( a, b );
// a == b0 && b == a0
:
// x == a0 && y == b0
int s( x ); x = y; y = s;
// x == b0 && y == a0

-
-
. -
.
, void p, n , v1, v2,... vn
m r1, r2,... rm. r1, r2,... rm
r1, r2,... rm , p
:
// Pd(p1, p2,... pn, q1, q2,... qm) &&
// (q1 == r1) && (q2 == r2) && ... (qm == rm)
p(v1, v2,... vn, r1, r2,... rm);
// Qd(p1, p2,... pn, r1, r2,... rm, q1, q2,... qm)
,
. -
, :
void p(T1 v1, T2 v2,... Tn vn, Tr1& r1, Tr2& r2,... Trm& rm)
{
// Pd(v1, v2,... vn, r1, r2,... rm) &&
// (r1 == r1) && (r2 == r2) && ... (rm == rm)
:
// Qd(v1, v2,... vn, r1, r2,... rm, r1, r2,... rm)
} // p

13.8 C ()
,
. 10.13.1
, , strtod() strtol() .
.
:
d = strtod( s3, &p );
s3 char* p. s3
, d p () 0. -
p ()
.
:
double d;
char s1[] = "12345", s2[] = "1.23456789e10",
s3[] = "1.23ab45678";
char* p;
:
d = strtod( s2, &p );
if ( p != 0 ) cout << d << " " << p << endl;
else cout << d << endl;
d = strtod( s3, &p );
if ( p != 0 ) cout << d << " " << p << endl;
I - 361

else cout << d << endl;


:
1.23457e+010
1.23 ab45678
strtod() ( cstdlib); :
double strtod( const char* s, char** endptr );
: -
. ; , 0
(NULL) . 13.2 C
: T, T*

.
char* (char*)*. -

p ( char*). p, &p.
, .
strtod() :
float strtof( const char* s, char** endptr );
long double strtold( const char* s, char** endptr );
atof() (10.13.1)
double atof( const char* s )
{ return strtod( s, NULL ); }
strtol(), :
long strtol( const char* s, char** endptr, int radix )
,
.
.. :
l = strtol( "11", &p, 2 ); cout << l << endl;
l = strtol( "11", &p, 8 ); cout << l << endl;
l = strtol( "11", &p, 10 ); cout << l << endl;
l = strtol( "11", &p, 16 ); cout << l << endl;
:
3
9
11
17
(3 = 2 + 1, 9 = 8 + 1, 11 = 10 + 1, 17 = 16 + 1)
, :
long int l( strtol(s1, &p, 10) );
if ( p != 0 ) cout << l << " " << p << endl;
else cout << l << endl;
l = strtol( s2, &p, 10 );
if ( p != 0 ) cout << l << " " << p << endl;
else cout << l << endl;
:
12345
1 .23456789e10
: -
p:
0 , -
.
362 13

0 -
. p (*p).
(overflow)!
;
errno.
#include <cerrno>.
strtod() DBL_MAX
HUGE_VAL ( cmath) errno ERANGE (
cerrno).
strtod() -DBL_MAX
-HUGE_VAL errno ERANGE.4

errno = 0;
d = strtod( s2, &p );

(d == HUGE_VAL || d == -HUGE_VAL) && errno == ERANGE
d.
,
errno = 0;
l = strtol(s2, &p, 10)

(l == LONG_MAX || l == LONG_MIN) && errno == ERANGE
true l.
errno .
strtol()
long long int strtoll( const char* s, char** endptr, int base );
unsigned long int strtoul( const char* s, char** endptr,
int base );
unsigned long long int strtoull( const char* s, char** endptr,
int base );
atol() (10.13.1), atoi(), atoll()
long int atol( const char* s )
{ return strtol( s, NULL, 10 ); }
int atoi( const char* s )
{ return int( strtol(s, NULL, 10) ); }
long long int atoll( const char* s )
{ return strtoll( s, NULL, 10 ); }

13.9
, ,
, ... ;
.
(-) (-
) .
:
.

4 strtof HUGE_VALF HUGE_VALF strtold


HUGE_VALL HUGE_VALL.
I - 363


:


, !
.
1 :

.
:
.
, , :
(),
(),
( ).
:
2 :

.
()
.

.
.
3 :

(void).
.
2
:
-
.

13.9.1
. -
. Ada, , -
, :
in ,
out
in out .
Ada
C++ in !5

5 ;...
364 13

C : .
. -
.
C++ C : -
,
.
:
1. (value parameters) -
.
(in). -

.
2. (reference parameters)

. (out)
(in out).

( ).
3. - -.
, 9.4, in out.
.
in const.
-
. , , -
. ( T)
in,
( )
. -
(T&) const (const T&).
C
(pointers).
-
.

13.9.2
(11.6) / - ().
.
, (8.2),
(buffer), , -
( ). ,
,
. /

/ .

. ( x, r
):
cout << " x = " << x << " r = " << r << endl;
:
I - 365

(((((cout << " x = ") << x) << " r = ") << r) << endl);

.
: cout << " x = "
cout " x = ". ! :
(cout << " x = ") << x
(cout << " x = ") x;
, . cout << " x = "
cout.

().
: (cout << " x = ") x
: cout << " x = "
" x = " , x.
:
main
ofstream tout( "afile.txt" );
tout:
afunction( tout, . . . );
tout ,
tout main .
main tout
afunction!
; :
/ ( )
in out ().
:
void afunction( ofstream& tout, . . . ) { . . . }
:
cout
ostream ofstream.
, cin
ifstream istream.
; 8.1

.
,
: .
void.

13.9.3

.
1
minmax x, y
.
:
(in) , x, y
366 13

(out) , mnxy, mxxy.


, 3
.
;
, x, y
, mnxy, mxxy.
:
void minmax( int x, int y, int& mnxy, int& mxxy )
{
if ( x < y )
{ mnxy = x; mxxy = y; }
else // x >= y
{ mnxy = y; mxxy = x; }
} // minmax

.
minmax() :
int min( int x, int y )
{
int fv( x );
if ( x > y ) fv = y;
return fv;
} // min
int max( int x, int y )
{
int fv( x );
if ( y > x ) fv = y;
return fv;
} // max
minmax() .

:
minmax() :
minmax( a, b, mnab, mxab );
:
,
,
.
min() max() :
mnab = min( a, b ); mxab = max( a, b );
:
,
,
(),
,
.
, , minmax() .

2
( swap) int
.
I - 367

-
(in out). 3 .
void swap( int& x, int& y )
{
int s( x );
x = y; y = s;
} // swap

3
, cntInt(), -
a double n
a .
cntInt():
a double
n ,
a .
, (in)
.

. :
int cntInt( const double a[], int n )//
.
6:
int cntInt( const double a[], int n )//
{
int m( 0 );

for ( int k(0); k < n; ++k )


if (a[k] == static_cast<long int>(a[k])) ++m;
return m;
} // cntInt

4
, to1Dgt, -
a, double, n
1
.
:
a double
1 -

.
,
[ ] n []. n
.
( a) -
(void). :
void to1Dgt( double a[], //

6 , a[k] == static_cast<long int>(a[k])


a[k] .
368 13

int n ) //
a .
:
void to1Dgt( double a[], int n )
{
for (int k(0); k < n; ++k )
a[k] = (static_cast<long int>(a[k]*10))/10.0;
} // to1Dgt

5
. 2 7.7 gcd()
lcm() . lcm() gcd().
:

unsigned int gcd( int x, int y )
lcm() :
void gcdLcm( int x, int y, int& gcdP, int& lcmP )
{ // (x,y)*(x,y) = x*y
if ( (x == 0 && y == 0) || x < 0 || y < 0 )
{
cout << " gcdLcm "
<< x << ", " << y << endl;
exit( EXIT_FAILURE );
}
// (x != 0 || y != 0) && x >= 0 && y >= 0
gcdP = gcd(x, y);
lcmP = x * y / gcdP;
} // gcdLcm
, , . -
.
: gcd(). -
.
lcm(), ; , .
.
. 2 9.4:
double vectorAvrg( const double x[], int n, int from, int upto)
double stdDev( const double x[], int n, int from, int upto )
x[from]..x[upto] .
stdDev() vectorAvrg().
: :
void simpleStat ( const double x[], int n, int from, int upto,
double& avrgP, double& stdDevP )
.
, .

6
. 4 12.4 ( )

. ;
!
, /
void:
void input2DAr( istream& tin, . . .
I - 369

void output2DAr( ostream& tout, . . .


: out
in. :
void output2DAr( ostream& tout,
const int* a, int nRow, int nCol )
; :
void input2DAr( istream& tin, int* a, int nRow, int nCol )

int& nRow, int& nCol.
out.
input2DAr:
void input2DAr( istream& tin, int* a, int nRow, int nCol )
{
for ( int r(0); r < nRow; ++r )
{
for ( int c(0); c < nCol; ++c )
tin >> a[r*nCol+c];
// tin >> a[r][c];
}
} // input2DAr
:
int a[ l ][ m ], b[ m ][ n ];
:
ifstream atx( "arr.txt" );
input2DAr( atx, &a[0][0], l, m );
input2DAr( atx, &b[0][0], m, n );
atx.close();
output2DAr.

:
, -
.
strtod() strtol() (double long
int ) endptr.
strlen()
strcat() :
,
-.
;
:
( C).


. .
, , , . -
(-) D.M. Ritchie B.W. Ker-
nighan, . ,
.
370 13

13.10
i)
( 5 ), ii) -
, iii) 1 -
iv) .
. 3
4 :
#include <iostream>
using namespace std;

int cntInt( const double a[], int n )//


{
int m( 0 );

for ( int k(0); k < n; ++k )


if (a[k] == static_cast<long int>(a[k])) ++m;
return m;
} // cntInt

void to1Dgt( double a[], int n )


{
for (int k(0); k < n; ++k )
a[k] = (static_cast<long int>(a[k]*10))/10.0;
} // to1Dgt

int main()
{
double q[5];

for ( int k(0); k < 5; ++k ) cin >> q[k];


cout << cntInt( q, 5 ) << endl;
to1Dgt( q, 5 );
for ( int k(0); k < 5; ++k ) cout << q[k] << " ";
cout << endl;
} // main
-
. , main -
, .
-
.

. 7.4, C++
( )
(prototypes) .
,
.
";".
:
int cntInt( const double[], int );
void to1Dgt( double[], int );

int cntInt( const double*, int );


void to1Dgt( double*, int );

int cntInt( const double a[], int n );


void to1Dgt( double a[], int n );
I - 371

, :
#include <iostream>
using namespace std;

int cntInt( const double a[], int n );


void to1Dgt( double a[], int n );

int main()
{
double q[5];

for ( int k(0); k < 5; ++k ) cin >> q[k];


cout << cntInt( q, 5 ) << endl;
to1Dgt( q, 5 );
for ( int k(0); k < 5; ++k ) cout << q[k] << " ";
cout << endl;
} // main

int cntInt( const double a[], int n )//


{
int m( 0 );

for ( int k(0); k < n; ++k )


if (a[k] == static_cast<long int>(a[k])) ++m;
return m;
} // cntInt

void to1Dgt( double a[], int n )


{
for (int k(0); k < n; ++k )
a[k] = (static_cast<long int>(a[k]*10))/10.0;
} // to1Dgt
, , -
(#include)
. ..
truncarr.cpp , ,
: truncarr.h :
#include <iostream>
#include <cmath>

#include "truncarr.h"

using namespace std;

int main()
. . .

13.11 !
!
.
. , text
autoflow.txt -
/min . ,
.

:
:\t<>\t<>
:\t<->\t<>\t<>
:\tdd.mm.yyyy\thh:mm
372 13

, .
.

. :
:
: 48
: 15.06.2009 05:00
26
30
8
28
. . .
17
19
4
12 /
28
17
. . .
17
31 / &
23
24
. . .
:
1. h
min.
2.
.
3. , -
/min.
,
report.txt.
autoflow.txt.

.
min.
; , ! .
.
text.
.
numberPerMink, k: 1..n autoflow.txt
,
differencek = numberPerMink numberPerMink-1, k: 2..n
n. min,
min n. h min
n 60:
hours = n / 60, minutes = n % 60
numberPerMink
min,
:
n
numberOfCars = num berPerMink .
k 1
I - 373

, /min

n
averageFlow = num berPerMink / n
k 1
n > 0,
.
:
: n > 0 ( autoflow.txt )
: differences.txt differencek,
k: 2..n
report.txt :
autoflow.txt,
n
n, hours (== n / 60), minutes (== n % 60), numberOfCars (== num berPerMink
k 1
), averageFlow (== numberOfCars / n).
.
autoflow.txt, -
report.txt . differences.txt
autoflow.txt .
; !
.
report.txt .
autoflow.txt,
differences.txt . :
.

n ( ) numberOfCars ( )
averageFlow.
, , report.txt -
.
:



, :
, ; :

if ( )
{


}
0.5 -
.

:
: n > 0 ( autoflow.txt )

374 13

: autoflow.txt
, differences.txt report.txt , n > 0 (
autoflow.txt )

: differences.txt
differencek, k: 2..n.
report.txt
autoflow.txt,
: n numberOfCars
n
(== num berPerMink ).
k 1
hours (== n / 60), minutes (== n % 60).
n > 0 ( autoflow.txt )
averageFlow (== numberOfCars / n).
report.txt n, hours, minutes, numberOfCars, averageFlow.

: differences.txt
differencek, k: 2..n
report.txt :
autoflow.txt,
n
n, hours (== n / 60), minutes (== n % 60), numberOfCars (== num berPerMink
k 1
), averageFlow (== numberOfCars / n).
. n
> 0
.

13.11.1
" "
.
; : autoflow.txt,
!. . -
,
. , :
, ,
report.txt differences.txt.
:
void openWrNoReplace( ofstream& newStream, string flNm, bool& ok )
{
ifstream test( flNm.c_str() ); //
if ( test.fail() ) // ok,
{
newStream.open( flNm.c_str() ); //
ok = !newStream.fail();
}
else // ,
{
test.close();
ok = false;
}
// ok = ( ) && ( )
} // openWrNoReplace
I - 375

:
ofstream report;
bool ok;
:
openWrNoReplace( "report.txt", report, bool& ok );
; (test)
report.txt.
test .
(test.fail())
.
.
. "
" :
autoflow
if ( autoflow)
{

}
else // autoflow
{
differences
if ( differences)
{
autoflow

}
else // autoflow, differences
{
report
if ( report)
{
autoflow, differences

}
else // autoflow, differences, report
{

} // if ( report)...
} // if ( differences)...
} // if ( autoflow)...
, openFiles.
.
openFiles
.
(void). ,
; -
ok .
ok
bool:
void openFiles( ifstream& autoflow, string autoFlNm,
ofstream& differences, string difFlNm,
ofstream& report, string reprtFlNm,
bool& ok )
openFiles C++
:
void openFiles( ifstream& autoflow, string autoFlNm,
ofstream& differences, string difFlNm,
376 13

ofstream& report, string reprtFlNm,


bool& ok )
{
ok = true;
autoflow.open( "autoflow.txt" );
if ( autoflow.fail() )
ok = false;
else // autoflow
{
openWrNoReplace( "differences.txt", differences, ok );
if ( !ok )
autoflow.close();
else // autoflow, differences
{
openWrNoReplace( "report.txt", report, ok );
if ( !ok )
{
autoflow.close();
differences.close();
} // if ( report)...
} // if ( differences)...
} // if ( autoflow)...
} // openFiles
, : ok
autoflow.txt , differences.txt report.txt
.
, main, C++ :
int main()
{
ifstream autoflow; // autoflow.txt
ofstream differences; // differences.txt
ofstream report; // report.dta
string autoFlNm( "autoflow.txt" ),
difFlNm( "differences.txt" ),
reprtFlNm( "report.txt" );
bool ok; // true

openFiles( autoflow, autoFlNm, differences, difFlNm,


report, reprtFlNm, ok );
if ( ok ) //
{


}
else {
cout << " ! !" << endl;
} // if (ok)...
} // main

13.11.2 E
:
: autoflow.txt , differences.txt
report.txt , n > 0 ( autoflow.txt
)

: autoflow.txt , differences.txt
report.txt .
differences.txt
differencek, k: 2..n.
I - 377

report.txt
autoflow.txt,
: n
n
numberOfCars (== num berPerMink ).
k 1
n > 0 ( autoflow.txt )
autoflow.txt , differences.txt
report.txt ,
. ,
close. , ...
n > 0 ;
7.

autoflow.txt. :
n
0.
,
!
.
; :
autoflow.txt text
.
.

.
, ,
. (): n
numberOfCars .
, , .

if ()
{



}
,
. .
.
( text),
.
copyTitle autoflow
report .
(bool ok) .
;
( ) :
void copyTitle( ifstream& autoflow, ofstream& report, bool& ok )
() .

7 n 2.
378 13

, , 8.11,

getline() 10.4. :
int lineCount; //
:
lineCount = 0;
while ( !autoflow.eof() && lineCount < 3 )
{
string aLine;
getline( autoflow, aLine, '\n' );
report << aLine << endl;
++lineCount;
} // while (... lineCount < 3)
, :
ok = ( lineCount == 3 );
:
void copyTitle( ifstream& autoflow, ofstream& report, bool& ok )
{
int lineCount( 0 ); //
while ( !autoflow.eof() && lineCount < 3 )
{
string aLine;
getline( autoflow, aLine, '\n' );
report << aLine << endl;
++lineCount;
} // while (... lineCount < 3)
ok = (lineCount == 3);
} // copyTitle
" ". ; :
n = 0; numberOfCars = 0;
.
initialize. ; -
, , ( ) -
( ): ,
. initialize 8.
.
n numberOfCars; ; int
! n . numberOfCars , INT_MAX
== 32767 ,
int long.
void initialize( int& n, long& numberOfCars )
{
n = 0;
numberOfCars = 0;
} // initialize
: " ".
. !
.
.
5 (8.5):
sum = 0; n = 0;
selSum = 0; selN = 0;

8 openFiles .
initialize() .
I - 379

a.open( "exp4.txt" );
a >> x;
while ( !a.eof() )
{
n = n + 1; //
sum = sum + x; //
if ( 0 < x && x <= 10 ) // '
{
selSum = selSum + x; //
selN = selN + 1; //
} // if
a >> x;
} // while
:
(autoflow) ,
sum numberOfCars,
x numberPerMin,
numberPerMin,
,
.
:
initialize( n, numberOfCars );
getline( autoflow, aLine, '\n' );
numberPerMin = strtol( aLine.c_str(), &p, 10 );
while ( !autoflow.eof() )
{
++n;
getline( autoflow, aLine, '\n' );
numberPerMin = strtol( aLine.c_str(), &p, 10 );
} // while
:
string aLine;
char* p;
autoflow:
, :
getline( autoflow, aLine, '\n' );
, strtol, long int .
strtol.
. p
; , -

.
: .
numberPerMin previous. :
getline( autoflow, aLine, '\n' );
numberPerMin = strtol( aLine.c_str(), &p, 10 );
while ( !autoflow.eof() )
{
++n;
numberOfCars = numberOfCars + numberPerMin;
difference = numberPerMin - previous;
differences << difference << endl;
previous = numberPerMin;
getline( autoflow, aLine, '\n' );
numberPerMin = strtol( aLine.c_str(), &p, 10 );
} // while
380 13

initialize;
.
:
,
,
, ,
,
previous, .
while:
getline( autoflow, aLine, '\n' );
numberPerMin = strtol( aLine.c_str(), &p, 10 ); // 1
if ( !autoflow.eof() )
{
++n;
numberOfCars = numberOfCars + numberPerMin;
previous = numberPerMin;
getline( autoflow, aLine, '\n' );
numberPerMin = strtol( aLine.c_str(), &p, 10 ); // 2
while ( !autoflow.eof() )
{
. . .
} // while
} // if (!autoflow.eof())
processData
. .
.
n numberOfCars ():
void processData( ifstream& autoflow, ofstream& differences,
int& n, long& numberOfCars )
processData:
void processData( ifstream& autoflow, ofstream& differences,
int& n, long& numberOfCars )
{
int numberPerMin; // autoflow.txt
string aLine;
char* p;
// 1
getline( autoflow, aLine, '\n' );
if ( !autoflow.eof() )
{
numberPerMin = strtol( aLine.c_str(), &p, 10 ); // 1
++n;
numberOfCars = numberOfCars + numberPerMin;
int previous( numberPerMin ); //
getline( autoflow, aLine, '\n' );
while ( !autoflow.eof() )
{
numberPerMin = strtol( aLine.c_str(), &p, 10 );// 2
++n;
numberOfCars = numberOfCars + numberPerMin;
int difference( numberPerMin previous );
//
differences << difference << endl;
previous = numberPerMin;
getline( autoflow, aLine, '\n' );
} // while
} // if (!autoflow.eof())
} // processData
I - 381

: .
autoflow;
autoflow.eof(). , ,
.
: n
numberOfCars

n > 0. .
report.txt:
void finish( ofstream& report, int n, long numberOfCars )
{
int hours( n / 60 ), // h . . .
minutes( n % 60 ); // . . . min
// report.txt
report << endl;
report << " ";
report.width(2); report << hours << " h ";
report.width(2); report << minutes << " min." << endl;
report << " " << n << " ." << endl;
report << " " << numberOfCars << " "
<< endl;
if ( n > 0 )
{
double averageFlow( static_cast<double>(numberOfCars) / n );
//
report << " : ";
report.setf( ios::fixed, ios::floatfield );
report.precision(1);
report.width(5);
report << averageFlow << " /min" << endl;
}
} // finish
-
n > 0.
, processing(). void
(bool ok) :
void processing( ifstream& autoflow,
ofstream& differences, ofstream& report,
bool& ok )
{
int n; // autoflow.txt,
long numberOfCars; // .
bool ok;

copyTitle( autoflow, report, ok );


if ( ok )
{
initialize( n, numberOfCars );
processData( autoflow, differences, n, numberOfCars );
finish( report, n, numberOfCars );
} // if (ok)...
} // processing
main, :
int main()
{
ifstream autoflow; // autoflow.txt
ofstream differences; // differences.txt
ofstream report; // report.dta
string autoFlNm( "autoflow.txt" ),
difFlNm( "differences.txt" ),
reprtFlNm( "report.txt" );
382 13

bool ok; // true

openFiles( autoflow, autoFlNm, differences, difFlNm,


report, reprtFlNm, ok );
if ( ok ) //
{
processing( autoflow, differences, report, ok );

}
else {
cout << " ! !" << endl;
} // if (ok)...
} // main

13.11.3
closeFiles :
void closeFiles( ifstream& autoflow,
ofstream& differences, ofstream& report,
bool& ok )
{
autoflow.close();

differences.close();
if ( differences.fail() )
{
cout << " !" << endl
<< " " << endl;
ok = false;
}
else
ok = true;

report.close();
if ( report.fail() )
{
cout << " !" << endl
<< " " << endl;
ok = false;
}
else
ok = ok && true; //
} // closeFiles
; !
,
: ..
close.
:
endl
.

13.11.4
:
#include <iostream>
#include <fstream>

using namespace std;

void openWrNoReplace( string flNm, ofstream& newStream,


bool& ok );
I - 383

void openFiles( ifstream& autoflow,


ofstream& differences, ofstream& report,
bool& ok );
void process( ifstream& autoflow,
ofstream& differences, ofstream& report,
bool& ok );
void copyTitle( ifstream& autoflow, ofstream& report,
bool& ok );
void initialize( int& n, long& numberOfVehicles );
void processData( ifstream& autoflow, ofstream& differences,
int& n, long& numberOfVehicles );
void finish( ofstream& report,
int n, long numberOfVehicles );
void closeFiles( ifstream& autoflow,
ofstream& differences, ofstream& report,
bool& ok );

int main()
{
ifstream autoflow; // autoflow.txt
ofstream differences; // differences.txt
ofstream report; // report.dta
string autoFlNm( "autoflow.txt" ),
difFlNm( "differences.txt" ),
reprtFlNm( "report.txt" );
bool ok; // true

openFiles( autoflow, autoFlNm, differences, difFlNm,


report, reprtFlNm, ok );
if ( ok ) //
{
processing( autoflow, differences, report, ok );
if ( !ok )
cout << " " << endl;
closeFiles( autoflow, differences, report, ok );
if ( ok ) //
cout << " , ..." << endl;
}
else
cout << " ! !" << endl;
} // main

13.12
, -
- .
(divide and conquer). ,
, ,
. 0.5,
(step by step refinement). .
,
(top - down). , , ..:
openFiles(), initialize(), finish() , .

. 13-3. , -
.
(
13.6.2.)
384 13

sqrt(), strcpy()
C++ . ,
openWrNoReplace().
.
, -
. .
, , .
.
.
( ) .. openFiles() ,
initialize() processData()
.. copyTitle(), processData().
(structured programming)
.
() . ,
.
.
.
, -
. main.
(bottom-up implementation)
(top-down design, bottom-up implementation).
:
, ,
.
1.
(data validation) . ,
5000 /min .
, .
2. : -
, ,
.

0
main

1
openFiles processing closeFiles

2
copyTitle initialize processData finish

3
openWrNoReplace

. 13-3 . openWrNoReplace (-
3) .
I - 385


. 13-1..13-11 -
( void)
. .
13-1 output2Dar(), . 6 13.9.3.
13-2 ( . 12-5) -
c1, c2 -
c1, c2.
13-3 ( . 12-12) -
k k
k .
13-4 h3, , ,
, 1, 2, 3, n
1 - 2 n == 0, 2 - 3 n == 1 3 - 1 n == 2.
13-5 {1,2,3}RR :
x y, n1

g(n, x, y) = xy , n2
x 1 / y , ( y 0) n 3

g() C++;
13-6 , q1,
, , x, y, z,
, p1 p2, :
x
z
yz
z > 0 p1 = p2 = zy+x,
z
z
x y z
z < 0 p1 = p2 = (z)yx.
z
q1() z 0 ().
13-7 , , -
x, y n double
w. : x y :
xk == a yk == b : xk == a - wb yk == a + wb,
k 0 n - 1.


13-8
( ).
(
).
13-9 M (nn) -
nn S A. :
m mcr m mcr
src rc (= scr) arc rc (= acr)
2 2
386 13

-
.
13-10 o . 5-7, 5-8 ,
trinomial(), :
() a, b, c ax + bx +
c.
reX1, im1, reX2, imX2,
ax + bx + c = 0.
, n, :
-1, ,
0 ,
1, ( reX1),
2, ( im1, imX2 0),
INT_MAX, .
a, b, c ,
trinomial(), ax + bx + c = 0.
13-11 , addPrev,
a double (
a[0]) , :
a[k] = a[k] + a[k-1], k: 1..n-1. (!
;).
13-12 13.11.2:
-
. (: ).
;
13-13 ) , toSec, h (0..23), min, sec -
sec .
) , toHms, :
h, min, sec.
) readHms() ,
h, min, sec.

h1, m1, s1 h2, m2, s2
, ,
: 0 h1, h2 < 24, 0 m1, m2 < 60, 0 s1, s2 < 60,

, : hh:mm:ss. ..: : 15 59 0 16
1 12 : 00:02:12.


13-14 "" (snakes and ladders)
100 1 100.
, . -
, 100.
(.. 96 6
100 98 ). -
.
I - 387


(
).
-
(
).

:


5 12 10 2
17 30 25 15
40 66 37 20
60 78 50 25
75 96 88 64

.
13-15 n
n. -
, :
1. 1 n
2. p = 2
3. while (p2 n) {
3.1 p
3.2 p =
}
: (n = 22)
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
p = 2
2 3 5 7 9 11 13 15 17 19 21
p = 3
2 3 5 7 11 13 17 19
388 13

14
II
:
.
:
(callback).
.
(templates) .
(exceptions) .
:
-
.
.
, -
.
:
inline

-

(callback)




main
(stack)


:
14.1 inline .......................................................................................................................... 390
14.2 ..................................................................................................... 390
14.3 ........................................................................................................................ 392
14.4 * ............................................................................... 394
14.5 ..................................................................................................................... 397
14.6 ............................................................................................................................ 400
14.6.1 WeekDay ............................................................................................400
389
390 14

14.6.2 ++ WeekDay .........................................................................................................401


14.6.3 () ........................................................................................................................403
14.6.4 ... ............................................................................................................................................................404
14.7 ................................................................................................................................. 405
14.7.1 .............................................................................................................................405
14.7.1.1 using ............................................................................................................ 409
14.7.2 ..........................................................................................................................409
14.7.2.1 , ... .......................................................................... 410
14.8 ..................................................................................................................................................... 411
14.8.1 stackavail .....................................................................................................................................413
14.9 ..................................................................................................... 414
14.9.1 ..................................................................................................................................419
14.10 () ....................................................................................................................................... 420
14.11 * ......................................................................................................... 424
14.12 ... .......................................................................................................................................... 426
................................................................................................................................................................... 427
.............................................................................................................................................................................427
.............................................................................................................................................................................427
.............................................................................................................................................................................428

14.1 inline
(
). ( ) -
:
.
.
, , (macros):

() .
,
C++1
. , ..:
inline int max( int x, int y )
{
int fvx;

if ( x > y ) fvx = x;
else fvx = y;
return fvx;
} // max int
.
:
. if . :
inline int max( int x, int y ) { return (x > y) ? x : y; }
.

14.2
, inc,
:
void inc( int& x, int s )

1 inline C 1999 (ISO/ IEC 1999).


II 391

{ x == x0 } inc( x, a ); { x == x0 + a }
{ x == x0 } inc( x ); { x == x0 + 1 }
, inc ! 2
:
{ x == x0 } inc( x, a ); { x == x0 + a }
; :
void inc( int& x, int s )
{
x += s;
} // inc
:
void inc( int& x, int s = 1 )
{
x += s;
} // inc
; s s -
1.
, :
int p;

p = 5; inc( p, 2 ); cout << p << endl;


p = 5; p += 2; cout << p << endl;
p = 5; inc( p ); cout << p << endl;
p = 5; ++p; cout << p << endl;
:
7
7
6
6
-
.
,
,
.
:
, , -
.
, .
. :
int f( double x, int y = 0, float z )
:
int f( double x, int y = 0, float z = 1.5 )
f :
f( 1.56 ) f( a+b, a, b/2 ) f( p+0.5, n+1 )
1.56 x. y z -
0 1.5 .
a+b x, a
y b/2 z.

2 x += a ++x x += 1.
392 14

p+0.5 n+1 x y .
z 1.5.

14.3
, ,
f(x) = 0 [a0,b0].
3 (bisection).
f [a0,b0] f(a0)f(b0)
0. m0 [a0,b0], f(m0).
f(a0)f(m0) 0
[a0,m0]

[m0,b0]
C++ :
a = a0; b = b0;
m = (a + b) / 2;
if ( f(a)*f(m) <= 0.0 ) b = m;
else a = m;
[a0,m0] b = m,
. (. 14-3).
. a, b -
. ;
m .
; [a,b]
m b a/2 . , m
b - a/2. ,
4 |b a|/2 < .
:
a = a0; b = b0;
while ( fabs(b - a)/2 >= epsilon )
{
m = (a + b) / 2;
if (f(a)*f(m) <= 0.0) b = m;
else a = m;
} // while
root = m;
f(a0)f(b0) 0. -
, ,
. -
, errCode, 0
1 .
: ; -
f a0, b0
errCode. :
void bisection( ...
double a0, double b0, double epsilon,
double& root, int& errCode )

3 -
. ( et al. 1992).
http://en.wikipedia.org/wiki/Bisection_method.
4 .
II 393

a0, b0, epsilon ,


. root
. errCode. ;
f ! ; H
C++ :
double. :
double* f(double)
(double) f f , double.
(. ) -
f(double) *. f , f(double)
. *f (*f)(double). ,
:
double (*f)(double)
:
void bisection( double (*f)(double),
double a, double b, double epsilon,
double& root, int& errCode )
:
f(a) : (*f)(a). :
void bisection( double (*f)(double),
double a, double b, double epsilon,
double& root, int& errCode )
{
double m;

if ( (*f)(a)*(*f)(b) > 0 )
errCode = 1;
else
{
while ( fabs(b-a)/2 >= epsilon )
{
m = (a + b) / 2;
if ( (*f)(a)*(*f)(m) <= 0.0 ) b = m;
else a = m;
} // while
root = m;
errCode = 0;
} // if
} // bisection
C++ :
if ( f(a)*f)(b) > 0 )

if ( f(a)*f(m) <= 0.0 ) b = m;


.
bisection(). -
x - ln(x) - 2 = 0 [0.1, 1]. ,
x - ln(x) - 2:
double q( double x )
{
return ( x - log(x) 2 );
} // q
.. main :
bisection( &q, 0.1, 1.0, 1e-5, riza, errCode );
&q;
q().
394 14

C++ &
:
bisection( q, 0.1, 1.0, 1e-5, riza, errCode );
x = 0 [0,] :
bisection( cos, 0.0, 4*atan(1), 1e-5, riza, errCode );
, , #include cmath
cos() atan().
bisection():
#include <iostream>
#include <cmath>

using namespace std;

double q( double x );
void bisection( double (*f)(double),
double a, double b, double epsilon,
double& root, int& errCode );

int main()
{
const double pi( 4*atan(1.0) );
double riza;
int errCode;

bisection( q, 0.1, 1.0, 1e-5, riza, errCode );


if ( errCode != 0 ) cout << "o " << endl;
else cout << " = " << riza << endl;
bisection( cos, 0.0, pi, 1e-5, riza, errCode );
if ( errCode != 0 ) cout << "o " << endl;
else cout << " = " << riza << endl;
} // main

void bisection( double (*f)(double),


double a, double b, double epsilon,
double& root, int& errCode )
//
double q( double x )
//
o o o oo.
= 0.1585983
= 1.570784
:
1. n |b a|/2. ,
nMax.
2. bisection() :
|b a|/2 < .
( )
|f(x)| < .

14.4 *
: ! :
.

. -
f(x) = 0
f. bisection f :
II 395

f : double y double
;
f.
f. f
(callback function)5. , q cos.
API Windows6.
: (
API Windows)
(dialog box)
.

. :
int DialogBox( HINSTANCE hInstance,
PCTSTR pTemplate, //
HWND hWndParent,
DLGPROC pDialogFunc ) //
//
(
).
.
DialogBox, ,
.
:
bool CALLBACK about( HWND hDlg, UINT iMessage,
WPARAM wParam, LPARAM lParam )
, :
bool about( HWND hDlg, unsigned int iMessage,
unsigned short int wParam, long int lParam )
:
DialogBox( hInstance, "AboutBox", hWnd, &about );
:
DialogBox( hInstance, "AboutBox", hWnd, about );
(
.) (, , -
) -
C. C, , -
. C++ ( )
.
(Haendel 2001) ,
C++.
(Hosey 2007) C C++.

.
:
. : strcpy, strcat .
:
. :
const char* myStrLT( const char* s1, const char* s2 )

5 .
6 Windows Application Program Interface ( o ).
396 14

s1 s2 -
. , :
const char* myStrLT( const char* s1, const char* s2 )
{
const char* fv( s1 );
if ( strcmp(s2, fv) < 0 ) fv = s2;
return fv;
} // myStrLT
char
.
. DLGPROC;
winuser.h . :
typedef int (*DLGPROC)( HWND, unsigned int,
unsigned short int, long int );
! &about
DLGPROC.
, , :
typedef double Real1( double );
Real1
double .
:
void bisection( Real1* f,
double a0, double b0, double epsilon,
double& root, int& errCode )
:
typedef double (*PReal1)( double );
PReal1
double .
bisection :
void bisection( PReal1 f,
double a0, double b0, double epsilon,
double& root, int& errCode )
! -
7 Real1. : :
Real1 funcArr[3];
. ;
; :
PReal1 funcArr[3];
!

( ex = x+2):
double em2( double x )
{
return exp(x)-x-2;
} // em2
:
x = lnx + 2 x [0.1,1], x = 0 x [0,], ex = x+2 x [0,2]
;
const double pi( 4*atan(1.0) );

7 ; . C++
. C...
II 397

PReal1 funcArr[3];
double a[3], b[3];
double riza;
int errCode;

funcArr[0] = &q; a[0] = 0.1; b[0] = 1.0;


funcArr[1] = &cos; a[1] = 0.0; b[1] = pi;
funcArr[2] = &em2; a[2] = 0.0; b[2] = 2.0;

for ( int k(0); k < 3; ++k )


{
bisection( funcArr[k], a[k], b[k], 1e-5, riza, errCode );
if ( errCode != 0 ) cout << "o " << endl;
else cout << " = " << riza << endl;
}
:
funcArr[0] = q; a[0] = 0.1; b[0] = 1.0;
funcArr[1] = cos; a[1] = 0.0; b[1] = pi;
funcArr[2] = em2; a[2] = 0.0; b[2] = 2.0;
, PReal1:
double (*funcArr[3])( double );
, ( ) .
:
PReal1 funcSel( PReal1 funcArr[], int n, int sel )
{
return funcArr[sel];
}
(
):
bisection( funcSel(funcArr, 3, 1), a[1], b[1], 1e-5,
riza, errCode );
,
:
double (*(funcSel(double (*funcArr[])(double),
int n,int sel )))(double)
{
return funcArr[sel];
}
, ;! .
; : ! ,
8

14.5
13.9.3 swap()
int.
!
, :
swapI, swapD, double, swapC,
char
.
swap :
#include <iostream>

8 , !
398 14

using namespace std;

enum WeekDay { sunday, monday, tuesday, wednesday, thursday,


friday, saturday };

void swap( int& x, int& y );


void swap( double& x, double& y );
void swap( char& x, char& y );
void swap( WeekDay& x, WeekDay& y );

int main()
{
int j1( 10 ), j2( 20 );
double d1( 1.23 ), d2( 2.34 );
char c1( 'A' ), c2( 'B' );
WeekDay m1( sunday ), m2( tuesday );

swap( j1, j2 ); cout << j1 << " " << j2 << endl;
swap( d1, d2 ); cout << d1 << " " << d2 << endl;
swap( c1, c2 ); cout << c1 << " " << c2 << endl;
swap( m1, m2 ); cout << int(m1) << " " << int(m2) << endl;
} // main

void swap( int& x, int& y )


{
int s( x );
x = y; y = s;
} // swap int

void swap( double& x, double& y )


{
double s( x );
x = y; y = s;
} // swap double

void swap( char& x, char& y )


{
char s( x );
x = y; y = s;
} // swap char

void swap( WeekDay& x, WeekDay& y )


{
WeekDay s( x );
x = y; y = s;
} // swap WeekDay
, (int, double,
char, WeekDay) .
.
(function overloading).

.
-
. , swap() :
double swap( int a, double b ) { return (a+b)/2; }
,
.

. :
void f( int& x, int& y ) { /*...*/ }
int f( int x, int y ) { /*...*/ return ...; }
II 399

void f( int& x, int y=0 ) { /*...*/ }


:
int j1, j2;
// . . .
f( 17, j2 );
f( j1 );
f( j1, j2 );
:
;

17

.
; ! !
.
:
-
(signature) ,
C++ : . 9
:

. , :
void f( char x ) // (a)
void f( int x ) // (b)
void f( double x ) // (c)
:
f( 'c' );
(a).


10 float double double long double.

void f( int x ) // (b)
void f( double x ) // (c)
:
f( 'c' );
(b).

int double, double
int . , (a) (b)
(c).11

9 ! C++ ,
( ) .
10 . .
11
.
400 14

14.6
. +. :
+: intint y int
, 1.2 + 3. ! :
+: doubleint y double
+: intdouble y double
. , -
+.
C++ ()
, () . :
-
. .. * .
.
:
, ++, , ,
/, .
: ::, ., .*, ?:.12
, .
() . , , wd WeekDay,
++wd
next(wd) advance(wd). , ,
--, ... !
:13
.
:
, @, -
operator@().
, WeekDay (4.8).
++ () <<
() .

14.6.1 WeekDay
<< wd, WeekDay, sunday
:
tout << wd << endl;
text tout:

, tout, cout .
, <<, ()
operator<<:
<<,
tout.

12 !
13 DCL11 (CERT 2009): Preserve operator semantics when overloading
operators.
II 401

<<,
wd.
, 13.9.2:
cout << " x = " cout. (
tout cout)
/ ( )
in out ().
cout
ostream ofstream.

:
ostream& operator<<( ostream& tout, WeekDay rhs )
void operator<<( .
:
ostream& operator<<( ostream& tout, WeekDay rhs )
{
string fv;
switch ( rhs )
{
case sunday: fv = ""; break;
case monday: fv = ""; break;
case tuesday: fv = ""; break;
case wednesday: fv = ""; break;
case thursday: fv = ""; break;
case friday: fv = ""; break;
case saturday: fv = ""; break;
} // switch
return ( tout << fv );
} // operator<< WeekDay
, :
ostream& operator<<( ostream& tout, WeekDay rhs )
{
switch ( rhs )
{
case sunday: return ( tout << "" );
case monday: return ( tout << "" );
case tuesday: return ( tout << "" );
case wednesday: return ( tout << "" );
case thursday: return ( tout << "" );
case friday: return ( tout << "" );
case saturday: return ( tout << "" );
} // switch
} // operator<< WeekDay
()
: return!
, (
) .

14.6.2 ++ WeekDay
, , ,
operator++() .
, .
,
WeekDay d;
. . .
402 14

++d;
d sunday friday: d
( : d = d + 1). d saturday
sunday.
: 14
WeekDay operator++( WeekDay& lhs )
{
if ( lhs < saturday ) lhs += 1;
else lhs = sunday;
return lhs;
} // operator++( WeekDay
( operator<<):
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

enum WeekDay { sunday, def, tuesday, wednesday, thursday, friday,


saturday };

ostream& operator<<( ostream& tout, WeekDay rhs );


WeekDay operator++( WeekDay& lhs );

int main()
{
// . . .
WeekDay d( sunday );
for ( int k(0); k < 10; ++k )
{
cout << d << endl;
++d;
}
// . . .
} // main
:

14 Borland C++ v.5.5 . gcc +=


WeekDay. :
WeekDay operator++( WeekDay& lhs )
{
if ( lhs < saturday )
{
int iv( static_cast<int>(lhs) );
++iv;
lhs = static_cast<WeekDay>(iv);
}
else
lhs = sunday;
return lhs;
} // operator++( WeekDay
II 403

operator++(); ++d! ;
++d :
operator++( d );
: operator++() d. , -
-
!
++d .
operator<<(); cout << d. ,
cout << d << endl :
operator<<( cout, d ) << endl;
! ,
cout << d
operator<<( cout, d ).
:
operator++() :
. C++
++ --.
C++ (
C) operator++() WeekDay
WeekDay&.
++ ;
:
WeekDay operator++( WeekDay& lhs, int )
{
WeekDay sv( lhs );
++lhs;
return sv;
} // operator++( WeekDay, int
()
.
: .

14.6.3 ()
v = :

static_cast<T>().
static_cast<T>() .
v.
:
w = v = u = 0;
:
w = (v = (u = 0));
:
(w = v) = u;
, ; :
#include <iostream>

using namespace std;

int main()
404 14

{
int u(1), v(2), w(3);
(w = v) = u;
cout << u << " " << v << " " << w << endl;
}
:
1 2 1
, (w = v) -l.
w 1 ( u) 2 ( v).
. :
cout << u << endl;
(u += 7) = 11;
cout << u << endl;
(++u) = 17;
cout << u << endl;
:
1
11
17
; 11.3 : v
v. ... .
(w = v) = u. v w, -
w = v w, -l. ,
w = u w u 1.
(++u) = 17 (u=u+1) = 17. u=u+1
u u = 17.
, -

. T
T&.
C++ ( C) -
:
T& operator=( T& lhs, const T& rhs )
T& operator+=( T& lhs, const T& rhs )
T& operator++( T& lhs )
( const T&).15 --, -=, *= .
,
WeekDay& operator++( WeekDay& v )
{
if ( v < saturday ) v += 1;
else v = sunday;
return v;
} // operator++( WeekDay
++, --
. ,
(sv) .

14.6.4 ...
,

15 34 (ELLEMTEL 1992) : An assign-


ment operator ought to return a const reference to the assigning object.
II 405

@
Trv operator@( Tl lhs, Tr rhs )
Trv , Tl Tr
.
...operator@( x, y )... ...x @ y.... (lhs)
(x) (rhs)
(y).
@
Trv operator@( T rhs )
Trv , T .
...operator@( x )... ...@x....
(rhs)
(x).
@ (
@)
Trv operator@( T lhs, int )
Trv , T .
...operator@( x, 1 )... ...x@....
( ) (lhs) -
(x).
.
, :

.

14.7
14.5 swap. ,
. C++
:
. (function
template).
o (generic function). ,

/ .

14.7.1
14.5 :
#include <iostream>

using std::cout;
using std::endl;

enum WeekDay { sunday, monday, tuesday, wednesday, thursday,


friday, saturday };

template < typename T >


void swap( T& x, T& y );

int main()
{
406 14

int j1( 10 ), j2( 20 );


double d1( 1.23 ), d2( 2.34 );
char c1( 'A' ), c2( 'B' );
WeekDay m1( sunday ), m2( tuesday );

swap( j1, j2 ); cout << j1 << " " << j2 << endl;
swap( d1, d2 ); cout << d1 << " " << d2 << endl;
swap( c1, c2 ); cout << c1 << " " << c2 << endl;
swap( m1, m2 ); cout << int(m1) << " " << int(m2) << endl;
} // main

template < typename T >


void swap( T& x, T& y )
{
T s( x );
x = y; y = s;
} // swap
16 : :
template < typename T >
void swap( T& x, T& y )
{
T s( x );
x = y; y = s;
} // swap
(template) swap .
typename T class T. class,
template typename - C++.
:
20 10
2.34 1.23
B A
2 0
swap(j1, j2) (instance)

void swap( int& x, int& y )

T int.
, swap(d1, d2)
:
void swap( double& x, double& y )
...

/
,
.

(template instance) :
, -
-
. (implicit instantiation).
(explicit) , ,
. ..

16 using. .
II 407

, swap(d1, d2), : swap<double>(d1, d2).



1
vectorSum (12.1) -
:
template < typename CT >
CT vectorSum( const CT x[], int n, int from, int upto )
{
CT sum( 0 );

for ( int m(from); m <= upto; ++m ) sum += x[m];


return sum;
} // vectorSum
: CT double.
double
DBL_MAX.
long double. :
template < typename CT, typename RT >
RT vectorSum( const CT x[], int n, int from, int upto )
{
RT sum( 0 );

for ( int m(from); m <= upto; ++m ) sum += x[m];


return sum;
} // vectorSum
:
double ar[7971];
long double res;

res = vectorSum( ar, 7971, 0, 7970 );
. -
:
res = vectorSum<double, long double>( ar, 7971, 0, 7970 );


.
.
2
. 6 13.9.3
void input2DAr( istream& tin, int* a, int nRow, int nCol )
void output2DAr( ostream& tout,
const int* a, int nRow, int nCol )

(. 4, 12.4). ,
. 13-1, .
:
,
:
template< typename T, unsigned int nCol >
void input2DAr( istream& tin, T a[][nCol], int nRow )
{
for ( int r(0); r < nRow; ++r )
for ( int c(0); c < nCol; ++c )
tin >> a[r][c];
408 14

} // input2DAr
; ! :
template < typename T, unsigned int nCol >
void output2DAr( ostream& tout,
const T a[][nCol], int nRow )
{
for ( int r(0); r < nRow; ++r )
{
for ( int c(0); c < nCol; ++c )
{
tout.width(3); cout << a[r][c] << " ";
}
cout << endl;
}
} // output2DAr
, :
input2DAr< int, m >( atx, a, l );
input2DAr< int, n >( atx, b, m );
:
cout << " a" << endl;
output2DAr< int, m >( cout, a, l );
cout << " b" << endl;
output2DAr< int, n >( cout, b, m );
cout << " c" << endl;
output2DAr< int, n >( cout, d, l );
!17 -
-
.
! -
156160 -
156672.18
; :
input2DAr output2DAr! , .
, :
.

.

:
swap


vectorSum() (RT)

+= operator+=( RT, CT )

output2DAr -
<< text. ..
WeekDay.

17 3 tout.width(3) .
;
18 Borland C++, v.5.5.
II 409

input2Dar() -
>> text. ..
WeekDay.
max.
:
template< typename T >
T max( T x, T y ) { return (x > y) ? x : y; }

>, int, double, char ... -
C ( ); T char*
. C++
(specialization) char*:
template<>
char* max<char*>( char* x, char* y )
{ return (strcmp(x, y) > 0) ? x : y; }
template<>.
<, >
.
-
. max :
template<>
char* max<>( char* x, char* y )
{ return (strcmp(x, y) > 0) ? x : y; }
, ) -
)
. -
output2DAr() :
template <>
void output2DAr<>( ostream& tout,
const int a[][nCol], int nRow )
// . . .
int nCol == 2.

14.7.1.1 using
swap

using namespace std;


:
using std::cout;
using std::endl;
; sdt swap()
C++!
min(), max() . ! using
namespace std #include <algorithm>.

14.7.2
swap() :
:
char s1[15], s2[20];
410 14

, ! :
void swap( char x[], char y[] )
. :
void swap( char x[], char y[] )
{
string s( x );
strcpy( x, y );
strcpy( y, s.c_str() );
} // swap( char*
:
1. ...; x y
. - .
2. using std::cout using
std::endl using std::string.
:
swap( s1, s2 );
.
:
template< typename T >
void qsc( T x, char c )
{ cout << "in template" << endl; }

void qsc( double x, char c )


{ cout << "in function" << endl; }
:
int k( 23 );
double e( 7.33 );
:
qsc( k, 'a' );
qsc( e, 'c' );

:
in template
in function
: ,
qsc
template< typename T >
void qsc( int x, T c )
{ cout << "in template 2" << endl; }

:
qsc( k, 'a' );

.

14.7.2.1 , ...
-
(-) (-) / (-) (-
) :

.
II 411


14.5.
-
.

.
:
template< typename T >
void qsc( T x, char c )
{ cout << "in template" << endl; }

void qsc( double x, char c )


{ cout << "in function" << endl; }

template<> void qsc<double>( double x, char c )


{ cout << "in template spec" << endl; }
:
!
:
qsc( e, 'c' );
! :
in function
:
:
void qsc<double>( double x, char c );

void qsc( double x, char c );
qsc(e,'c') double char
.
.
, ,

qsc(e,'c').

.

14.8

C++. () .
.
.
19 :
(static),

,
(automatic) (stack)
,

19 : .
412 14

:
.
:
#include <iostream>

using namespace std;

long g = 0;

double fd( double p1, double p2 )


{
cout << " &p1 = " << &p1 << " &p2 = " << &p2 << endl;
return p1*p2/2;
} // fd

long fl( double p )


{
long s;

cout << " &p = " << &p << " &s = " << &s << endl;
p = fd(p, 1.56);
s = (p + 1.56)/2;
return s;
} // fl

int main()
{
long a, b;
double x[5], y;

cout << " &g = " << &g << endl;


cout << " &a = " << &a << " &b = " << &b << endl
<< " x = " << x << " &y = " << &y << endl;
y = fl(5);
x[2] = fd( x[0], y );
}
(Borland C++, v.5.5 Windows XP):
&g = 0041B178
&a = 0012FF88 &b = 0012FF84
x = 0012FF54 &y = 0012FF7C
&p = 0012FF44 &s = 0012FF38
&p1 = 0012FF28 &p2 = 0012FF30
&p1 = 0012FF3C &p2 = 0012FF44
, , :
g
(0041B178) (0012FF...). g -
.
, a3, q,
b main.
main. ,
main 0012FF54 (x)
0012FF88 (a).
fl
0012FF38 (s) 0012FF44 (p).
fd, fl, -
0012FF28 (p1) 0012FF30 (p2).
fl, fl
fd . :
II 413

fd, main,
0012FF3C (p1) 0012FF44 (p2). -
fl.
, ,
(Last In First Out), , , -
(stack, LIFO stack).

14.8.1 stackavail
Borland C++, v.5.5 ( v.5.02)
( ) stackavail
:
#include <iostream>
#include <malloc.h>

using namespace std;

long g = 0;

double fd( double p1, double p2 )


{
cout << " fd, stackavail: " << stackavail() << endl;
cout << " &p1 = " << &p1 << " &p2 = " << &p2 << endl;
return p1*p2/2;
} // fd

long int fl( double p )


{
long s;

cout << " fl, stackavail: " << stackavail() << endl;
cout << " &p = " << &p << " &s = " << &s << endl;
cout << " fd, stackavail: " << stackavail()
<< endl;
p = fd(p, 1.56);
cout << " fd, stackavail: " << stackavail() << endl;
s = (p + 1.56)/2;
return s;
} // fl

int main()
{
long int a, b;
double x[5], y;

cout << " &g = " << &g << endl;


cout << " &a = " << &a << " &b = " << &b << endl
<< " x = " << x << " &y = " << &y << endl;
cout << " fl, stackavail: " << stackavail()
<< endl;
y = fl(5);
cout << " fl, stackavail: " << stackavail() << endl;
cout << " fd, stackavail: " << stackavail()
<< endl;
x[2] = fd( x[0], y );
cout << " fd, stackavail: " << stackavail() << endl;
}
(Borland C++, v.5.5 Windows XP):
&g = 0041B17C
&a = 0012FF88 &b = 0012FF84
x = 0012FF54 &y = 0012FF7C
fl, stackavail: 1048376
414 14

fl, stackavail: 1048356


&p = 0012FF40 &s = 0012FF34
fd, stackavail: 1048356
fd, stackavail: 1048332
&p1 = 0012FF24 &p2 = 0012FF2C
fd, stackavail: 1048356
fl, stackavail: 1048376
fd, stackavail: 1048376
fd, stackavail: 1048352
&p1 = 0012FF38 &p2 = 0012FF40
fd, stackavail: 1048376
:
fl 1048376 .
1048356 . 20
(8+4) .
fl, stackavail:
1048376.
fd 24
.

14.9
7.8. V,
{ k: Z 2k }:
double v( double x )
{
const double a( -1 ), b( 1 ), T( b-a );
double m( floor( (x-a)/T ) ), x0( x - m*T ), fv;

// (-1 <= x0 < 1) && (v(x0) == v(x))


if ( x0 == 0 )
{
cerr << " v : " << x << endl;
exit( EXIT_FAILURE );
}
// (-1 <= x0 < 1) && (x0 != 0) && (v(x0) == v(x))
fv = -1/fabs(x0+2) - 1/fabs(x0) - 1/fabs(x0-2);
return fv;
} // v
7 . 7.4 :
,
:
if (x )
{
cerr << " ... x = " << x << endl;
exit( EXIT_FAILURE );
}
else

. ,
:
, pqer,
, x, y, z -
:
1
xy xy
xy x , |x| |y| z > 0.
t= 2 z , u=
x y2 z
II 415

:
void pqer( double x, double y, double z, double& t, double& u )
{
if ( x == y || x == -y || z <= 0 )
{
cerr << " pqer " << x << ", "
<< y << ", " << z << endl;
exit( EXIT_FAILURE );
}
t = x*y*pow(z, x-y)/(x*x-y*y);
u = (x*y-1/x)/z;
} // pqer

. ..
v -5 5 0.5:
for ( int k(-10); k <= 10; ++k )
cout << " v(" << (k/2.0) << ") = " << v(k/2.0) << endl;
:
v(-5) = -2.33333
v(-4.5) = -3.06667
v : -4
, :
#include <iostream>
#include <cmath>
#include <cstdlib>

using namespace std;

double v( double x );

int main()
{
for ( int k(-10); k <= 10; ++k )
{
try
{
cout << " v(" << (k/2.0) << ") = " << v(k/2.0) << endl;
}
catch( double x )
{
cout << " v " << x << endl;
}
} // for (int k...
} // main

double v( double x )
{
const double a( -1 ), b( 1 ), T( b-a );
double m( floor( (x-a)/T ) ), x0( x - m*T ), fv;

// (-1 <= x0 < 1) && (v(x0) == v(x))


if ( x0 == 0 )
{
throw x;
}
// (-1 <= x0 < 1) && (x0 != 0) && (v(x0) == v(x))
fv = -1/fabs(x0+2) - 1/fabs(x0) - 1/fabs(x0-2);
return fv;
} // v
:
v(-5) = -2.33333
v(-4.5) = -3.06667
416 14

v -4
v(-3.5) = -3.06667
v(-3) = -2.33333
v(-2.5) = -3.06667
v -2
v(-1.5) = -3.06667
. . .
v(3.5) = -3.06667
v 4
v(4.5) = -3.06667
v(5) = -2.33333
, , .
.
; : throw, try catch.
, throw x -
( ) (throw (raise) an exception). x
(exception object). -
v() ,
main.
main, v try ().
try
.
catch () try.
catch .
catch (exception handling):
.
.
, :
int main()
{
for ( int k(-10); k <= 10; ++k )
{
try
{
cout << " v(" << (k/2.0) << ") = " << v(k/2.0) << endl;
}
catch( double x )
{
cout << " v(" << (x+1e-5) << ") = " << v(x+1e-5) << endl;
}
} // for (int k...
} // main
:
v(-5) = -2.33333
v(-4.5) = -3.06667
v(-3.99999) = -100001
v(-3.5) = -3.06667
v(-3) = -2.33333
v(-2.5) = -3.06667
v(-1.99999) = -100001
v(-1.5) = -3.06667
. . .
v(3.5) = -3.06667
v(4.00001) = -100001
v(4.5) = -3.06667
v(5) = -2.33333
II 417

, , ,
, . -
, , .
try-catch
exit():
int main()
{
try
{
for ( int k(-10); k <= 10; ++k )
{
cout << " v(" << (k/2.0) << ") = " << v(k/2.0) << endl;
} // for (int k...
}
catch( double x )
{
cout << " v " << x << endl;
}
} // main
:
v(-5) = -2.33333
v(-4.5) = -3.06667
v -4
:

exit().
.
, main.
, :
main; . ,
.
try; ! -
throw try.
pqer, -
:
void pqer( double x, double y, double z, double& t, double& u )
{
if ( x == y || x == -y || z <= 0 )
throw " pqer ";
t = x*y*pow(z, x-y)/(x*x-y*y);
u = (x*y-1/x)/z;
} // pqer
, pqer char* ( ).
: , , , -
. x, y, z
. -
.
main : v
double pqer char*.
; main:
int main()
{
double t, u;

try
{
418 14

// . . .
pqer( 1, 2, 3, t, u );
// . . .
for ( int k(-10); k <= 10; ++k )
{
cout << " v(" << (k/2.0) << ") = " << v(k/2.0) << endl;
} // for (int k...
// . . .
}
catch( double x )
{
cout << " v " << x << endl;
}
catch( char* x )
{
cout << x << endl;
}
} // main
, try catch -
-
.
catch( ... ) . ..
:
try
{
// . . .
}
catch( double x )
{
cout << " v " << x << endl;
}
catch( char* x )
{
cout << x << endl;
}
catch ( ... )
{
cout << " " << endl;
}
, , ,
(exception specification) -
:
double v( double x ) throw( double );
void pqer( double x, double y, double z,
double& t, double& u ) throw( char* );
double f( double x ) throw( double, int );
-
. :
double g( double x ) throw()
g() -

double g( double x )
g() .
II 419

14.9.1
, -
.
. 1 7.7 :
#include <iostream>

using namespace std;

unsigned long int comb( int m, int n );

int main()
{
int m, n;

cout << " m, n <= 50, m >= n: ";


cin >> m >> n;
try
{
cout << " "
<< m << " " << n << " = " << comb(m,n) << endl;
}
catch( int )
{
cout << " " << endl;
}
} // main

// natProduct -- m*(m+1)*...*(n-1)*n
unsigned long int natProduct( int m, int n )
{
if ( m <= 0 || n < m )
{
throw -1;
}
// 0 < m <= n
unsigned long int fv( m );
for ( int k(m+1); k <= n; ++k ) fv *= k;
return fv;
} // natProduct

// factorial -- a!
unsigned long int factorial( int a )
{
return (a == 0) ? 1 : natProduct(1, a);
} // factorial

// comb -- m n
unsigned long int comb( int m, int n )
{
unsigned long int fv;

if ( n < m-n ) fv = natProduct(m-n+1, m)/factorial(n);


else fv = natProduct(n+1, m)/factorial(m-n);
return fv;
} // comb
, :

5
. :
2
5 5! 5! 1 2 3 4 5
= = =
2
2! ( 5 2 )! 2!3! 2!1 2 3
, 123 .
comb() , .
420 14

natProduct( int m, int n )


: m(m+1)...(n-1)n, 0 < m n. natProduct
.
natProduct() , ,
factorial().
natProduct().
!
natProduct() 0 < m n
( int) -1. , , main
8
.
10
comb(m, n) comb(). -
n < m-n , else. H comb()
natProduct(11, 8)
factorial(-2). factorial(-2).
factorial(). facto-
rial(), , natProduct(1, -2).
nat-
Product(). natProduct() m 0,
-1.
natProduct()
factorial().
factorial() . factorial() -
comb().
comb() catch(int ...) -
comb() main
.
-
(stack unwinding).
main
.
,
:
1. , throw, try catch,

.
2. , , ,

. 13.11.
.
3. : factorial()
comb()!

14.10 ()
7.10, C++
,
. : n!

II 421

, ,
, .
, , -
.
; -
n+1 ,
. n -
.
. .
(Dijkstra 1976), "A Discipline of Programming",
. .
(Manna & Waldinger 1978), -
, -
, -
Dijkstra. ( 6 2)
Dijkstra.
.

, x > 1 y 0 (), z
():
R: z == xy
Dijkstra h,

P: hz == xy

while ( h 1 ) h P
: h = xy; z = 1. ,
while, h == 1
R.
xy , h.
h xxyy
P: xxyyz == xy
:
xx = x; yy = y; z = 1;
while (yy != 0)
yy P
yy = yy - 1, P
z = z*xx.
while .
:
unsigned int power( int x, int y )
{
if ( x <= 1 || y < 0 )
{
throw -1;
}
unsigned int xx( x ), yy( y ), z( 1 );
while ( yy != 0 )
{
--yy;
z *= xx;
} // while
return z;
422 14

} // power
, Dijkstra . yy
xx = xx2 yy = yy/2 h :
h == xxyy == (xx2)yy/2
, 20

unsigned int power( int x, int y )


{
if ( x <= 1 || y < 0 )
{
throw -1;
}
unsigned int xx( x ), yy( y ), z( 1 );
while ( yy != 0 )
{
while ( even(yy) )
{
xx *= xx;
yy /= 2;
} // while (even(yy))
--yy;
z *= xx;
} // while
return z;
} // power
while ,
' 2, , 0 (),
while.
y, -
log2y.
Manna Waldinger ,
, -
. ,
, :
unsigned int power( int x, int y )
{
if ( x <= 1 || y < 0 )
{
throw -1;
}
unsigned int fv;
if ( y == 0 ) fv = 1;
else fv = x * power( x, y-1 );
return fv;
} // power
! : x0 == 1 xy == xxy-1.
, Dijkstra,
:
unsigned int power( int x, int y )
{
if ( x <= 1 || y < 0 )
{
throw -1;
}
unsigned int fv;

20 even int true (even), false


. :
bool even( int x ) { return ( x % 2 == 0 ); }
II 423

if ( y == 0 )
fv = 1;
else if ( even(y) )
{ unsigned int z( power(x,y/2) );
fv = z*z; }
else
fv = x * power( x, y-1 );
return fv;
} // power
Dijkstra,
!


. , ! ;
; y, y-
1,... 1, 0. , 1xx ... x.
, , log2y.
( y);
,
.
Fibonacci, :21
f0 = 0, f1 = 1, fn = fn-1 + fn-2 n 2
:
unsigned int f( int n )
{
if ( n < 0 )
{
throw n;
}
unsigned int fv;
if ( n < 2 ) fv = n;
else fv = f(n-1) + f(n-2);
return fv;
} // f
. 14-1 f(6). f(4) 2 ,
f(3) 3, f(2) 5 f(1) 8.
, -
:
unsigned int f( int n )
{
if ( n < 0 )
{
throw n;
}
unsigned int fn, fp, fpp;
if ( n < 2 )
{
fn = n;
}
else
{
fp = 0; fn = 1;
for ( int j(1); j < n; ++j )
{
fpp = fp; fp = fn;
fn = fp + fpp;
} // for

21 7-14;
424 14

f(6)

f(5) f(4)

f(4) f(3) f(3) f(2)

f(3) f(2) f(2) f(1) f(2) f(1) f(1) f(0)

f(2) f(1) f(1) f(0) f(1) f(0) f(1) f(0)

f(1) f(0)
. 14-1 f(6).
} // if (n < 2)
return fn;
} // f

. ,
( ).
power().
,
, ;
! .
, , .
, -
' , ,
. ,

. , .
power() :
x ,
y, ,
xy.
. , :
y 1
y == 1. . y == 1
-
y == 1.

14.11 *

. C++ -
.
char
double char '>'
double '<'
.
II 425

, , maxormin(),
: double. ,
char, tel, :
double maxormin(char tel, ...)
; : C++ 22 (ellipsis)
, , .
:
#include <iostream>
#include <cstdarg>

using namespace std;

double maxormin( char tel, ... )


{
if ( tel != '<' && tel != '>' )
{
throw tel;
}
va_list ap;
va_start( ap, tel );

double x( va_arg(ap, double) );


if ( x == 0 )
{
throw 0;
}
double fv( x );
if ( tel == '>' )
{
while ( x != 0 )
{
if ( x > fv ) fv = x;
x = va_arg( ap, double );
}
}
else // tel == '<'
{
while ( x != 0 )
{
if ( x < fv ) fv = x;
x = va_arg( ap, double );
} // while (x != 0)
} // if (tel == '>')
va_end( ap );
return fv;
} // maxormin

int main()
{
double mx = maxormin( '>', 1.1, 2.2, 2.0, 0.4, 0.0 );
double mn = maxormin( '<', 1.1, 2.2, 1.3, 0.4, 7.1, 0.0 );
cout << mx << " " << mn << endl;
} // main
1. cstdarg. va_list
va_arg(), va_start() va_end().
2. ap va_list.
.

22 C!
426 14

3. va_start(ap, tel) va_start() -


(tel)
ap.
4. va_arg(ap, double).
ap
( ).
va_arg (!). .
5. va_end(ap). -
( ).
.
if :
x = va_arg( ap, double ); // x...
fv = x; // ...
x = va_arg( ap, double ); // x...
while ( x != 0 ) // 0 ()
{
if ( x > fv ) fv = x; // x > fv
x = va_arg( ap, double );// x...
} // while
while
0 () x! !
:
double mx = maxormin( '>', 1.1, 2.2, 2.0, 0.4, 0.0 );
0.0 ! -
; , (1 2)
.
( ) -
:
1. -
( 0.0 ). -
!
2. .
.
3. , va_start()

.
4.
(.. char int).
(
).
5.
va_arg(). , 3 2.0
2 .

14.12 ...
( ),
. C++ -
--.
.

II 427

.
.

, (template),
.
-
/ . -


.

: .
: , -

. ()
.

inline:
.
: .
.
: -
. .
,
.


14-1 ( .9-5)
double vectorSumIf( const double x[], int n, bool (*predic)(double) )
x[k] x
predic(x[k]).


14-2 pluMin()
) a1, a2, int, -
, a1, 1 a2 1.
) a1, a2, b1, b2 int,
a1 b1 a2 b2.
, ; .
( ,
).
2 4 .
( )
.
428 14

3 ; -
.
14-3 ( C++ .)
:23
template<typename T1, typename T2>
void f( T1, T2 ); // 1
template<typename T> void f( T ); // 2
template<typename T> void f( T, T ); // 3
template<typename T> void f( T* ); // 4
template<typename T> void f( T*, T ); // 5
template<typename T> void f( T, T* ); // 6
template<typename T> void f( int, T* ); // 7
template<> void f<int>( int ); // 8
void f( int, double ); // 9
void f( int ); // 10

int i;
double d;
float ff;
:
f( i ); // a
f<int>( i ); // b
f( i, i ); // c
f( i, ff ); // d
f( i, d ); // e
f( i, &d ); // f
f( &d, d ); // g
f( &d ); // h
f( d, &i ); // i
f( &i, &i ); // j


b
14-4 , : f ( x)dx
a
x'x y = f (x), x = a b.

(midpoint):
[a,b] h = (b - a)/N.
, h f(xk), xk =
a + (k-0.5)h, k . -
.
N

a f ( x)dx h
b
f ( xk )
k 1
midPoint
, N
.
, errCode midPoint < 1,
errCode 1, , ,
0.
14-5 14.3, : m0 [a0,b0], f(m0).
f(a0)f(m0) 0
[a0,m0]

23 (Sutter 1998).
II 429


[m0,b0]
C++:
a = a0; b = b0;
m = (a + b) / 2;
if (f(a)*f(m) <= 0.0) b = m;
else a = m;
, [a0,m0]
: [a0, m0].
[m0,b0].
bisection.
14-6 (9.4)
:
template<typename T> void merge( T v[], T w[], T z[],
int pv, int tv, int pw, int tw,
int pz, int tz,
bool& ok )
v[pv]...v[tv] w[pw]...w[tw] v, w o
z[pz]...z[tz]. 0 pv tv, 0 pw tw tz - pz + 1 (tv - pv + 1)
+ (tw - pw + 1). , ok false. v[pv]...v[tv]
w[pw] ... w[tw] ' .
z[pz]... z[tz].
14-7 9.6 :

.
, ()2 = N2. : N2.
, , ,
N2.
, :
middle = (from + upto) / 2;
v[from] v[middle]
v[middle+1] v[upto]
z
. -
; ( z). ,
: ; ; -
(merge sort)
Nlog(N), N2.
mergeSort() string.
.
430 14

15
- II
:

,
, C, 1,
- ,
(-)
,
.
:
.
() .
-
.
.
:
-
-

- reinterpret_cast


seek - tell
:
15.1 .......................................................................................................................................................... 432
15.1.1 ............................................................................................................................................436
15.2 ............................................................................................................................................... 436
15.3 ................................................................................................................................................. 437
15.3.1 ! .............................................................................................................................................439
15.4 - ............................................................................................................................. 439
15.5 ........................................................................................... 440
15.5.1 .......................................................................................................................................441
15.6 ..................................................................................................................... 442
15.6.1 * .....................................................................................................................................442

1 C++; .

431
432 15

15.7 ..................................................................................................................... 444


15.8 * ............................................................................................................................................. 447
15.9 * union ........................................................................................................................................................ 448
15.10 ................................................................................................................................ 451
15.11 ..................................................................................................................... 454
15.12 - seek tell ............................................................................ 457
15.12.1 ................................................................................................................459
15.13 - ............................................................................................. 460
15.13.1 * string;................................................................................................................461
15.14 ....................................................................................................................................... 462
15.14.1 ........................................................................................................................................463
15.14.2 .....................................................................................................................................467
15.14.3 .......................................................................................................................................472
15.15 ........................................................................................................................................ 474
................................................................................................................................................................... 474
.............................................................................................................................................................................474
.............................................................................................................................................................................475

:
E Pluribus Unum
E Pluribus Unum.
.
; -
-
.
: .

, , , , , -
. .

.
COBOL (COmmon Business Oriented Language) -
PL/I Algol-60 FORTRAN .
Pascal
(record types) , . Ada
Pascal.
(struct(ure)s) C Pascal. C++
. Java : .
C# .
. : -
() ( ) -
. (
) . -
-
.

15.1
.
, .
, -
.
- II 433

1
:






...
, ,
.
C++ -
: (class). (structure)
-
(object orientation). , , -
:
struct Employee
{
char surname[24];
char firstname[16];
Date birthDate;
int rank;
Date emplDate;
int numberOfChld;
Address home;
}; // Employee
:
Employee clerk, typist, manager;
:
strcpy( clerk.surname, "" );

if ( manager.birthDate < clerk.birthDate )


{
megalhYpotesh();
grafto( clerk );
}
else
tiPerimenes();

( ) ( : ) -
(object) ().
, , -
. -
, , , (.) .
, surname, birthDate,
numberOfChld, rank, (members)2 .

"struct", , "{"
"};". ,
:

2 , (fields). C++
.
434 15

, , ";"
2
8.13 C
FILE. (ISO/IEC 1999) -
-
,
( ),
/,
.
Borland C++, v.5.5 :
struct FILE
{
unsigned char* curp; //
unsigned char* buffer; //
int level; //
int bsize; //
unsigned short istemp; //
unsigned short flags; //
wchar_t hold; // ungetc
//
char fd; // File descriptor
unsigned char token; // Used for validity checking
}; // FILE

3
struct complex
{
double re;
double im;
}; // complex
double.
re im. (complex =
), complex -
. :
struct complex
{
double re, im;
}; // complex
.
struct Date
{
unsigned int year;
unsigned char month;
unsigned char day;
}; // Date

:
struct Address
{
char country[17];
char city[17];
int areaCode;
char street[17];
int number;
}; // Address

- II 435

() -
. :
complex i, j, k;
Date yesterday, today, tomorrow;
Address residence;
:
, struct C, ( )
C++. .
. .., :
complex i, j, k;
: 3
typedef struct { double re; double im; } complex;

.. Employee
Date Address, surname, firstname
.
,
, ..:
complex j = { 0, 1 }, isqrt2 = { 1/sqrt(2), 1/sqrt(2) };
Date d1 = { 2004, 11, 17 };
, :
cout << "( " << j.re << ", " << j.im << " )" << endl;
cout << "( " << isqrt2.re << ", " << isqrt2.im << " )" << endl;
cout << int(d1.day) << '.' << int(d1.month)
<< '.' << d1.year << endl;
:
( 0, 1 )
( 0.707107, 0.707107 )
17.11.2014
, : d1 = { 2004, 11, 17 } (2004)
(d1.year), (11) (d1.month) ...
,
, :
, ,
,
return (
).
4
:
complex conj( complex c )
{
complex cj = { c.re, -c.im };
return cj;
} // conj
. :
k = conj( j );
cout << "( " << k.re << ", " << k.im << " )" << endl;
:

3 :
struct complex i, j, k;
436 15

( 0, -1 )

15.1.1


(13.3, 14.8).
conj() k = conj(j) -
c j. -
j c 16 ( ).


.
, :
complex conj( const complex& c )
{
complex cj = { c.re, -c.im };
return cj;
} // conj
const
. .
13.3:
const
,
-l, .. .
const
.
const -
;
, -
.
const .

15.2
(attribute) .
.

.
,
, .
1
:
i.re
j.im
today.month
residence.city
complex re im. i.re j.im -
i, j complex. , month city Date
- II 437

Address . : Date today Address residence


today.month residence.city today residence
.
Employee ,
:
clerk.emplDate
Date.
:
clerk.emplDate.year
clerk.emplDate.day

(scope) . ,
-
, .
:
. .
. :
struct Q
{
T1 x1; T2 x2; ... Tn xn;
}; // Q
:
Q a, b;

a = b;
:
a.x1 = b.x1; a.x2 = b.x2; ... a.xn = b.xn;

2
:
today = tomorrow;
( ) :
today.day = tomorrow.day;
today.month = tomorrow.month;
today.year = tomorrow.year;

15.3
-:
complex j = { 0, 1 }, isqrt2 = { 1/sqrt(2), 1/sqrt(2) };
Date d1 = { 2004, 11, 17 };
C.
C++; , .
(constructor)
.
() .
:
complex j( 0, 1 ), isqrt2( 1/sqrt(2), 1/sqrt(2) );
:
struct complex
438 15

{
double re;
double im;
complex( double rp, double ip ) { re = rp; im = ip; };
}; // complex
: -
re im.
.
: complex q.
:
struct complex
{
double re;
double im;
complex( double rp, double ip ) { re = rp; im = ip; };
complex() { re = 0.0; im = 0.0; };
}; // complex
-
. -
(default constructor).
complex ( ).
, ,
. -
.
(14.2):
struct complex
{
double re;
double im;
complex( double rp=0.0, double ip=0.0 )
{ re = rp; im = ip; };
}; // complex
2 1:
.
:
complex q;
:
q = complex( 1.7, 8.1 );
, complex -
q. , conj :
complex conj( complex c )
{
return complex( c.re, -c.im );
} // conj
Date :
struct Date
{
unsigned int year;
unsigned char month;
unsigned char day;
Date( int yp=1, int mp=1, int dp=1 )
{ year = yp; month = mp; day = dp; }
}; // Date
:
Date d0( 2011, 3, 5 ) // d0 == 05.03.2011
Date d1; // d1 == 01.01.0001
- II 439

:
Date d2( 2011, 3 ) // d2 == 01.03.2011
Date d3( 2011 ); // d3 == 01.01.2011
, :
:
Date d1( 2004, 14, 37 );
.
, .

15.3.1 !
11.1; :
struct MyType
{
int v;
MyType( int a=0 )
{
cout << "creating a MyType variable. Initialize with "
<< a << endl;
v = a;
}
~MyType()
{
cout << "destroying a MyType variable having value "
<< v << endl;
}
}; // MyType
, ~MyType();
(destructor) MyType. -
MyType. , My-
Type . -
.

15.4 -
- . C++
.
:
complex q;
complex* pC( &q );
q pC :
(*pC).re = 2.5; (*pC).im = 1.03;
:
cout << "*pC = ( " << (*pC).re << ", " << (*pC).im << " )"
<< endl;
: ( *pC) (q)
pC.
.
C++ :
pC->re = 2.5; pC->im = 1.03;
cout << "*pC = ( " << pC->re << ", " << pC->im << " )" << endl;
; (*). : ->.
440 15

15.5
, :
struct Q
{
T1 x1; T2 x2; ... Tn xn;
}; // Q
:
Q a, b;

a == b
, , :
(a.x1 == b.x1) && (a.x2 == b.x2) && ... && (a.xn == b.xn)
.
== . , -
complex; 14.6.4, :4
bool operator==( const complex& lhs, const complex& rhs )
{
return lhs.re == rhs.re && lhs.im == rhs.im;
} // bool operator==( const complex
:
if ( isqrt2 == j ) . . .
== ( ) .
+, -, *, /.
- (-
) . 14.6.4, :
complex operator-( const complex& lhs )
{
return complex( -lhs.re, -lhs.im );
} // operator-( const complex
:
cout << isqrt2 << endl;
:
cout << "( " << isqrt2.re << ", " << isqrt2.im << " )" << endl;
<< 14.6.1:
ostream& operator<<( ostream& tout, const complex rhs )
{
return tout << "( " << rhs.re << ", " << rhs.im << " )";
} // operator<<( ostream& tout, const complex
Date :
cout << d1 << endl;

cout << int(d1.day) << '.' << int(d1.month)
<< '.' << d1.year << endl;
:

4 , double
.
- II 441

ostream& operator<<( ostream& tout, const Date& rhs )


{
return tout << static_cast<unsigned int>(rhs.day) << '.'
<< static_cast<unsigned int>(rhs.month) << '.'
<< rhs.year;
} // operator<<( ostream& tout, const Date
Address; ,
!...
15.1 manager.birthDate < clerk.birthDate.
< Date.
Date d1, d2;
d1 < d2 true
d1 d2.
14.6.4,
:
Trv operator<( Tl lhs, Tr rhs )
, :
Tl Tr const Date&
Trv bool.
:
bool operator<( const Date& lhs, const Date& rhs )
: .
:
bool operator<( const Date& lhs, const Date& rhs )
{
bool fv;

if ( lhs.year < rhs.year ) fv = true;


else if ( lhs.year > rhs.year ) fv = false;
else // lhs.year == rhs.year
{
if ( lhs.month < rhs.month ) fv = true;
else if ( lhs.month > rhs.month ) fv = false;
else // lhs.year == rhs.year && lhs.month == rhs.month
fv = ( lhs.day < rhs.day );
}
return fv;
} // operator<( const Date . . .
,
.

15.5.1
. ;
.
.
, Employee,
,
. Employee
:
bool operator==( const Employee& lhs, const Employee& rhs )
{
return ( strcmp(lhs.surname, rhs.surname)==0 &&
strcmp(lhs.firstname, rhs.firstname)==0 &&
lhs.birthDate == rhs.birthDate );
442 15

} // operator==( const Employee


Date.
:
bool operator==( const Date& lhs, const Date& rhs )
{
return ( lhs.year == rhs.year && lhs.month == rhs.month &&
lhs.day == rhs.day );
}; // operator==( const Date
==
Address.
() surname, firstname, birthDate (key)
Employee.5
, -
. < Employee.
bool operator<( const Employee& lhs, const Employee& rhs )
{
bool fv;
if ( strcmp(lhs.surname, rhs.surname) < 0 ) fv = true;
else if ( strcmp(lhs.surname, rhs.surname) > 0 ) fv = false;
else // strcmp(lhs.surname, rhs.surname)==0
{
if ( strcmp(lhs.firstname, rhs.firstname) < 0 ) fv = true;
if ( strcmp(lhs.firstname, rhs.firstname) > 0 ) fv = false;
else // strcmp(lhs.surname, rhs.surname)==0 &&
// strcmp(lhs.firstname, rhs.firstname)==0
fv = lhs.birthDate < rhs.birthDate;
}
return fv;
}; // operator<( const Employee
==
: . :

. <
Date .

15.6
C++
- ()
( ).
!
-
. .

15.6.1 *
:
#include <iostream>

5 .
. ,
, (surrogate) -
, , .
- II 443

using namespace std;

struct Address
{
char country[17];
char city[17];
int areaCode;
char street[17];
int number;
}; // Address

int main()
{
Address a;

cout << " sizeof a: " << (sizeof a) << endl;


cout << " members: "
<< sizeof(a.country) + sizeof(a.city) +
sizeof(a.areaCode) + sizeof(a.street) +
sizeof(a.number) << endl;
cout << " address of a: "
<< reinterpret_cast<long int>(&a) << endl;
cout << " address of a.country: "
<< reinterpret_cast<long int>(a.country) << " "
<< reinterpret_cast<long int>(&a) << endl;
cout << " address of a.city: "
<< reinterpret_cast<long int>(a.city) << " "
<< reinterpret_cast<long int>(a.country)+sizeof(a.country)
<< endl;
cout << " address of a.areaCode: "
<< reinterpret_cast<long int>(&a.areaCode) << " "
<< reinterpret_cast<long int>(a.city)+sizeof(a.city)
<< endl;
// . . .
,
- (sizeof a)
(sizeof(a.country) + sizeof(a.city) + sizeof(a.areaCode) +
sizeof(a.street) + sizeof(a.number)),
(a.country) -
(&a).
(.. a.city)
(a.country) (sizeof(a.
country)).
reinterpret_cast<long int>(&a) :
&a long int ( ) ,
.
Borland C++ 5.02 ( Win32) :
sizeof a: 59
members: 59
address of a: 1245008
address of a.country: 1245008 1245008
address of a.city: 1245025 1245025
address of a.areaCode: 1245042 1245042
address of a.street: 1245046 1245046
address of a.number: 1245063 1245063
:
- (59)
.
444 15

(1245008)
a.

.
Borland C++ 5.5 ( Win32)
C++ :
sizeof a: 64
members: 59
address of a: 1245004
address of a.country: 1245004 1245004
address of a.city: 1245021 1245021
address of a.areaCode: 1245040 1245038
address of a.street: 1245044 1245044
address of a.number: 1245064 1245061
. gcc (Dev-C++). :
- (64)
(59).
a.areaCode -
(1245038) (1245040). ,
a.number (1245061)
.
:
(padding). ,

(word) , .., 2 4 .
:
struct cl1
{
char c1;
int klm;
// ...
};
-
, c1
.
Borland C++ 5.5 gcc:
int
4.

15.7
( . 1
) : C++ -
long int 4 , float.
7.345F 7L, 7.345F
long int, (111); (!!!)
:
float ff( 7.345 );
long int nn( static_cast<long>(ff) );
: , static_cast<long>
(ff)
( float long)
- II 445

( 7.345 7).
:
long* pl( &ff );
cout << (*pl) << endl;
*pl.
:
Cannot convert 'float*' to 'long*'
; :
long* pl( reinterpret_cast<long*>(&ff) );
cout << (*pl) << endl;
:
7 1089145405

7 . ,
,
( long float)
( 7.345 7).
; pl, long*,
&ff, float*. ; , ,
C++, , long* ll(
&ff )6.
:
,
( ),
,
.
, pl ff long*
float. pl
(1089145405)
ff long.
:
reinterpret_cast< T >( )
T , , .
. , -
(reinterpretation casting),
.
union, .
: , C++, -
: , C++ , k, unsigned short int,
, k/256
k%256. , , :
unsigned short int k( 8548 );
:
cout << (k%256) << " " << (k/256) << endl;
:
100 33

6 ;
.
446 15

;
:
char* p;
p - char.
:
p = reinterpret_cast<char*>(&k);
; k ( k)
char, p.
, - char, k,
int. 12.1, C++
. , :
cout << p[0] << " " << p[1] << endl;
: :
d !
:
cout << static_cast<int>(p[0]) << " "
<< static_cast<int>(p[1]) << endl;
:
100 33
(15.7) (
) . ,
. , :
float a[10];
int aToInt( reinterpret_cast<int>(a) );
aToInt a.
:
reinterpret_cast<float*>( aToInt + k*sizeof(float) )
a+k &a[k]. ,
.
C++,
: 7
. IT

T* p;
:
reinterpret_cast<T*>(reinterpret_cast<IT>(p)) p
:
.
(addressing)
.


. ; :
. ,
.

7 : Windows (Win32) 32
. BC++ 5.5 Dev-C++ 32 int
long int.
- II 447

15.8 *
(Kernighan & Ritchie
1988):
struct flags1
{
bool isKeyword;
bool isExtern;
bool isStatic;
}; // flags1

cout << "sizeof flags1: " << (sizeof(flags1)) << endl;
:
sizeof flags1: 3
() 3 .
; , :
struct flags2
{
bool isKeyword: 1;
bool isExtern: 1;
bool isStatic: 1;
}; // flags2
flags2 1 .
isKeyword, isExtern, isStatic (fields) -
(bit-fields). ,
:
, , ":",
: int, unsigned int, char, unsigned char, wchar_t, bool.
-
. , int char -
. unsigned , ,
. , -
( ' ).
.
:
flags2 aSymbol;
flags2* pToSymbol;
, , :
aSymbol.isKeyword aSymbol.isExtern
pToSymbol->isExtern pToSymbol->isStatic


:
struct time1
{
unsigned short year;
unsigned char month;
unsigned char day;
unsigned char hour;
unsigned char min;
unsigned char sec;
}; // time1
448 15

, unsigned char -
.
8 (gcc - Dev-C++, BC++ v.5.5).
:
4095 12 ,
(1-12) 4 (0 - 15),
(1-31) 5 (0 - 31),
(0 - 23) 5 (0 - 31),
(0 - 59) 6 (0 - 63)
(0 - 59) 6 (0 - 63).
: 38 5 8 ( 60%
).
C++ :
struct time2
{
unsigned int year: 12;
unsigned char month: 4;
unsigned char day: 5;
unsigned char hour: 5;
unsigned char min: 6;
unsigned char sec: 6;
}; // time2
6 (gcc - Dev-C++, BC++ v.5.5).


, ( ) .
; () .
struct union (
) class ( ).

15.9 * union

.
unsigned short int char .
.
, union. -
. :
union U
{
char c;
int i;
}; // U

U m;
:
m.c = 'a'; m.i = 70;
cout << m.c << endl;
:
F
:
m.i = 180; m.c = 'q';
- II 449
m.c = a; m.i = 70; m.i = 100; m.c = q;
m.c

a F d q
??? 0 0 0
97 70 100 113

m.i
() () () ()
. 15-1 union { char c; int i; } m.
m.i, int, ().
m.c.
. ()
m.c = 'a'.
'a', 97.
() m.i = 70.
70 : 70 ( ) 0
. m.c,
,
'F'. () () m.i = 180
m.c = 'q' .
cout << m.i << endl;
:
113
m.c 'a' F. m.i
180 113. ;
union . ,
,
. ; int 2
char 1 . m
. 15-1. ,
.
15.7 :
union U1
{
char c[2];
unsigned short int i;
}; // U1
:
U1 u1;

u1.i = 8548;
cout << u1.c[0] << " " << u1.c[1] << endl;
cout << static_cast<int>(u1.c[0]) << " "
<< static_cast<int>(u1.c[1]) << endl;
:
d !
100 33
union . , ,
:
a * b + c / d
. 15-2.
: :
struct Node
450 15

{ +
char oper;
Node* arg1;
Node* arg2;
}; // Node
, * /
. -
a b c d
. -
- . 15-2 -
. : -
.
struct Node
{
char oper;
double arg1;
double arg2;
}; // Node
:
struct Node;

union Arg
{
double d;
Node* p;
}; // Arg

struct Node
{
char oper;
char leftArgKind; Arg leftArg;
char rightArgKind; Arg rightArg;
}; // Node
struct Node ,
Arg, Node* p.
Node, oper, leftArg, rightArg, leftArgKind,
rightArgKind.
leftArg . rightArgKind rightArg.
:
Node root, mulT, divT;
pr :
root.oper = '+';
root.leftArgKind = 'p'; root.leftArg.p = &mulT;
root.rightArgKind = 'p'; root.rightArg.p = &divT;
, root.leftArgKind () p (
mulT). root.leftArgKind 'p' root.leftArgKind
p.
mulT divT :
mulT.oper = '*';
mulT.leftArgKind = 'd'; mulT.leftArg.d = a;
mulT.rightArgKind = 'd'; mulT.rightArg.d = b;
divT.oper = '/';
divT.leftArgKind = 'd'; divT.leftArg.d = c;
divT.rightArgKind = 'd'; divT.rightArg.d = d;
mulT.leftArg d, a.
mulT.leftArgKind 'd' mulT.leftArg
d.
:
. . . eval( &root ) . . .
- II 451

:
double eval( Node* r )
{
double argL, argR, fv;

argL = (r->leftArgKind == 'd') ?


r->leftArg.d : eval(r->leftArg.p);
argR = (r->rightArgKind == 'd') ?
r->rightArg.d : eval(r->rightArg.p);
switch ( r->oper )
{
case '+': fv = argL + argR; break;
case '-': fv = argL - argR; break;
case '*': fv = argL * argR; break;
case '/': fv = argL / argR; break;
// default: throw . . .
}
return fv;
} // eval

15.10
:
! ,
Murphy : .8
, ,
:
.
.
.
. -
14.9
:
struct ApplicXptn
{
enum { domainErr, paramErr };
char funcName[100];
int errCode;
double errDblVal1, errDblVal2, errDblVal3;

ApplicXptn( const char* fn, int ec,


double dv1, double dv2 = 0, double dv3 = 0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
errDblVal1 = dv1; errDblVal2 = dv2; errDblVal3 = dv3; }
}; // ApplicXptn
( ) . :
char funcName[100]: .
int errCode: -
. .
(domainErr = 0, paramError = 1).
.
double errDblVal1, errDblVal2, errDblVal3:
.

8 There is always one more bug.


452 15

:
. :
. .
:
double v( double x )
{
const double a( -1 ), b( 1 ), T( b-a );
double m( floor( (x-a)/T ) ), x0( x - m*T ), fv;

// (-1 <= x0 < 1) && (v(x0) == v(x))


if ( x0 == 0 )
throw ApplicXptn( "v", ApplicXptn::domainErr, x );
// (-1 <= x0 < 1) && (x0 != 0) && (v(x0) == v(x))
fv = -1/fabs(x0+2) - 1/fabs(x0) - 1/fabs(x0-2);
return fv;
} // v
, throw -
. :
"v": .
ApplicXptn::domainErr: . ;
1.2 std::cout, std::endl. : domainErr
ApplicXptn.9
x: .
void pqer( double x, double y, double z, double& t, double& u )
{
if ( x == y || x == -y || z <= 0 )
throw ApplicXptn( "pqer", ApplicXptn::paramErr, x, y, z );
t = x*y*pow(z, x-y)/(x*x-y*y);
u = (x*y-1/x)/z;
} // pqer
(x, y, z) .
catch catch(...):
int main()
{
double t, u;

try
{
// . . .
pqer( 1, 2, 3, t, u );
// . . .
for ( int k(-10); k <= 10; ++k )
{
cout << " v(" << (k/2.0) << ") = " << v(k/2.0) << endl;
} // for (int k...
// . . .
}
catch ( ApplicXptn& x )
{
switch ( x.errCode )
{
case ApplicXptn::domainErr:
cout << " " << x.funcName << " "
<< x.errDblVal1 << endl;
break;
case ApplicXptn::paramErr:
cout << " " << x.funcName
<< " " << x.errDblVal1

9 , () .
- II 453

<< ", " << x.errDblVal2 << ", " << x.errDblVal2
<< endl;
break;
default:
cout << " ApplicXptn "
<< x.funcName << endl;
} // switch
}
catch( ... )
{
cout << " " << endl;
}
} // main

:
#include <iostream>

using namespace std;

struct ApplicXptn
{
char funcName[100];
int errCode;
int iErrVal1;
int iErrVal2;

enum { paramError, factOfNeg };


ApplicXptn ( const char* fn, int ec, int iv1=0, int iv2=0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = \0;
errCode = ec;
iErrVal1 = iv1; iErrVal2 = iv2; }
}; // ApplicXptn

unsigned long int factorial( int n );


unsigned long int comb( int m, int n );

int main()
{
int m, n;

cout << " m, n <= 50, m >= n: ";


cin >> m >> n;
try
{
cout << " "
<< m << " " << n << " = " << comb( m, n ) << endl;
}
catch ( ApplicXptn x )
{
switch ( x.errCode )
{
case ApplicXptn::paramError:
cout << " " << x.funcName
<< " ( "
<< x.iErrVal1 << " < " << x.iErrVal2 << " )"
<< endl;
break;
case ApplicXptn::factOfNeg:
cout << " " << x.funcName
<< " ( "
<< x.iErrVal1 << " )" << endl;
break;
default:
cout << " "
<< x.funcName << " : " << x.iErrVal1 << ", "
<< x.iErrVal2 << endl;
454 15

} // switch
} // catch
} // main

// natProduct -- m*(m+1)*...*(n-1)*n
unsigned long int natProduct( int m, int n )
{
if ( m <= 0 || n < m )
throw ApplicXptn( "natProduct",
ApplicXptn::paramError, m, n );
// 0 < m <= n
unsigned long int fv(m);
for ( int k(m+1); k <= n; ++k ) fv *= k;
return fv;
} // natProduct

// factorial -- n!
unsigned long int factorial( int n )
{
try
{
return ( n == 0 ) ? 1 : natProduct( 1, n );
}
catch( ApplicXptn x )
{
throw ApplicXptn( "factorial",
ApplicXptn::factOfNeg, n );
}
} // factorial

// comb -- m n
unsigned long int comb( int m, int n )
{
unsigned long int fv;

if ( n < m-n ) fv = natProduct(m-n+1,m)/factorial(n);


else fv = natProduct(n+1,m)/factorial(m-n);
return fv;
} // comb
:
1.
natProduct() m n.
2. ,
natProduct() ,
factorial() natProduct()
.
, -
. ,
catch.
.

15.11
, ,
() .
, .
8.6 :
:
double sum( 0 );
- II 455

int n( 0 );
ofstream a( "fltnum.dta", ios_base::binary );
cout << " - 9999 : "; cin >> x;
while ( x != sentinel )
{
//
a.write( reinterpret_cast<const char*>(&x), sizeof(x) );
++n;
sum += x;
cout << " - 9999 : "; cin >> x;
} // while
a.close();
cout << " " << n << " " << endl;
:
if ( n > 0 )
{
double avrg( sum/n );
cout << " = " << sum
<< " <x> = " << avrg << endl;
ifstream b( "fltnum.dta", ios_base::binary );
int m( 0 );
b.read( reinterpret_cast<char*>(&x), sizeof(x) );
while ( !b.eof() )
{
++m;
y = exp( (avrg-x)/avrg );
cout << " x[";
cout.width(3); cout << m << "] = ";
cout.width(6); cout << x << " y[";
cout.width(3); cout << m << "] = " ;
cout.width(6); cout << y << endl;
b.read( reinterpret_cast<char*>(&x), sizeof(x) );
} // while
b.close();
}
, fltnum.dta (binary,
unformatted). ,
. a :
ofstream a( "fltnum.dta", ios_base::binary );
fltnum.dta, , .
, , :
ofstream a;
:
a.open( "fltnum.dta", ios_base::binary );
, b :
ifstream b( "fltnum.dta", ios_base::binary );
fltnum.dta .
, , , :
ifstream b;
:
b.open( "fltnum.dta", ios_base::binary );
,
fstream a;
a :
a.open( "fltnum.txt",
ios_base::in|ios_base::out|ios_base::binary );
;
456 15

ofstream write(), :
, p, char (: const char*).
n.
a.write( p, n ) :
a, n ,
p.
, x.
:
a.write( &x, sizeof(x) );
. , &x -
sizeof(x)
. &x: double* (
double) write() const char*. -
. :
a.write( reinterpret_cast<const char*>(&x), sizeof(x) );
, ifstream read(), ,
write(). b.read(p, n) : b, n
, p. , p
char*. , :
b.read( reinterpret_cast<char*>(&x), sizeof(x) );
fstream write() read().
, ,

,

(, formatting) -
.
:
,
-
,
.
:
:
. -

.

( ).
.
,
. -
.
.
- II 457

15.12 - seek tell


.
(records) -
. , , ,
, sizeof(double) 8 , 0 -
0 7, 1 8
15, k k8 (k+1)8-1. -
,
, -
, (random access file). C++ -
seekg() seekp().
. 8 seekg(), a.seekg(0)
a.
seekg() ifstream, fstream .
a, ,
a.seekg(n), n , ,
, n .

0 ().
: seekg() -
text .

ranfl.txt :
45____89___54
_____-3___4.67___dagdash___jkfs_jfejk
___1
:
ifstream f( "ranfl.txt" );
double x;

for ( int k(0); k <= 12; k += 2 )


{
f.seekg( k ); f >> x;
cout << x << endl;
}
; :
45
89
89
89
54
54
4
: f.seekg(0); f >> x, 0
45.
f.seekg(2); f >> x, -
2 ( 45) -
, 89.
f.seekg(4); f >> x,
45 89
f.seekg(6).
458 15

k 8 10
89 f.seekg(k); f >> x 54.
k 12 f.seekg(k), -
4 54.

, -
(text) ()
.
seekg() -
:
f.seekg(0) .
f.seekg(0, ios_base::end) ,
.
ofstream fstream seekp, ,
.
seekg() seekp
.
x T fstream a,
T. , :
a.open( "...", ios_base::in|ios_base::out|ios_base::binary );

a.seekg( n*sizeof(T) );
a.read( reinterpret_cast<char*>(&x), sizeof(T) );
n , :
/ ' nsizeof(T)

read , x
n .
, x n
:
a.seekp( n*sizeof(T) );
a.write( reinterpret_cast<const char*>(&x), sizeof(T) );
seekg() seekp()
.

:
a.seekg( n*sizeof(T) );
a.read( reinterpret_cast<char*>(&x), sizeof(T) );
// x
a.seekp( n*sizeof(T) );
a.write( reinterpret_cast<const char*>(&x), sizeof(T) );
seekg() seekp() tellg() tellp().
k = a.tellg();
a , k (long)
. , :
k = a.tellp();
a , k (long)
.
- II 459

15.12.1
seekg() tellg() .
ios_base::binary -
:
a.seekg( 0, ios_base::end );
k = a.tellg();
:
, .
, a.seekg(n, ios_base::end) : n
.
:

:
a.open( "myFileName.dta",
ios_base::in|ios_base::binary|ios_base::ate );
k = a.tellg();
(8.12) open() ios_base::ate
.

, text -
, ,
.
:
ifstream a( "abc.txt",
ios_base::in|ios_base::binary|ios_base::ate );
char t[16000];
long flSize;

// a.seekg( 0, ios_base::end ); ios_base::ate


flSize = a.tellg();
if ( flSize <= 16000 )
{
a.seekg( 0 );
a.read( t, flSize );
}
a.close();
:
1. ios_base::binary: .
: read() write() .
2. , , . -
<cr><lf> ( C++:'\r''\n'), !10
3. , , '\0'
. (t[flSize] = '\0').
4. -
.

T
11:

10 ios_base::binary
( ) '\r''\n' '\n'.
11 .
.
460 15

( flSize )
T (sizeof(T) ).

15.13 -
, , int double -
, struct (
) .
. ,

(in situ, in place):
a.seekg( n*sizeof(T) );
a.read( reinterpret_cast<char*>(&x), sizeof(T) );
// x
a.seekp( n*sizeof(T) );
a.write( reinterpret_cast<const char*>(&x), sizeof(T) );
.


. ,
sizeof(T) .
: -
a.write( reinterpret_cast<const char*>(&x), sizeof(T) );
. ..
struct Address
{
char country[17];
char city[17];
int areaCode;
char street[17];
int number;
}; // Address
:
void address_save( const Address& a, ostream& bout )
{
bout.write( a.country, sizeof(a.country) );
bout.write( a.city, sizeof(a.city) );
bout.write( reinterpret_cast<const char*>(&a.areaCode),
sizeof(a.areaCode) );
bout.write( a.street, sizeof(a.street) );
bout.write( reinterpret_cast<const char*>(&a.number),
sizeof(a.number) );
}; // Address_save
seekg() seekp() sizeof(T)
. Address :
struct Address
{
enum { countrySz = 17, citySz = 17, streetSz = 17,
saveSize = countrySz + citySz + sizeof(int) +
streetSz + sizeof(int) };
char country[countrySz];
char city[citySz];
int areaCode;
char street[streetSz];
int number;
}; // Address
- II 461

saveSize:
a.seekg( n*Address::saveSize );
address_load( x, a );
// x
a.seekp( n*Address::saveSize );
address_save( x, a );
:
1. a :
fstream a( "...",
ios_base::in|ios_base::out|ios_base::binary );
2. address_load(); :
void address_load( Address& a, istream& bin )
{
bin.read( a.country, sizeof(a.country) );
bin.read( a.city, sizeof(a.city) );
bin.read( reinterpret_cast<char*>(&a.areaCode),
sizeof(a.areaCode) );
bin.read( a.street, sizeof(a.street) );
bin.read( reinterpret_cast<char*>(&a.number),
sizeof(a.number) );
}; // Address_load
1-1 read() address_load() write()
address_save().
3.
Address::saveSize sizeof(Address).
4. -
; , .

15.13.1 * string;
countrySz, citySz, streetSz -
, char. -
. string
. ,
:
struct Address
{
enum { countrySz = 17, citySz = 17, streetSz = 17,
maxSize = 17,
saveSize = countrySz + citySz + sizeof(int) +
streetSz + sizeof(int) };
string country;
string city;
int areaCode;
string street;
int number;
}; // Address
, address_save() :
void address_save( const Address& a, ostream& bout )
{
char tmp[Address::maxSize];
strncpy( tmp, a.country.c_str(), Address::countrySz-1 );
tmp[Address::countrySz-1] = '\0';
bout.write( tmp, Address::countrySz );
strncpy( tmp, a.city.c_str(), Address::citySz-1 );
tmp[Address::citySz-1] = '\0';
bout.write( tmp, Address::citySz );
bout.write( reinterpret_cast<const char*>(&a.areaCode),
462 15

sizeof(a.areaCode) );
strncpy( tmp, a.street.c_str(), Address::streetSz-1 );
tmp[Address::streetSz-1] = '\0';
bout.write( tmp, Address::streetSz );
bout.write( reinterpret_cast<const char*>(&a.number),
sizeof(a.number) );
}; // address_save
a.country;
countrySz .
countrySz1 ( ) tmp
(tmp[countrySz-1])
.
tmp (countrySz ).
countrySz a.country
.c_str(); countrySz .12
city, street.
:
void address_load( Address& a, istream& bin )
{
char tmp[Address::maxSize];
bin.read( tmp, Address::countrySz ); a.country = tmp;
bin.read( tmp, Address::citySz ); a.city = tmp;
bin.read( reinterpret_cast<char*>(&a.areaCode),
sizeof(a.areaCode) );
bin.read( tmp, Address::streetSz ); a.street = tmp;
bin.read( reinterpret_cast<char*>(&a.number),
sizeof(a.number) );
}; // address_load
a.country = tmp ( ) tmp
('\0').
string -
; , -
() . , : -

...

15.14
:
, elements.dta, -
. :
struct Elmn
{
unsigned short int eANumber; //
float eAWeight; //
char eSymbol[4];
char eName[14];
}; // Elmn
:
void Elmn_save( const Elmn& a, ostream& bout )
{
bout.write( reinterpret_cast<const char*>(&a.eANumber),
sizeof(a.eANumber) );
bout.write( reinterpret_cast<const char*>(&a.eAWeight),

12 ;
- II 463

sizeof(a.eAWeight) );
bout.write( a.eSymbol, sizeof(a.eSymbol) );
bout.write( a.eName, sizeof(a.eName) );
} // Elmn_save
1 ( : 1),
(..: 2) k-
..= k.
eName .
, : elementsGr.dta,
:
struct GrElmn
{
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[4];
char geName[14];
char geGrName[14];
}; // GrElmn
geGrName . -
,
.
:
.
. ,
, .
.

15.14.1
: ,
:
bin
bout

while ( !bin.eof() )
{



} // while

:
ifstream bin( "elements.dta", ios_base::binary );
if ( bin.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotOpen,
"elements.dta" );
ofstream bout( "elementsGr.dta", ios_base::binary );
if ( bout.fail() )
{
bin.close();
throw ApplicXptn( "main", ApplicXptn::cannotCreate,
"elementsGr.dta" );
}
// ...
: ,
, !
464 15

: Elmn_load()
Elmn_save() (
).
void Elmn_load( Elmn& a, istream& bin )
{
bin.read( reinterpret_cast<char*>(&a.eANumber),
sizeof(a.eANumber) );
bin.read( reinterpret_cast<char*>(&a.eAWeight),
sizeof(a.eAWeight) );
bin.read( a.eSymbol, sizeof(a.eSymbol) );
bin.read( a.eName, sizeof(a.eName) );
if ( bin.fail() && !bin.eof() )
throw ApplicXptn( "Elmn_load", ApplicXptn::cannotRead );
} // Elmn_load
-
bin bin.eof().
:
Elmn oneElmn;
:
Elmn_load( oneElmn, bin );
GrElmn -
:
struct GrElmn
{
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
}; // GrElmn
, .

Elmn GrElmn.
:
GrElmn GrElmn_copyFromElmn( const Elmn& a )
{
GrElmn fv;
fv.geANumber = a.eANumber;
fv.geAWeight = a.eAWeight;
strcpy( fv.geSymbol, a.eSymbol );
strcpy( fv.geName, a.eName );
fv.geGrName[0] = '\0';
return fv;
} // GrElmn_copyFromElmn
:
GrElmn oneGrElmn;
oneGrElmn = GrElmn_copyFromElmn( oneElmn );
.
:
void GrElmn_save( const GrElmn& a, ostream& bout )
{
bout.write( reinterpret_cast<const char*>(&a.geANumber),
sizeof(a.geANumber) );
bout.write( reinterpret_cast<const char*>(&a.geAWeight),
sizeof(a.geAWeight) );
- II 465

bout.write( a.geSymbol, sizeof(a.geSymbol) );


bout.write( a.geName, sizeof(a.geName) );
bout.write( a.geGrName, sizeof(a.geGrName) );
if ( bout.fail() )
throw ApplicXptn( "GrElmn_save", ApplicXptn::cannotWrite );
} // GrElmn_save
, .
:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct ApplicXptn
{
enum { cannotOpen, cannotCreate, cannotClose,
cannotWrite, cannotRead };
char funcName[100];
int errCode;
char errStrVal[100];
ApplicXptn( const char* fn, int ec, const char* sv="" )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // ApplicXptn

struct Elmn
{
unsigned short int eANumber; //
float eAWeight; //
char eSymbol[4];
char eName[14];
}; // Elmn

void Elmn_load( Elmn& a, istream& bin );

struct GrElmn
{
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
}; // GrElmn

void GrElmn_save( const GrElmn& a, ostream& bout );


GrElmn GrElmn_copyFromElmn( const Elmn& a );

int main()
{
try
{
// bin
ifstream bin( "elements.dta", ios_base::binary );
if ( bin.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotOpen,
"elements.dta" );
// bout
ofstream bout( "elementsGr.dta", ios_base::binary );
if ( bout.fail() )
{
bin.close();
466 15

throw ApplicXptn( "main", ApplicXptn::cannotCreate,


"elementsGr.dta" );
}
//
Elmn oneElmn;
int k( 0 );
Elmn_load( oneElmn, bin );
while ( !bin.eof() )
{
//
GrElmn oneGrElmn;
oneGrElmn = GrElmn_copyFromElmn( oneElmn );
//
GrElmn_save( oneGrElmn, bout );
++k;
//
Elmn_load( oneElmn, bin );
}
//
bout.close();
if ( bout.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotClose,
"elementsGr.dta" );
bin.close();
cout << " " << k << " " << endl;
}
catch( ApplicXptn& x )
{
switch ( x.errCode )
{
case ApplicXptn::cannotOpen:
cout << "cannot open file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case ApplicXptn::cannotCreate:
cout << "cannot create file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case ApplicXptn::cannotClose:
cout << "cannot close file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case ApplicXptn::cannotWrite:
cout << "cannot write to file " << x.errStrVal
<< " in " << x.funcName << endl;
break;
case ApplicXptn::cannotRead:
cout << "cannot read from file " << x.errStrVal
<< " in " << x.funcName << endl;
break;
default:
cout << "unexpected ApplicXptn from "
<< x.funcName << endl;
} // switch
} // catch( ApplicXptn ...
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main
,
.
, -
. , , -
- II 467

.
!
: !
! ! (
).

15.14.2
. -
, elementsGr.dta, (
). :
fstream bInOut;
string flNm( "elementsGr.dta" );
:
bool ok;
do {
bInOut.open( flNm.c_str(),
ios_base::in|ios_base::out|ios_base::binary );
if ( bInOut.fail() )
{
ok = false;
cout << "cannot open " << flNm << endl;
cout << "file name ('x' to exit): ";
getline( cin, flNm, \n );
}
else
ok = true;
} while ( !ok && flNm != "x" && flNm != "X" );
:
void openFile( string& flNm, fstream& bInOut )
{
string prevFlNm;
bool ok;
do {
bInOut.open( flNm.c_str(),
ios_base::in|ios_base::out|ios_base::binary );
if ( bInOut.fail() )
{
ok = false;
prevFlNm = flNm;
cout << "cannot open " << flNm << endl;
cout << "file name ('x' to exit): ";
getline( cin, flNm, '\n' );
}
else
ok = true;
} while ( !ok && flNm != "x" && flNm != "X" );
if ( !ok )
throw ApplicXptn( "openFile", ApplicXptn::cannotOpen,
prevFlNm.c_str() );
} // openFile
flNm "x" "X". ,
.
prevFlNm open().
. : -
(..) . ..;
1 . -
.
468 15

grName. ,
, . , ...
( ).
0, : 0 .. . -
.
, :
.. ( )
..
while ( .. != 0 )
{




..
}
.. ( )

void countRecords( fstream& bInOut, unsigned int& noOfRecords )


{
unsigned long int initialPos;
unsigned long int flSize;

initialPos = bInOut.tellg();
bInOut.seekg( 0, ios_base::end ); flSize = bInOut.tellg();
noOfRecords = flSize / GrElmn::saveSize;
bInOut.seekg( initialPos );
} // countRecords
:
unsigned int maxAtNo;
:
countRecords( bInOut, maxAtNo );
initialPos:
(initialPos = bInOut.tellg()) , ,
(bInOut.seekg( initialPos )).
C++:
void readAtNo( int maxAtNo, int& aa )
{
string aastr;

do {
cout << " Atomic Number (1.." << maxAtNo
<< ", 0 to exit): ";
getline( cin, aastr, '\n' );
aa = atol( aastr.c_str() );
} while( aa < 0 || maxAtNo < aa );
} // readAtNo

Elmn_load(), GrElmn_load:
void GrElmn_load( GrElmn& a, istream& bin )
{
bin.read( reinterpret_cast<char*>(&a.geANumber),
sizeof(a.geANumber) );
bin.read( reinterpret_cast<char*>(&a.geAWeight),
sizeof(a.geAWeight) );
bin.read( a.geSymbol, sizeof(a.geSymbol) );
bin.read( a.geName, sizeof(a.geName) );
bin.read( a.geGrName, sizeof(a.geGrName) );
if ( bin.fail() )
- II 469

throw ApplicXptn( "GrElmn_load", ApplicXptn::cannotRead );


} // GrElmn_load
: , -
. -
; 0 ()
, .. 1, 1
, .. 2 : k-1
.. k. , , -
, GrElmn::saveSize aa-1 ,
.. aa, (aa-1)*GrElmn::saveSize.
:
:
void readRandom( GrElmn& a, istream& bin, int atNo )
{
if ( bin.fail() )
throw ApplicXptn( "readRandom", ApplicXptn::streamNotOpen );
if ( atNo <= 0 )
throw ApplicXptn( "readRandom",
ApplicXptn::rangeErr, atNo );
bin.seekg( (atNo-1)*GrElmn::saveSize );
GrElmn_load( a, bin );
} // readRandom
main :
GrElmn a;
:
readRandom( a, bInOut, aa );

:
void GrElmn_display( const GrElmn& a, ostream& tout )
{
tout << "atomic number: " << a.geANumber << endl
<< "atomic weight: " << a.geAWeight << endl
<< "symbol: " << a.geSymbol << endl
<< "name: " << a.geName << endl
<< "greek name: " << a.geGrName << endl;
} // GrElmn_display
geGrName; ; -
,
.
GrElmn_display main :
GrElmn_display( a, cout );
:
cin >> newGrName;
strcpy( a.geGrName, newGrName.c_str() );
newGrName string. , , ,
,
.
<enter>
. cin >> newName, , ,
. getline( cin, newGrName, '\n' ).

.
:
470 15





:



if ( )

:
void editGrName( fstream& bInOut, int atNo )
{
GrElmn a;
readRandom( a, bInOut, atNo );
GrElmn_display( a, cout );
string newGrName;
cout << "new greek name: "; getline( cin, newGrName, '\n' );
if ( !newGrName.empty() )
{
GrElmn_setGrName( a, newGrName );
writeRandom( a, bInOut );
}
} // editGrName
main :
readAtNo( maxAtNo, aa );
if ( aa != 0 )
editGrName( bInOut, aa );
GrElmn_setGrName() :
void GrElmn_setGrName( GrElmn& a, string newGrName )
{
strncpy( a.geGrName, newGrName.c_str(), GrElmn::grNameSz-1 );
a.geGrName[GrElmn::grNameSz-1] = '\0';
} // GrElmn_setGrName
writeRandom() readRandom() :
, a.
:
void writeRandom( const GrElmn& a, ostream& bout )
{
if ( bout.fail() )
throw ApplicXptn( "writeRandom",
ApplicXptn::streamNotOpen );
bout.seekp( (a.geANumber-1)*GrElmn::saveSize );
GrElmn_save( a, bout );
} // writeRandom
:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

struct ApplicXptn
{
enum { cannotOpen, streamNotOpen, rangeErr, cannotClose,
cannotWrite, cannotRead };
char funcName[100];
int errCode;
char errStrVal[100];
int errIntVal;
- II 471

ApplicXptn( const char* fn, int ec, const char* sv="" )


{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
ApplicXptn( const char* fn, int ec, int iv )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errIntVal = iv; }
}; // ApplicXptn

struct GrElmn
{
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
}; // GrElmn

void GrElmn_save( const GrElmn& a, ostream& bout );


void GrElmn_load( GrElmn& a, istream& bin );
void GrElmn_display( const GrElmn& a, ostream& tout );
void GrElmn_setGrName( GrElmn& a, string newGrName );

void openFile( string& flNm, fstream& bInOut );


void countRecords( fstream& bInOut, unsigned int& noOfRecords );
void readAtNo( int maxAtNo, int& aa );
void readRandom( GrElmn& a, istream& bin, int atNo );
void writeRandom( const GrElmn& a, ostream& bout );
void editGrName( fstream& bInOut, int atNo );

int main()
{
fstream bInOut;
string flNm( "elementsGr.dta" );

try
{
openFile( flNm, bInOut );
// .. ( )
unsigned int maxAtNo;
countRecords( bInOut, maxAtNo );
int aa;
do {
// ..
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
editGrName( bInOut, aa );
}
} while ( aa != 0 );
bInOut.close();
if ( bInOut.fail() )
throw ApplicXptn( "GrElmn_load", ApplicXptn::cannotClose,
flNm.c_str() );
}
catch( ApplicXptn& x )
{
switch ( x.errCode )
{
case ApplicXptn::cannotOpen:
cout << "cannot open file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case ApplicXptn::streamNotOpen:
472 15

cout << "cannot open file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case ApplicXptn::rangeErr:
cout << "no element with such atomic number ("
<< x.errIntVal << ") in " << x.funcName << endl;
break;
case ApplicXptn::cannotClose:
cout << "cannot close file " << x.errIntVal
<< " in " << x.funcName << endl;
break;
case ApplicXptn::cannotWrite:
cout << "cannot write to file " << x.errStrVal
<< " in " << x.funcName << endl;
break;
case ApplicXptn::cannotRead:
cout << "cannot read from file " << x.errStrVal
<< " in " << x.funcName << endl;
break;
default:
cout << "unexpected ApplicXptn from "
<< x.funcName << endl;
} // switch
} // catch( ApplicXptn
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main
:
Atomic Number (1..103, 0 to exit): 22
atomic number: 22
atomic weight: 47.9
symbol: Ti
name: Titanium
greek name:
new greek name:
Atomic Number (1..103, 0 to exit): 55
atomic number: 55
atomic weight: 132.906
symbol: Cs
name: Cesium
greek name:
new greek name:
Atomic Number (1..103, 0 to exit): 35
atomic number: 35
atomic weight: 79.904
symbol: Br
name: Bromine
greek name:
new greek name:
Atomic Number (1..103, 0 to exit): 0


. .

15.14.3
1 (Hydrogen) H 1.0008
:
2 (Helium) He 4.0026
( ),
3 (Lithium) Li 6.941
.
4 (Beryllium) Be 9.01218
:
. . .

. . 15-1 -
( )
.
- II 473

.
. ,
. 15-1.
void GrElmn_writeToTable( const GrElmn& a, ostream& tout )
{
tout << a.geANumber << '\t' << a.geGrName
<< " (" << a.geName << ")\t" << a.geSymbol << '\t'
<< a.geAWeight << endl;
} // GrElmn_writeToTable
:
ofstream tout( "elementsTbl.txt" );
GrElmn a;
bInOut.seekg( 0 );
GrElmn_load( a, bInOut );
while ( !bInOut.eof() )
{
GrElmn_writeToTable( a, tout );
GrElmn_load( a, bInOut );
} // while
tout.close();
elementsTbl.txt :13
1\t (Hydrogen)\tH\t1.008
2\t (Helium)\tHe\t4.0026
3\t (Lithium)\tLi\t6.941
4\t (Beryllium)\tBe\t9.01218
. . .
, GrElmn_.
:
( ) GrElmn. -
(methods) .
. :
.
.
: (..)
,
.. 6. , .. 1 112 ( 113
114). , :
.. k (k-1)- .

. -
carbon .. 6.
; (index) . 15-2 .
, .


, , -
(Data Base Management Sys-
tems, DBMS) . ,
-
. .

13 , (tabs) . MS
Excel MS Word .
474 15

:
..
- Actinium 89
Aluminum 13
: Americium 95
( ). Antimony 51
. Argon 18
Arsenic 33
Astatine 85
15.15 Barium 56
- ... ...
- . 15-2
,
. ( ) -
. .
(text) -

. : , :
.
seekp() ( ofstream, fstream)
. ,
seekg() ( ifstream, fstream).
-
. .
projects.
, . (-
) .
.


15-1 (binary) dates.dta
:
struct Date
{
unsigned int year;
unsigned char month;
unsigned char day;
}; // Date

void Date_save( const Date& a, ostream& bout )
{
if ( bout.fail() )
throw _Xptn( "Date_save", _Xptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&a.year),
sizeof(a.year) );
bout.write( reinterpret_cast<const char*>(&a.month),
sizeof(a.month) );
bout.write( reinterpret_cast<const char*>(&a.day),
sizeof(a.day) );
- II 475

if ( bout.fail() )
throw _Xptn( "Date_save", _Xptn::cannotWrite );
}; // Date_save
_Xptn .

limDate (text)
:
, odates.txt, limDate
, ndates.txt,
limDate.
:
,

.


15-2 0 () (sparse).
, , -
, . -
double nR nC .

nR * nC * sizeof(double)
. nNZ

struct ArrElmn
{
unsigned int row;
unsigned int col;
double value;
}; // ArrElmn

nNZ * sizeof(ArrElmn) < nR * nC * sizeof(double)
sprs017.dta -
:
unsigned int (nR)
.
unsigned int (nC)
.
nR*nC double :
0, 1 ...
, ,
sprs017cn.dta, :
unsigned int, (nR) .
unsigned int, (nC)
.
ArrElmn,
.
476 15
project

1

:
Prj01.1 ............................................................................................................................................. 477
Prj01.2 .................................................................................................................................. 478
Prj01.3 openWrNoReplace() .......................................................................................................... 478
Prj01.4 openFiles() ......................................................................................................................... 479
Prj01.5 copyTitle() .......................................................................................................................... 481
Prj01.6 closeFiles() ......................................................................................................................... 481
Prj01.7 ApplicXptn () ............................................................................................................................ 482
Prj01.8 main ................................................................................................................................................ 482
Prj01.9 openFiles() ................................................................................................................................ 483

Prj01.1
13.11
. :
. , text
autoflow.txt -
/min . ,
.

:
:\t<>\t<>
:\t<->\t<>\t<>
:\tdd.mm.yyyy\thh:mm
, .
.

. :
:
: 48
: 15.06.2009 05:00
26
30
8
28
. . .
17

477
478 Project 01

19
4
12 /
28
17
. . .
17
31 / &
23
24
. . .
:
1. h
min.
2.
.
3. , -
/min.
,
report.txt.
autoflow.txt.

.
min.

Prj01.2

bool& ok. . :
struct ApplicXptn
{
enum { . . . };
char funcName[100];
int errCode;
// . . .
ApplicXptn( const char* fn, int ec, . . . )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
// . . .
}
}; // ApplicXptn
15.10.
() -
.
ok.

Prj01.3 openWrNoReplace()
openWrNoReplace(). :
void openWrNoReplace( ofstream& newStream, string flNm )
{
ifstream test( flNm.c_str() ); //
if ( !test.fail() ) // ,
{
test.close(); //
throw ApplicXptn( "openWrNoReplace", ApplicXptn::fileExists,
479

flNm.c_str() );
}
newStream.open( flNm.c_str() ); //
if ( newStream.fail() )
throw ApplicXptn( "openWrNoReplace", ApplicXptn::cannotCreate,
flNm.c_str() );
} // openWrNoReplace
. -
. ;
throw newStream.open(
flNm.c_str() ) !

:
enum { fileExists, cannotCreate, . . . };
(-
C):
ApplicXptn( const char* fn, int ec, const char* sv="" )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
errStrVal :
char errStrVal[100];

Prj01.4 openFiles()
openWrNoReplace() openFiles() ok.
13.11.1 .
(autoflow, differences, report)
. , :
autoflow.open( autoFlNm.c_str() );
if ( autoflow.fail() )
throw ApplicXptn( "openFiles",
ApplicXptn::cannotOpen, autoFlNm.c_str() );
// . . .
: autoflow
.
(differences) openWrNoReplace(). ,
differences .
:
try
{
openWrNoReplace( differences, difFlNm );
}
catch( ApplicXptn& x )
{
autoflow.close();
throw;
} // catch
; autoflow
.
report:
try
{
openWrNoReplace( report, reprtFlNm );
}
480 Project 01

catch( ApplicXptn& x )
{
autoflow.close();
differences.close();
throw;
} // catch
differences.
-
(x.errStrVal), :
void openFiles( ifstream& autoflow, string autoFlNm,
ofstream& differences, string difFlNm,
ofstream& report, string reprtFlNm )
{
autoflow.open( autoFlNm.c_str() );
if ( autoflow.fail() )
throw ApplicXptn( "openFiles",
ApplicXptn::cannotOpen, autoFlNm.c_str() );
// autoflow
try
{
openWrNoReplace( differences, difFlNm );
openWrNoReplace( report, reprtFlNm );
}
catch( ApplicXptn& x )
{
autoflow.close();
if ( x.errStrVal == reprtFlNm ) // report
differences.close();
throw;
} // catch
} // openFiles
openWrNoReplace() autoflow.
report.txt differences
.
,
:
try
{
autoflow.open( autoFlNm.c_str() );
if ( autoflow.fail() )
throw ApplicXptn( "openFiles",
ApplicXptn::cannotOpen,
autoFlNm.c_str() );
// autoflow
openWrNoReplace( differences, difFlNm );
openWrNoReplace( report, reprtFlNm );
}
catch( ApplicXptn& x )
{ . . . }
, . : autoflow
catch :
catch( ApplicXptn& x )
{
if ( x.errStrVal == difFlNm ) // differences
autoflow.close();
else if ( x.errStrVal == reprtFlNm ) // report
{
autoflow.close();
differences.close();
}
throw;
} // catch
481

...
openFiles()
:
enum { fileExists, cannotCreate, cannotOpen };

Prj01.5 copyTitle()
copyTitle() ok throw :
void copyTitle( ifstream& autoflow, ofstream& report )
{
int lineCount( 0 ); //
while ( !autoflow.eof() && lineCount < 3 )
{
string aLine;
getline( autoflow, aLine, '\n' );
report << aLine << endl;
++lineCount;
} // while (... lineCount < 3)
if ( lineCount != 3 )
throw ApplicXptn( "copyTitle", ApplicXptn::incomplete, lineCount );
} // copyTitle
, (incomplete)
int:
ApplicXptn( const char* fn, int ec, int iv )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errIntVal = iv; }
errIntVal ApplicXptn:
int errIntVal;
, :
enum { fileExists, cannotCreate, cannotOpen, incomplete };

Prj01.6 closeFiles()
ok closeFiles(). :
void closeFiles( ifstream& autoflow, ofstream& differences, ofstream& report )
{
autoflow.close();

differences.close();
if ( differences.fail() )
throw ApplicXptn( "closeFiles", ApplicXptn::cannotClose, "" );
report.close();
if ( report.fail() )
throw ApplicXptn( "closeFiles", ApplicXptn::cannotClose, "" );
} // closeFiles
. dif-
ferences report. -
. -
; , .
.

.
482 Project 01

Prj01.7 ApplicXptn ()
:
struct ApplicXptn
{
enum { fileExists, cannotCreate, cannotOpen, incomplete, cannotClose };
char funcName[100];
int errCode;
char errStrVal[100];
int errIntVal;

ApplicXptn( const char* fn, int ec, const char* sv="" )


{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
ApplicXptn( const char* fn, int ec, int iv )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errIntVal = iv; }
}; // ApplicXptn

Prj01.8 main
, main :
int main()
{
ifstream autoflow; // autoflow.dta
ofstream differences; // differences.txt
ofstream report; // report.txt
string autoFlNm( "autoflow.txt" ),
difFlNm( "differences.txt" ),
reprtFlNm( "report.txt" );
try
{
openFiles( autoflow, autoFlNm, differences, difFlNm,
report, reprtFlNm );
process( autoflow, differences, report );
closeFiles( autoflow, differences, report );
cout << " , ..." << endl;
}
catch( ApplicXptn& x )
{
switch ( x.errCode )
{
case ApplicXptn::fileExists:
cout << " " << x.funcName << ": "
<< x.errStrVal << " " << endl;
break;
case ApplicXptn::cannotCreate:
cout << " " << x.funcName
<< ": " << x.errStrVal << endl;
break;
case ApplicXptn::cannotOpen:
cout << " " << x.funcName
<< ": " << x.errStrVal << endl;
break;
case ApplicXptn::incomplete:
cout << " " << x.funcName
<< ": . "
<< x.errIntVal << " " << endl;
break;
case ApplicXptn::cannotClose:
cout << " " << x.funcName
<< ": " << x.errStrVal << endl;
break;
483

default:
cout << "unexpected ApplicXptn from " << x.funcName << endl;
} // switch
} // catch( ApplicXptn
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main
main :
openFiles( autoflow, autoFlNm, differences, difFlNm,
report, reprtFlNm );
process( autoflow, differences, report );
closeFiles( autoflow, differences, report );
cout << " , ..." << endl;
: if (ok)
catch!

Prj01.9 openFiles()
14.9 : main; . -
,
. main , -
, .
-
main. ,
. ()-
ok :
void openFiles( ifstream& autoflow, string autoFlNm,
ofstream& differences, string difFlNm,
ofstream& report, string reprtFlNm,
bool& ok )
{
ok = false;
try
{
autoflow.open( autoFlNm.c_str() );
if ( autoflow.fail() )
throw ApplicXptn( "openFiles", ApplicXptn::cannotOpen,
autoFlNm.c_str() );
// autoflow
openWrNoReplace( differences, difFlNm );
openWrNoReplace( report, reprtFlNm );
ok = true;
}
catch( ApplicXptn& x )
{
switch ( x.errCode )
{
case ApplicXptn::fileExists:
case ApplicXptn::cannotCreate:
autoflow.close();
if ( x.errStrVal == reprtFlNm )// report
differences.close();
cout << " " << x.funcName;
if ( x.errCode == ApplicXptn::fileExists )
cout << ": " << x.errStrVal << " " << endl;
else // x.errCode == ApplicXptn::cannotCreate
cout << ": " << x.errStrVal
<< endl;
break;
484 Project 01

case ApplicXptn::cannotOpen:
cout << " " << x.funcName
<< ": " << x.errStrVal << endl;
break;
default:
throw;
} // switch
} // catch
} // openFiles
openFiles() :
ApplicXptn fileExists, cannotCreate cannotOpen
.
:
14.9 :
try; ! throw
try. :
openWrNoReplace() throw
.
false
ok. main . ,
:
do {
openFiles( autoflow, autoFlNm, differences, difFlNm,
report, reprtFlNm, ok );
if ( !ok )
getFileNames( autoFlNm, difFlNm, reprtFlNm, quit );
} while ( !ok && !quit );
if ( ok )
{
process( autoflow, differences, report );
closeFiles( autoflow, differences, report );
cout << " , ..." << endl;
}

void getFileNames( string& autoFlNm, string& difFlNm,


string& reprtFlNm, bool& quit )
( ) ()
. quit true.
closeFiles().
project

2
3
:
Prj02.1 ............................................................................................................................................. 485
Prj02.2 Vector3 ........................................................................................................ 486
Prj02.3 ............................................................................................................................. 487
Prj02.4 +, -, *, ^ ................................................................................................................ 488
Prj02.5 - ............................................................................................................................. 489
Prj02.6 ........................................................................................................................... 489
Prj02.7 << ....................................................................................................................................... 490
Prj02.8 ... ......................................................................................................................... 490
Prj02.9 ........................................................................................................................................... 490

Prj02.1
Project . -

.
() (vector)
(x, y, z).
Vector3
. -
(0, 0, 0)
.
A. v1 = (x1, y1, z1) v2 = (x2, y2, z2).
1. v1 v2 (
== !=). x1 = x2 y1 = y2 z1 = z2.
== != Vector3.
2.
v1 v2 (x1x2, y1y2, z1z2).
+ - Vector3.
+= -= Vector3.
3. v1 (v1 v1)
(x1, y1, z1).
* Vector3.
*= Vector3.
4. : (1)v1 v1.
- Vector3.

485
486 Project 02

5. v1 v2
: v1 v2 = x1x2 + y1y2 +z1z2 (inner dot
product).
( ) * Vector3.
6. (outer cross product)
v1 v2 : v1 v2 = (y1z2-z1y2, x2z1-z2x1, y2x1-x2y1).
^ Vector3
.
7. text
<<.
<< Vector3.
x2 y 2 z2
8. , : |v| = (=
v v ) .
Vector3_abs
Vector3.
B. ,
Laplace FL = q(v B) q = 1 Cb
v = (108, 0, 0) B = (0, 0, 10).
v B (: FL v = 0 FL B = 0).

a b S = a b.
-
B S.

a = (0.1, 0.2, 0.3) b = (0.2, 0.3, 0.4)
.
a b : |a|2|b|2 = (ab)2 + |ab|2.

Prj02.2 Vector3
complex :
struct Vector3
{
double x;
double y;
double z;
}; // Vector3
complex:
Vector3( double ax=0, double ay=0, double az=0 )
{ x = ax; y = ay; z = az; }
:
Vector3 v0; // (0, 0, 0)
Vector3 v1( 1 ); // (1, 0, 0)
Vector3 v2( sqrt(2), 3 ); // (1.41421, 3, 0)
Vector3 v3( sqrt(3), sqrt(5), 2*sqrt(2) ); // (1.73205, 2.23607, 2.82843)
:
struct Vector3
{
double x;
double y;
double z;
Vector3( double ax=0, double ay=0, double az=0 )
3 487

{ x = ax; y = ay; z = az; }


}; // Vector3

Prj02.3
14.6.4, (@)
:
Trv operator@( Tl lhs, Tr rhs )
, ==, Trv bool.
Tl Tr , , Vector3. :
bool operator==( Vector3 lhs, Vector3 rhs )
{
return (lhs.x == rhs.x) &&
(lhs.y == rhs.y) && (lhs.z == rhs.z);
} // operator==( Vector3
, , , ,
:
bool operator==( const Vector3& lhs, const Vector3& rhs )
{
return (lhs.x == rhs.x) &&
(lhs.y == rhs.y) && (lhs.z == rhs.z);
} // operator==( Vector3
; -
, , Vector3.
() 8:48 ! ,
48 . -
, , -
string 1000 . -
const.

(!)
!= ; ==
!(a == b) a != b. ,
:1
@
@.
:
bool operator!=( const Vector3& lhs, const Vector3& rhs )
{
return !(lhs == rhs);
} // operator!=( Vector3
, ().
:
bool operator!=( const Vector3& lhs, const Vector3& rhs )
{
return (lhs.x != rhs.x) ||
(lhs.y != rhs.y) || (lhs.z != rhs.z);
} // operator!=( Vector3
-
.

1 36 (ELLEMTEL 1998) : When two operators are opposite (such as == and !=), it is
appropriate to define both.
488 Project 02

Prj02.4 +, -, *, ^
() ^ ( )
:
Trv operator@( Tl lhs, Tr rhs )
:
+: Vector3 Vector3 y Vector3
-: Vector3 Vector3 y Vector3
^: Vector3 Vector3 y Vector3
.
, ,
.
Trv, Tl Tr Vector3.
, Tl Tr const Vector3&:
Vector3 operator+( const Vector3& lhs, const Vector3& rhs )
{
Vector3 fv;
fv.x = lhs.x + rhs.x;
fv.y = lhs.y + rhs.y;
fv.z = lhs.z + rhs.z;
return fv;
} // operator+( const Vector3&

Vector3 operator-( const Vector3& lhs, const Vector3& rhs )


{
Vector3 fv;
fv.x = lhs.x - rhs.x;
fv.y = lhs.y - rhs.y;
fv.z = lhs.z - rhs.z;
return fv;
} // operator-( const Vector3&

Vector3 operator^( const Vector3& lhs, const Vector3& rhs )


{
Vector3 fv;
fv.x = lhs.y*rhs.z - lhs.z*rhs.y;
fv.y = rhs.x*lhs.z - rhs.z*lhs.x;
fv.z = rhs.y*lhs.x - rhs.x*lhs.y;
return fv;
} // operator^( const Vector3
:
^ C++; , . 14.6
.
; ,
.
* . :
Vector3 v1, v2;
double a;
:
v2 = a*v1;
:
v2 = v1*a;
:
*: double Vector3 y Vector3
*: Vector3 double y Vector3
*:
3 489

Vector3 operator*( double lhs, const Vector3& rhs )


{
Vector3 fv;
fv.x = lhs * rhs.x;
fv.y = lhs * rhs.y;
fv.z = lhs * rhs.z;
return fv;
} // operator*

Vector3 operator*( const Vector3& lhs, double rhs )


{
Vector3 fv;
fv.x = rhs * lhs.x;
fv.y = rhs * lhs.y;
fv.z = rhs * lhs.z;
return fv;
} // operator*
* :
*: Vector3 Vector3 y double

double operator*( const Vector3& lhs, const Vector3& rhs )
{
return lhs.x*rhs.x + lhs.y*rhs.y + lhs.z*rhs.z;
} // operator*( const Vector3&

Prj02.5 -
:
Vector3 v1, v2;
:
v2 = -v1;
v2 v1, : v1 + v2 = 0.
- :
-: Vector3 Vector3
14.6.4 @

Trv operator@( T rhs )


- complex (15.5). , Trv
T Vector3:
Vector3 operator-( const Vector3& rhs )
{
return Vector3( -rhs.x, -rhs.y, -rhs.z );
} // operator-( const Vector3&

Prj02.6 2
+=, -=, *=
14.6.3. += T :
T& operator+=( T& lhs, const T& rhs )
const.
T Vector3 :
Vector3& operator+=( Vector3& lhs, const Vector3& rhs )
{

2 .
490 Project 02

lhs.x += rhs.x;
lhs.y += rhs.y;
lhs.z += rhs.z;
return lhs;
} // operator+=( Vector3&
:
Vector3& operator-=( Vector3& lhs, const Vector3& rhs )
{
lhs.x -= rhs.x;
lhs.y -= rhs.y;
lhs.z -= rhs.z;
return lhs;
} // operator-=( const Vector3&

Vector3& operator*=( Vector3& lhs, double rhs )


{
lhs.x *= rhs;
lhs.y *= rhs;
lhs.z *= rhs;
return lhs;
} // operator*=( const Vector3&

Prj02.7 <<
<< .
complex (15.5) :
ostream& operator<<( ostream& tout, const Vector3& rhs )
{
return tout << "(" << rhs.x << ", " << rhs.y << ", "
<< rhs.z << ")";
} // operator<<

Prj02.8 ...
( ) . -
:
double Vector3_abs( const Vector3& lhs )
{
return sqrt( lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z );
} // double Vector3_abs

Prj02.9
. -
( )
:
double Vector3_abs2( const Vector3& lhs )
{
return ( lhs.x*lhs.x + lhs.y*lhs.y + lhs.z*lhs.z );
} // double Vector3_abs2
a |a|2.
:
Vector3_abs2(a)*Vector3_abs2(b) - ((a*b)*(a*b)+Vector3_abs2(a^b))
:
#include <iostream>
#include <cmath>
3 491

using namespace std;

struct Vector3
{
double x;
double y;
double z;
Vector3( double ax=0, double ay=0, double az=0 )
{ x = ax; y = ay; z = az; }
Vector3( const Vector3& rhs )
{ x = rhs.x; y = rhs.y; z = rhs.z; }
}; // Vector3

bool operator==( const Vector3& lhs, const Vector3& rhs );


bool operator!=( const Vector3& lhs, const Vector3& rhs );
Vector3 operator-( const Vector3& rhs );
Vector3 operator+( const Vector3& lhs, const Vector3& rhs );
Vector3& operator+=( Vector3& lhs, const Vector3& rhs );
Vector3 operator-( const Vector3& lhs, const Vector3& rhs );
Vector3& operator-=( Vector3& lhs, const Vector3& rhs );
Vector3 operator*( double lhs, const Vector3& rhs );
Vector3 operator*( const Vector3& lhs, double rhs );
Vector3& operator*=( Vector3& lhs, double rhs );
double operator*( const Vector3& lhs, const Vector3& rhs );
Vector3 operator^( const Vector3& lhs, const Vector3& rhs );
ostream& operator<<( ostream& tout, const Vector3& rhs );
double Vector3_abs( const Vector3& lhs );
double Vector3_abs2( const Vector3& lhs );

int main()
{
double q( 1e-6 ); // Cb
Vector3 v( 1e8, 0, 0 );
Vector3 B( 0, 0, 10 );
Vector3 FL;

FL = q*( v ^ B );
cout << FL << endl;
cout << FL*v << " " << FL*B << endl;

Vector3 a( 0.1, 0.2, 0.3 ), b( 0.2, 0.3, 0.4 );

cout << a << " " << b << endl;


cout << B*( a ^ b) << endl;

cout << Vector3_abs2(a)*Vector3_abs2(b) -


((a*b)*(a*b)+Vector3_abs2(a^b)) << endl;
cout << Vector3_abs2(a)*Vector3_abs2(b) << endl;
} // main
:
(0, -1000, 0)
0 0
(0.1, 0.2, 0.3) (0.2, 0.3, 0.4)
-0.1
-3.27294e-018
0.0406
.
-3.31018. |a|2|b|2 0.0406 4102. ,
, 1016 . -
(0).
492 Project 02

16

:
C++.

.
.
:

. ( -
).
:
new, new[]
delete, delete[]


- (pointer)
RAII
:
16.1 new delete ......................................................................................................... 494
16.2 B .............................................................................................................. 496
16.3 T .............................................................................................. 498
16.4 ..................................................................................................................................... 500
16.5 * new..................................................................................................................... 504
16.6 bad_alloc ............................................................................................................................... 504
16.6.1 .................................................................................................................505
16.7 ................................................................................................. 505
16.7.1 RAII: ..................................................................................................................................509
16.8 ..................................................................................................................... 511
16.9 ............................................................................................................. 511
16.10 * : void* ...................................................................................................................... 515
16.11 * C: malloc(), free(), realloc() .................................................................................. 517
16.12 realloc() ............................................................................................................ 519
16.13 ............................................................................................................................................ 520
16.13.1 linSearch() ................................................................................................................................532
16.13.2 linSearch() ...........................................................................................................................................533
16.13.3 reserved + incr 2*reserved ....................................................................................................................535
16.14 ........................................................................................................................... 535
16.15 ........................................................................................................................................ 537
................................................................................................................................................................... 538

493
494 16

.............................................................................................................................................................................538

:
11.1 :
, (
),
(automatic) (stack),

(dynamic) .

, -
.


.
, , f() g() main
:
f( . . . );
. . .
g( . . . );
main
f() g(). main f()
g(), main f()
g() .
f() n -
main n+1 f().
C++, ,

. (dynamic
memory allocation).
C++ :

(heap memory) C (malloc,


calloc, realloc, free)
free store new delete C++.
, 14.8, ,
.
, :
new delete malloc, calloc,
realloc free.
C++ -
C, Java C#: C++
- (pointers) () C.

16.1 new delete


new delete
:
- (pointer variables)
495
double* a1( new double );
(dynamic) . double* a2; int* i; int* k;
-
a1 a2 i k
. 2 (2.8.3) : -
??? ??? ???
&number

???

. *a1
(double)
&number -
(referencing) a2 = new double;
- (pointer) a1 a2 i k
. - ??? ???
: -
p, ??? ???
*a1 *a2
p; , , (double) (double)
&; C++ i = new int( 375 ); k = new int;
*: -
a1 a2 i k
p -
*p. [...] *(&number)
number.
??? ??? 375 ???
* - (dereferences)
*a1 *a2 *i *k
- . (double) (double) (int) (int)
. 12 C++,
( cin >> *a1; *a2 = 4.56;

) - a1 a2 i k
. (
)
-. 1.23 4.56 375 ???
, *a1 *a2 *i *k
- - (double) (double) (int) (int)
( ) . . 16-1
. . -
: -
T* q; (T *q;) .
q -,
T,
q = new T;
:
T.

*q.
*q q.
, , , -

delete q;
-
,
.
496 16

16.1
new
:
* pv;
1) pv = new T;

() T.
*pv
T.
pv.
2) pv = new T[N];
N -
T, N T.
:
pv[0], pv[1], pv[N-1]
:
pv[N];

16.2 B
T :
T* q;
, , :
typedef T* PT;
:
PT q;
, q -. T* PT
(target domain base type) T.
q
, . ,
q, T.
,
typedef int* PInt;
// . . .
double *a1, *a2;
PInt i, j, k;
a1, a2, i, j, k - char,
int.
:
: PInt int*, ,
i, j, k int*. , double* a1, a2
a1 double* a2 double.
() -
.
.
new (. 16.1). :
"new", [ "(", , ")" ];
497

a1 a2 i k
.

1.23 4.56 1250 1143
. *a1 *a2 *i *k
(double) (double) (int) (int)
..: delete a1; delete a2;
k = new int;
a1 a2 i k
- k ??? ???
-
int 1250 1143
. ; *k!
*i *k
k (int) (int)
*k .
. 16-2 delete

i = new int( 375 );
.
, - i -
(*i) int *i
375.
new :
double *a1( new double );
a1 . ,
(*a1) a1 new double(1.23).
. 16-1. , k,
, *k . -

( ) .
new.
, Date, :
Date* pd( new Date(Date(2008, 7, 9)) );
: Date (
pd) Date -
2008, 7, 9.
:
Date* pd( new Date(2008, 7, 9) );
:
.
, ,

*i = (*i)*2 + 500;
:
cin >> *k;
-
. -
new delete (. 16.2).
. 16-1

delete a1; delete a2;
498 16

16.2
delete
:
* pv;

pv = new T;


delete pv;
) *pv )
pv .
:
pv = new T[];

delete[] pv;

)
pv ) pv .
. 16-2 .
a1 a2 . delete a1 (-
) *a1 delete a2 *a2. T ; *a1 *a2
.
new .
:
delete q *q -
.
, C++
.

16.3 T
, C++
. . 16-1
???:
#include <iostream>
using namespace std;
int main()
{
double* a1( new double );
double* a2; int* i; int* k;
cout << a1 << " " << a2 << " " << i << " " << k << endl;
;
0x3e2478 0x34 0x22ffa8 0x7c800000
, :
cout << *a1 << " " << *a2 << " " << *i << " " << *k << endl;
.
-
-:
a2 = new double;
i = new int( 375 ); k = new int;
499

cout << a1 << " " << a2 << " " << i << " " << k << endl;
cout << *a1 << " " << *a2 << " " << *i << " " << *k << endl;

0x3e2478 0x3e24e0 0x3e24f0 0x3e2500
0 1.66976e-307 375 4064328
:
new
,
.
, ,
*i (375).
, a1
. - ;
. ,

.
:
(address space)
. , -
(virtual)
1.
-
() a1 .
, . -
( ).
, ,

(memory swapping) .
: :
cin >> *a1; *a2 = 4.56; cin >> *k;
cout << a1 << " " << a2 << " " << i << " " << k << endl;
cout << *a1 << " " << *a2 << " " << *i << " " << *k << endl;
:
0x3e2478 0x3e24e0 0x3e24f0 0x3e2500
1.23 4.56 375 1143
:
delete a1; delete a2;
cout << a1 << " " << a2 << " " << i << " " << k << endl;
cout << *a1 << " " << *a2 << " " << *i << " " << *k << endl;
:
0x3e2478 0x3e24e0 0x3e24f0 0x3e2500
1.23 4.56 375 1143
delete a1 a2
! ... :
a1 = new double;
cout << a1 << " " << *a1 << endl;
*a1 = 7.13;
cout << *a2 << endl;
:
0x3e24e0 4.56

1 , virtual address space


500 16

7.13
a1 = new double *a1 *a2 (
). *a1 (
) *a2.

.

-. , -
()
! -
;
- .
0 (NULL). ( 12.3.2
new
. 0.)
-
p , ,
if( p != 0 )
delete p, p,
p = 0 (
). delete p
p,
*p
.2

16.4

int
1. (, )
2. .

new delete. :
double* p( 0 );
:
p = new double[100];
100 double -
:
double p[100];
: 100, new
.
,
.

2 delete, ,
.
501

:
! ; C++
C.
.
. -
p p[0], p[1], , p[99] -
double.
, :
delete[] p;
: -
new delete.
p = new T delete p
p = new T[...] delete[]
p.
, p
delete p.
double q( new double );
*q delete[] q.
.
. .

alturing.txt,
. 1 8.10,
(15.12.1),
.

void loadText( string flNm, char*& toText, size_t& tLength )
(flNm),
( char)
(toText) (tLength). -

.
void loadText( string flNm, char*& toText, size_t& tLength )
{
ifstream tin( flNm.c_str(), ios_base::binary|ios_base::ate );
if ( tin.fail() )
throw ApplicXptn( "loadText", ApplicXptn::cannotOpen,
flNm.c_str() );
tLength = tin.tellg();
try { toText = new char[tLength+1]; }
catch( bad_alloc& )
{ throw ApplicXptn( "loadText", ApplicXptn::allocFailed ); }
tin.seekg( 0 );
tin.read( toText, tLength );
if ( tin.fail() )
throw ApplicXptn( "loadText", ApplicXptn::cannotRead,
flNm.c_str() );
tin.close();
toText[tLength] = '\0';
} // loadText
15.12.1 :
try { toText = new char[tLength+1]; }
catch( bad_alloc& )
502 16

{ throw ApplicXptn( "loadText", ApplicXptn::allocFailed ); }


tLength+1; ('\0') -
() .
():
void countText( const char* toText, int tLength,
int& nRows, int& nUpCase, int& nDigits )
{
int pos( 0 );
char ch; //
//
nRows = 0; nUpCase = 0; nDigits = 0;
//
ch = toText[pos];
while ( pos < tLength )
{
while ( pos < tLength && ch != '\n' )
{
if ( isupper(ch) ) ++nUpCase;
else if ( isdigit(ch) ) ++nDigits;
++pos; ch = toText[pos];
}
++nRows;
if ( pos < tLength ) { ++pos; ch = toText[pos]; }
} // while
} // countText
:
pos ch (toText[pos] == ch)
t.get(ch) : pos = 0; ch = toText[pos]; -
: ++pos; ch = toText[pos].
!t.eof() pos < tLength. ch != '\0'; ,

'\0' . , ,
text.
: ch != '\n'.
text
'\n'.
;
toText == 0 tLength < 0
.
:
char* toText( 0 ); //
size_t tLength; //
int nRows; //
int nUpCase; //
int nDigits; //
:
loadText( "alturing.txt", toText, tLength );
countText( toText, tLength, nRows, nUpCase, nDigits );
:
#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <new>

using namespace std;


503

struct ApplicXptn
{
enum { cannotOpen, cannotRead, allocFailed };
char funcName[100];
int errCode;
char errStrVal[100];

ApplicXptn( const char* fn, int ec, const char* sv="" )


{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // ApplicXptn

void loadText( string flNm, char*& toText, size_t& tLength );


void countText( const char* toText, int tLength,
int& nRows, int& nUpCase, int& nDigits );

int main()
{
char* toText( 0 ); //
size_t tLength; //
int nRows; //
int nUpCase; //
int nDigits; //

try
{
loadText( "alturing.txt", toText, tLength );
countText( toText, tLength, nRows, nUpCase, nDigits );
delete[] toText; toText = 0;
//
cout << " " << nRows << " " << endl;
cout << " " << nUpCase << " "
<< nDigits << " " << endl;
}
catch( ApplicXptn& x )
{
switch ( x.errCode )
{
case ApplicXptn::cannotOpen:
cout << "cannot open file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case ApplicXptn::cannotRead:
cout << "cannot read from file " << x.errStrVal
<< " in " << x.funcName << endl;
break;
case ApplicXptn::allocFailed:
cout << "cannot get enough memory " << " in "
<< x.funcName << endl;
break;
default:
cout << "unexpected ApplicXptn from "
<< x.funcName << endl;
} // switch
} // catch( ApplicXptn
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main

504 16

16.5 * new
new
. :
int buf[100];
double* d( new (buf) double );
cout << &buf[0] << endl;
cout << d << endl;
:
0x22fde0
0x22fde0
: *d buf.
, new
-

delete. new (placement new).
:
char* buf( new char[100] );
double* d( new (buf) double );
// . . .
delete[] buf;
delete; buf new
(new char[100]). , *d,
buf.

new
.
Linux Windows Unix
.
.

16.6 bad_alloc
(
). -
. ,
new,
. bad_alloc.
new try
catch(bad_alloc&).
bad_alloc :
#include <new>
:
// . . .
#include <new>
// . . .
try
{
double dr( new double[1000] );
// . . .
}
// . . .
catch( bad_alloc& )
{
505

//
}
// . . .
:
bad_alloc ,
// . . .
double dr( 0 );
try { dr = new double[1000]; }
catch( bad_alloc& )
{ throw MyProgXptn( "thisFunc", MyProgXptn::allocFailed ); }
// . . .
;
( ) (-) .

16.6.1

.

char funcName[100];
:
string funcName;
; -
(allocFailed). string -
. -


. char
.

16.7


.

12.3.2:
:
int* a( new int(10) );
int* b( new int(20) );
. 16-3(): a
*a, 10, b *b 20.
*a = *b. .
16-3 (). *a 20, .
, (), : a
= b. *a *b ,
a a b: *b (. 16-3 ()).
, , :
cout << *a << " " << *b << endl;
:
20 20
506 16

*a 10 *b 20 *a 20 *b 20 *a 10 *b 20

a b a b a b

() () ()
. 16-3 ( . 12-3) , -
( ) int* a(new int(10)); int* b(new int(20)); -
(). ()
: *a = *b. () , (),
a = b.


: , *a,
( ).
, (mem-
ory leakage). :
p
, p, .
p, ,
.
p .
.
:
void f( int ni, int nd, . . . )
{
int* pi( 0 );
double* pd( 0 );

try { pi = new int[ni]; }


catch( bad_alloc& )
{ throw MyProgXptn( "f", MyProgXptn::allocFailed ); }
try { pd = new double[nd]; }
catch( bad_alloc& )
{ throw MyProgXptn( "f", MyProgXptn::allocFailed ); }
// . . .
} // f

f,
pi = new int[ni] pi,
pd MyProgXptn
throw.
f pi pd (
).
, ni int
. ;
:
// . . .
try { pd = new double[nd]; }
catch( bad_alloc& )
{ delete[] pi; //
throw MyProgXptn( "f", MyProgXptn::allocFailed ); }
// . . .

:
507

void f( int ni, int nd, . . . )


{
int* pi( 0 );
double* pd( 0 );

try { pi = new int[ni]; }


catch( bad_alloc& )
{ throw MyProgXptn( "f", MyProgXptn::allocFailed ); }
try { pd = new double[nd]; }
catch( bad_alloc& )
{ delete[] pi; //
throw MyProgXptn( "f", MyProgXptn::allocFailed ); }
try
{
//
}
catch( ... )
{
delete[] pi;
delete[] pd;
throw;
}
} // f
catch:
,

!
, ,
(pending dangling pointer).
() . 16-3
delete b; b = 0;
, *b -
b. , *b *a a
.
.
:
void g( double* dAr, int n )
{
int nn;
// . . .
if ( n < nn )
{
double* dArL( new double[nn] );
// . . .
delete[] dAr; dAr = dArL;
n = nn;
} // if
// . . .
} // g
.
.
! - dAr .
const dAr
.
.
:
double* bd( 0 );
int bn( 0 );
// . . .
508 16

g( bd, bn );
dAr bd
. -
( dArL)
(delete[] dAr) , , .
bd, ,
.
dArL (
)
. .

:
void g( double*& dAr, int& n )
delete.
(16.4): delete

new .
o (heap).
.
:
new delete
. ...
, ,
, .
delete : , , -
(
) o . ,

delete p;
delete p;
:
if ( . . . )
{
// . . .
delete p;
// . . .
}
delete p;
:
while ( . . . )
{
// . . .
delete p;
// . . .
}
delete p;
:
f( ..., p, ... );
delete p;
f delete p.
delete
. :
delete p; p = 0;
509

delete p;
delete p delete 0
delete 0 . delete[] 0.
:
.
.
a int v int.
v a .
;

.
.
,
.


.
; :

.

.
.

.
, STL,
. :
(smart pointers)
vector (containers).

16.7.1 RAII:
, f -
try-catch!
, ,
C++ Resource Acquisition Is Initialization (RAII), : -
.

(15.3) (15.3.1).
, :
struct IntDArr
{
int* da;
IntDArr( int n )
{
try { da = new int[n]; }
catch( bad_alloc& )
{ throw MyProgXptn( "IntDArr", MyProgXptn::allocFailed ); }
}
~IntDArr() { delete[] da; }
}; // IntDArr
510 16

-
int. , int* pi(0) :
IntDArr pi( ni );

pi.da.
:
: ! !
( ) !
-
Date 37;
.
, , k
pi.da[k] pi[k].
pi
. , , -
.
, : -
int*& ipp
( -
). :
int* psv( pi.da );
pi.da = ipp;
ipp = psv;
: pi.da ipp ipp
, pi,
ipp ( 0).
double :
struct DoubleDArr
{
int* da;
DoubleDArr( int n )
{
try { da = new int[n]; }
catch( bad_alloc& )
{ throw MyProgXptn( "DoubleDArr", MyProgXptn::allocFailed ); }
}
~DoubleDArr() { delete[] da; }
}; // DoubleDArr
f:
void f( int ni, int nd, . . . )
{
IntDArr pi( ni );
DoubleDArr pd( nd );

// . . .
// pi[k] pi.da[k]
// pd[k] pd.da[k]
} // f
!
,

.
IntDArr DoubleDArr ( ) (wrapper
structures classes). .
511

16.8
.
Address:
struct AddressD
{
char* country;
char* city;
int areaCode;
char* street;
int number;
}; // AddressD

. !
: :
AddressD a1, a2;
a1.
a2 = a1 ; a1.country,
a1.city, a1.street a2
. , -
. a1 a2
a2 a1. .

. . 3 ,
, :
string.4

16.9
.
( egr63e2.txt)
, , () .

.
.
.
.
:
ifstream tin( "egr63e2.txt" );
int nR, nC;
tin >> nR >> nC;
nRnC.

nR nC
double.
double* nR double*:
(double*)* a;

3 = 14.6.3.
.
4 , save() load()! , ,
.
512 16

a a

a[0][0] a[0][nC-1]
a[0] a[0] ...
a[1] a[1] ...
a[2] a[2] ...
a[3] a[3] ...
. . . .
. . . .
. . . .
a[nR-2] a[nR-2] ...
a[nR-1] a[nR-1] ...

. 16-4 . 16-5
for ( int r(0); r < nR; ++r )
a = new double*[nR] a[r] = new double[nC];
:
double** a;
.
nR
:
a = new double*[nR];
. 16-4 a -
. () , a[r], r: 0..nR-1, -
, .
.
:
for ( int r(0); r < nR; ++r ) a[r] = new double[nC];
. 16-5. c
r (a[r])[c] a[r][c].
.
, -
:
for ( int r(0); r < nR; ++r )
{
for ( int c(0); c < nC; ++c ) tin >> a[r][c];
}
tin.close();
-
. (
.)
;
:
for ( int r(0); r < nR; ++r ) delete[] a[r];
:
delete[] a;
-
.
. :
struct MyTmpltLibXptn
{
enum { domainError, noArray, allocFailed };

char funcName[100];
513

int errCode;
int errVal1, errVal2;
MyTmpltLibXptn( const char* fn, int ec,
int erv1 = 0, int erv2 = 0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
errVal1 = erv1; errVal2 = erv2; }
}; // MyTmpltLibXptn
.
new2d
T** (T -):
0: template< typename T >
1: T** new2d( int nR, int nC )
2: {
3: if ( nR <= 0 || nC <= 0 )
4: throw MyTmpltLibXptn( "new2d",
5: MyTmpltLibXptn::domainError,
6: nR, nC );
7: T** fv;
8: try { fv = new T*[nR]; }
9: catch( bad_alloc& )
10: { throw MyTmpltLibXptn( "new2d",
11: MyTmpltLibXptn::allocFailed ); }
12: for ( int r(0); r < nR; ++r )
13: {
14: try { fv[r] = new T[nC]; }
15: catch( bad_alloc& )
16: {
17: for ( int k(0); k < r; ++k ) delete[] fv[k];
18: delete[] fv;
19: throw MyTmpltLibXptn( "new2d",
20: MyTmpltLibXptn::allocFailed );
21: } // catch
22: } // for ( int r
23: return fv;
24: } // new2d
. 8
. . 14,
for (. 12) r.
0
.. r-1. r
.
. 17 18.
delete2d() :
template< typename T >
void delete2d( T**& a, int nR )
{
if ( a == 0 && nR > 0 )
throw MyTmpltLibXptn( "delete2d", MyTmpltLibXptn::noArray );
for ( int r(0); r < nR; ++r ) delete[] a[r];
delete[] a; a = 0;
} // delete2d
: T**& ! -
: a
.
C++:
.
, :
tin >> nR >> nC;
a = new2d<double>( nR, nC );
514 16

for ( int r(0); r < nR; ++r )


{
for ( int c(0); c < nC; ++c ) tin >> a[r][c];
}
tin.close();
// . . .
delete2d( a, nR );
new2d()
. :
new2d<double>.

(!) -
4 12.4 ( ), . 6 13.9.3 (-
) 14.7.1,
.
:
const int l( 3 ), m( 5 ), n( 2 );

int** a( new2d<int>(l, m) );
int** b( new2d<int>(m, n) );
int** d( new2d<int>(l, n) );
/ :
void input2DAr( istream& tin, int** a, int nRow, int nCol )
{
for ( int r(0); r < nRow; ++r )
for ( int c(0); c < nCol; ++c )
tin >> a[r][c];
} // input2Dar

void output2DAr( ostream& tout, int** a, int nRow, int nCol )


{
for ( int r(0); r < nRow; ++r )
{
for ( int c(0); c < nCol; ++c )
{
tout.width(3); cout << a[r][c] << " ";
}
cout << endl;
}
} // output2DAr
: () , , -
. -
( ).
: :
input2DAr( atx, a, l, m );
input2DAr( atx, b, m, n );
:
cout << " a" << endl;
output2DAr( cout, a, l, m );
cout << " b" << endl;
output2DAr( cout, b, m, n );
cout << " d" << endl;
output2DAr( cout, d, l, n );
, :
delete2d( a, l );
delete2d( b, m );
delete2d( d, l );
515

: -
!


. :
char** monthName( 0 );
:
monthName = new char*[12];

monthName[0] = new char[strlen("January")+1];


strcpy( monthName[0], "January" );
monthName[1] = new char[strlen("February")+1];
strcpy( monthName[1], "February" );
// . . .
monthName[10] = new char[strlen("November")+1];
strcpy( monthName[10], "November" );
monthName[11] = new char[strlen("December")+1];
strcpy( monthName[11], "December" );
, ( +1
).
,
delete2d( monthName, 12 );
.

:
. .
string* sMonthName( new string[12] );
// . . .
delete[] sMonthName;
string ,
.

16.10 * : void*
C -
(
) :
void*.

. :
int iv;
void* pv1( &iv );
double dv;
pv1 = &dv;
Date dt;
pv1 = &dt;
, ..:
int* pInt( reinterpret_cast<int*>(pv1) );
void* -
(reinterpret_cast).

.
516 16

C
void* . -
#include <cstdlib> C
void qsort( void* base, size_t num, size_t size,
int (*compar)(const void*, const void*) );
Quicksort num -
base. size ( )
. ( ) .
qsort() :

.

.

.
: ()
. ,
, , . () : ,
, -
, qsort() -
. -
( ) compar().
:
int intArr[ 50 ];
double dblArr[ 100 ];
dblArr, ,
qsort(). :
qsort( dblArr, 100, sizeof(double), compareDblInc );
, dblArr, &dblArr[0]. -
base. compareDblInc(); :5
int compareDblInc( const void* a, const void* b )
{
return ( *reinterpret_cast<const double*>(a) -
*reinterpret_cast<const double*>(b) );
} // compareDblInc
7.1 11.7.
compareDblInc(&dblArr[35],&dblArr[71]), -
, -4 (== int(-4.6)). qsort() -
.
intArr[11] intArr[20] -
:
qsort( &intArr[11], 10, sizeof(int), compareIntDec );
:
int compareIntDec( const void* a, const void* b )
{
return ( *reinterpret_cast<const int*>(b) -
*reinterpret_cast<const int*>(a) );
} // compareIntDec
11 7.

5 C : return ( *(double*)a - *(double*)b );.


517

16.11 * C: malloc(), free(), realloc()


C++, C ,
malloc() (calloc()), free() realloc().
, .
cstdlib.
malloc() :
void* malloc( size_t size );
void* . -
. :
int* pInt;
:
pInt = reinterpret_cast<int*>( malloc(72*sizeof(int) );
72 int ( 72 int)
pInt .
0 ().
malloc() 0
:
0.

.
malloc() :
void* calloc( size_t nItems, size_t size );
: nItems
size .
:
pInt = reinterpret_cast<int*>( calloc(72, sizeof(int) );
, new.
delete
void free( void* block );
block.
, , -
( ) . C++ (C)

void* realloc( void* block, size_t size );
block
size .
realloc() .
.
0: #include <iostream>
1: #include <cstdlib>
2:
3: using namespace std;
4:
5: int main()
6: {
7: int* ip( 0 );
8: double* dp( 0 );
9:
10: ip = reinterpret_cast<int*>( malloc(3*sizeof(int)) );
11: dp = reinterpret_cast<double*>( calloc(3,sizeof(double)));
12: for ( int k(0); k <= 2; ++k )
518 16

13: {
14: ip[k] = k+1;
15: dp[k] = 1.1*ip[k];
16: }
17: for ( int k(0); k <= 2; ++k )
18: cout << ip[k] << " " << dp[k] << endl;
19: cout << "==========" << endl;
20: ip = reinterpret_cast<int*>( realloc(ip, 7*sizeof(int)) );
21: dp = reinterpret_cast<double*>(
22: realloc(dp, 7*sizeof(double)) );
23: for ( int k(3); k <= 6; ++k )
24: {
25: ip[k] = k+1;
26: dp[k] = 1.1*ip[k];
27: }
28: for ( int k(0); k <= 6; ++k )
29: cout << ip[k] << " " << dp[k] << endl;
30: free( dp );
31: free( ip );
32: } // main
:
1 1.1
2 2.2
3 3.3
==========
1 1.1
2 2.2
3 3.3
4 4.4
5 5.5
6 6.6
7 7.7
, malloc() calloc(), (. 10-
11). , realloc (. 20-22)
. , free() (. 30-31), .
new delete
, :
new delete
malloc(), calloc(), realloc() free().
:
C
new delete.

. -
.
, -
: C++ new delete
malloc() free().

C++ C.
malloc(0) -
o new.
519

16.12 realloc()
, new delete
. realloc, .
C++ 7, vector, map,
list, new
delete.

,
(p) T
nf .
ni ni .
MyTmpltLibXptn(::domainError)8
0 ni nf.
0 () ni. (p ==
0 && ni > 0) MyTmpltLibXptn(::noArray).
, MyTmpltLibXptn(::allocFailed)
.
template< typename T >
void renew( T*& p, int ni, int nf )
{
if ( ni < 0 || nf < ni )
throw MyTmpltLibXptn( "renew",
MyTmpltLibXptn::domainError, ni, nf );
// 0 <= ni <= nf
if ( p == 0 && ni > 0 )
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::noArray );
// (0 <= ni <= nf) && (p != 0 || ni == 0)
try
{
T* temp( new T[nf] );
for ( int k(0); k < ni; ++k ) temp[k] = p[k];
delete[] p; p = temp;
}
catch( bad_alloc& )
{
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::allocFailed );
}
} // void renew
:
1. , , .
2. bad_alloc new T[nf] -
temp[k] = p[k]. T
, 16.8. -
new2d. .
,
C++:
#include <iostream>
#include <new>

using namespace std;

template< typename T >


void renew( T*& p, int ni, int nf );

7 .
8 MyTmpltLibXptn , 16.9.
520 16

int main()
{
int* ip( 0 );
double* dp( 0 );

ip = new int [3]; dp = new double [3];


for ( int k = 0; k <= 2; ++k )
{ ip[k] = k+1; dp[k] = 1.1*ip[k]; }
for ( int k = 0; k <= 2; ++k )
cout << ip[k] << " " << dp[k] << endl;
cout << "==========" << endl;
renew( ip, 3, 7 ); renew( dp, 3, 7 );
for ( int k = 3; k <= 6; ++k )
{ ip[k] = k+1; dp[k] = 1.1*ip[k]; }
for ( int k = 0; k <= 6; ++k )
cout << ip[k] << " " << dp[k] << endl;
delete [] dp;
delete [] ip;
} // main
renew(ip, 3, 7) 7
int. 3
ip . renew(dp, 3,
7) dp.
C++ realloc vector
(Standard Template Library, STL).

16.13
-
(15.14.2) 15.14.

.
.
1

/
,

.
. :
GrElmn* grElmnTbl( 0 );

:
countRecords( bInOut, maxAtNo );
grElmnTbl = new GrElmn[maxAtNo];
, try, :
catch ( bad_alloc& )
{
cout << "not enough memeory to load data" << endl;
}
:
loadAllData( bInOut, grElmnTbl, maxAtNo );
:
521

void loadAllData( fstream& bInOut,


GrElmn grElmnTbl[], int maxAtNo )
{
bInOut.seekg( 0 );
for ( int k(0); k < maxAtNo; ++k )
GrElmn_load( grElmnTbl[k], bInOut );
} // loadAllData
editGrName . :
void editGrNameMM( GrElmn& a )
{
GrElmn_display( a, cout );
string newGrName;
cout << "new greek name: "; getline( cin, newGrName, '\n' );
if ( !newGrName.empty() )
{
GrElmn_setGrName( a, newGrName );
}
} // editGrNameMM
, /
( MM Main Memory).
, , :
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
editGrNameMM( grElmnTbl[aa-1] );
}
( aa aa-1 .)
, :
void saveAllData( fstream& bInOut,
GrElmn grElmnTbl[], int maxAtNo )
{
bInOut.seekp( 0 );
for ( int k(0); k < maxAtNo; ++k )
GrElmn_save( grElmnTbl[k], bInOut );
} // saveAllData
readRandom() writeRandom() . loadAllData()
saveAllData() .
:
#include <iostream>
#include <fstream>
#include <string>
#include <new>

using namespace std;

struct ApplicXptn
//
struct GrElmn
//
// GrElmn_...

void openFile( string& flNm, fstream& bInOut );


void countRecords( fstream& bInOut, unsigned int& noOfRecords );
void readAtNo( int maxAtNo, int& aa );
//
void editGrNameMM( GrElmn& a );
void loadAllData( fstream& bInOut,
GrElmn grElmnTbl[], int maxAtNo );
void saveAllData( fstream& bInOut,
GrElmn grElmnTbl[], int maxAtNo );

int main()
522 16

{
fstream bInOut;
string flNm( "elementsGr.dta" );
GrElmn* grElmnTbl( 0 );

try
{
openFile( flNm, bInOut );
// .. ( )
unsigned int maxAtNo;
countRecords( bInOut, maxAtNo );
grElmnTbl = new GrElmn[maxAtNo];
loadAllData( bInOut, grElmnTbl, maxAtNo );
bInOut.close();
int aa;
do {
// ..
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
editGrNameMM( grElmnTbl[aa-1] );
}
} while ( aa != 0 );
openFile( flNm, bInOut );
saveAllData( bInOut, grElmnTbl, maxAtNo );
bInOut.close();
if ( bInOut.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotClose,
flNm.c_str() );
delete[] grElmnTbl;
}
catch ( bad_alloc& )
{
cout << "not enough memory to load data" << endl;
}
catch( ApplicXptn& x )
//
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main
:
(grElmnTbl = new GrElmn[maxAtNo]),
(delete[] grElmnTbl).
, bad_alloc .

2
:

.
:
-
.
!
-
1.
. , -
74 (Tungsten),
!
523

!
.
:
. : linSearch()
12.2.1 (16.13.1). ,
( =)
!=. != (
==) GrElmn.
GrElmn :
bool operator!=( const GrElmn& lhs, const GrElmn& rhs )
{ return ( lhs.geANumber != rhs.geANumber ); }

bool operator==( const GrElmn& lhs, const GrElmn& rhs )


{ return ( lhs.geANumber == rhs.geANumber ); }
.
renew() .
:
( ).
( ).
... , , 12
renew() :
1 + 2 + 3 + ... + 11 = 66

12 .
:
. , 5
10. 15
.
. , 5 10
80; . ,
12
, 5 . -
35 40 10 15 .
linSearch
. , , n
n+1 .

:
GrElmn* grElmnTbl( 0 );
const unsigned int incr( 5 ); //
unsigned int nElmn; //
unsigned int nReserved; //
:
grElmnTbl = new GrElmn[incr];
nReserved = incr;
nElmn = 0;
aa
:
if ( nElmn+1 == nReserved )
{
renew( grElmnTbl, nElmn, nReserved+incr );
nReserved += incr;
}
524 16

readRandom( grElmnTbl[nElmn], bInOut, aa );


++nElmn;
:
nElmn+1 == nReserved. +1
linSearch .
renew() renew(grElmnTbl, nElmn, nReserved+incr). -
nReserved+incr.
nElmn .
nElmn .
nElmn nElmn-1.

:
void elmntInTable( GrElmn*& grElmnTbl, unsigned int& nElmn,
unsigned int& nReserved, unsigned int incr,
fstream& bInOut, int aa, unsigned int& pos )
{
GrElmn oneElmn( aa );
int lPos( linSearch(grElmnTbl, nElmn, 0, nElmn-1, oneElmn) );
if ( lPos < 0 )
{
if ( nElmn+1 == nReserved )
{
renew( grElmnTbl, nElmn, nReserved+incr );
nReserved += incr;
}
readRandom( grElmnTbl[nElmn], bInOut, aa );
++nElmn;
pos = nElmn - 1;
}
else
pos = lPos;
} // elmntInTable
:
(7) .
. :

nElmn.
renew
grElmnTbl nReserved.
, linSearch() lPos
, . linSearch() -
. -
oneElmn.
!= ,
oneElmn.geANumber aa,
:
oneElmn.geANumber = aa.
oneElmn .

struct GrElmn
{
// . . .
GrElmn( int aAN=0 ) { geANumber = aAN; }
}; // GrElmn
525

one-
Elmn linSearch() :
int lPos( linSearch(grElmnTbl, nElmn, 0, nElmn-1, GrElmn(aa)));

(lPos < 0).
pos
nElmn - 1.
lPos pos.

:
saveUpdateTable( bInOut, grElmnTbl, nElmn );
:
void saveUpdateTable( fstream& bInOut,
const GrElmn grElmnTbl[], int nElmn )
{
for ( int k(0); k < nElmn; ++k )
writeRandom( grElmnTbl[k], bInOut );
} // saveUpdateTable
:
#include <iostream>
#include <fstream>
#include <string>
#include <new>

using namespace std;

struct MyTmpltLibXptn
//

template< typename T >


void renew( T*& p, int ni, int nf );
template< typename T >
int linSearch( const T v[], int n,
int from, int upto, const T& x );

struct ApplicXptn
//

struct GrElmn
{
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
GrElmn( int aAN=0 ) { geANumber = aAN; }
}; // GrElmn

// GrElmn_...
bool operator!=( const GrElmn& lhs, const GrElmn& rhs );
bool operator==( const GrElmn& lhs, const GrElmn& rhs );

void openFile( string& flNm, fstream& bInOut );


void countRecords( fstream& bInOut, unsigned int& noOfRecords );
void readAtNo( int maxAtNo, int& aa );
void readRandom( GrElmn& a, istream& bin, int atNo );
void writeRandom( const GrElmn& a, ostream& bout );
void editGrNameMM( GrElmn& a );
526 16

void saveUpdateTable( fstream& bInOut,


const GrElmn grElmnTbl[], int nElmn );
void elmntInTable( GrElmn*& grElmnTbl, unsigned int& nElmn,
unsigned int& nReserved, unsigned int incr,
fstream& bInOut, int aa, unsigned int& pos );

int main()
{
fstream bInOut;
string flNm( "elementsGr.dta" );
GrElmn* grElmnTbl( 0 );
const unsigned int incr( 5 ); //
unsigned int nElmn; //
unsigned int nReserved; //

try
{
try { grElmnTbl = new GrElmn[incr]; }
catch( bad_alloc& )
{ throw ApplicXptn( "main", ApplicXptn::allocFailed ); }
nReserved = incr;
nElmn = 0;

openFile( flNm, bInOut );


// .. ( )
unsigned int maxAtNo;
countRecords( bInOut, maxAtNo );
int aa;
do {
// ..
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
unsigned int pos;
elmntInTable( grElmnTbl, nElmn, nReserved, incr,
bInOut, aa, pos );
editGrNameMM( grElmnTbl[pos] );
}
} while ( aa != 0 );
saveUpdateTable( bInOut, grElmnTbl, nElmn );
bInOut.close();
if ( bInOut.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotClose,
flNm.c_str() );
delete[] grElmnTbl;
}
catch( ApplicXptn& x )
{
switch ( x.errCode )
{
//
case ApplicXptn::allocFailed:
cout << "cannot get enough memory " << " in "
<< x.funcName << endl;
break;
default:
cout << "unexpected ApplicXptn from "
<< x.funcName << endl;
} // switch
} // catch( ApplicXptn
catch( MyTmpltLibXptn& x )
{
switch ( x.errCode )
{
case MyTmpltLibXptn::domainError:
cout << x.funcName << "called with parameters "
<< x.errVal1 << ", " << x.errVal2 << endl;
527
lnData lnNext lnData lnNext lnData lnNext lnData lnNext
20 8 38 xxx
40.08 15.9994 87.63
Ca Sr
Calcium Oxygen Strontium

slHead slTail
. 16-6 , .
break;
case MyTmpltLibXptn::noArray:
cout << x.funcName << "called with NULL pointer"
<< endl;
break;
case MyTmpltLibXptn::allocFailed:
cout << "cannot get enough memory " << " in "
<< x.funcName << endl;
break;
default:
cout << "unexpected MyTmpltLibXptn from "
<< x.funcName << endl;
} // switch
} // catch( MyTmpltLibXptn
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main
main ( ) renew().
, renew()
MyTmpltLibXptn, main bad_alloc
ApplicXptn(::allocFailed).
ApplicXptn
ApplicXptn::allocFailed.

3
. 2 :
()
.
(simply linked list) (se-
quence) .
.
. 16-6. ,
(nodes). - -
.
( GrElmn) --
.
:
struct ListNode
{
GrElmn lnData;
ListNode* lnNext;
}; // ListNode
528 16

.
,
. :
struct SList
{
ListNode* slHead;
ListNode* slTail;
}; // SList
. 16-7 . -
:
struct SList
{
ListNode* slHead;
ListNode* slTail;
SList()
{
try { slHead = new ListNode; }
catch( bad_alloc& )
{ throw ApplicXptn( "SList", ApplicXptn::allocFailed ); }
slHead->lnNext = 0; slTail = slHead;
} // SList
}; // Slist
.
: .
.
; delete
.
:
( ).
.
.
.

:9
void SList_push_front( SList& lst, const GrElmn& aData )
{
ListNode* pnln( 0 );
try { pnln = new ListNode; }
catch( bad_alloc& )
{ throw ApplicXptn( "SList_push_front",
ApplicXptn::allocFailed ); }
pnln->lnData = aData; pnln->lnNext = lst.slHead;
lst.slHead = pnln;
} // SList_push_front
. 16-
6:
. aData.
-
xxx
lst.slHead = new ListNode
. :
,
pnln pnln = new ListNode. . 16-8

slHead slTail
. 16-7
9 STL. .
529
lnData lnNext lnData lnNext
xxx 8
15.9994
lnData lnNext lnData lnNext lnData lnNext lnData lnNext
Oxygen
38 xxx 38 xxx
87.63 87.63
Sr Sr
Strontium Strontium

pnln pnln
aData aData

8 8
15.9994 15.9994
slHead slTail slHead slTail
Oxygen Oxygen

. 16-8 : . 16-8 :
ListNode* pnln( new ListNode ); pnln->lnData = aData;
lnData lnNext lnData lnNext

8 8
15.9994 15.9994
lnData lnNext lnData lnNext lnData lnNext lnData lnNext
Oxygen Oxygen
38 xxx 38 xxx
87.63 87.63
Sr Sr
Strontium Strontium

pnln pnln
aData aData

8 8
15.9994 15.9994
slHead slTail slHead slTail
Oxygen Oxygen

. 16-8 : . 16-8 :
pnln->lnNext = lst.slHead; lst.slHead = pnln;
. .
, lnData -
pnln->lnData = aData. .
. 16-8.
pnln->lnNext = lst.slHead . lnNext
. . 16-8
.
lst.slHead = pnln (. 16-8):
slHead
( ).
pnln .
, ,
: . 16-8 16-8, .
:
ListNode* pnln( lst.slHead );
lst.slHead = new ListNode;
(lst.slHead)->lnData = aData;
(lst.slHead)->lnNext = pnln;

linSerch:
ListNode* SList_listSearch( const SList& lst,
const GrElmn& aData )
{
ListNode* p( lst.slHead );
while ( p->lnData != aData && p->lnNext != lst.slTail )
p = p->lnNext;
return (p->lnData == aData ? p : 0 );
530 16

} // SList_listSearch
p lst.slHead
p = p->lnNext.
p = p->lnNext
, (p->lnData != aData)
(p->lnNext != lst.slTail).
(p->lnData == aData)
p 0.
-
while; ,
. , const
SList& lst : const.
ListNode* SList_listSearch( const SList& lst,
const GrElmn& aData )
{
SList& ncLst( const_cast<SList&>(lst) );
ncLst.slTail->lnData = aData;
ListNode* p( lst.slHead );
while ( p->lnData != aData ) p = p->lnNext;
return (p != lst.slTail ? p : 0 );
} // SList_listSearch
ncLst lst SList& const :
ncLst.slTail->lnData = aData;
, while :
ListNode* p( lst.slHead );
while ( p->lnData != aData ) p = p->lnNext;
return:
return (p != lst.slTail ? p : 0 );
( p , 0)
linSearch() . SList_listSearch
GrElmn. , editGrNameMM -
:
ListNode* pos;
elmntInList( lst, bInOut, aa, pos );
editGrNameMM( pos->lnData );
: p
lst.slHead p = p-
>lnNext ... ... (p->lnNext != lst.slTail).
-
. :
void saveUpdateList( fstream& bInOut, const SList& lst )
{
for ( ListNode* p(lst.slHead); p != lst.slTail; p = p->lnNext )
writeRandom( p->lnData, bInOut );
} // saveUpdateList
.
void SList_deleteAll( SList& lst )
{
while ( lst.slHead != lst.slTail )
{
ListNode* p( lst.slHead );
lst.slHead = (lst.slHead)->lnNext;
delete p;
}
delete lst.slHead;
531

lst.slTail = lst.slHead = 0;
} // SList_deleteAll
() :
p lst.slHead .
lst.slHead .
p.
lst.slHead == lst.slTail:
. delete lst.slHead .
; ; ! !
SList_push_front().
:
lst.slTail = lst.slHead = 0;
:
#include <iostream>
#include <fstream>
#include <string>
#include <new>

using namespace std;

struct ApplicXptn
//

struct GrElmn
//

// GrElmn
//

struct ListNode
{
GrElmn lnData;
ListNode* lnNext;
}; // ListNode

struct SList
{
ListNode* slHead;
ListNode* slTail;
SList()
{
try { slHead = new ListNode; }
catch( bad_alloc& )
{ throw ApplicXptn( "SList", ApplicXptn::allocFailed ); }
slHead->lnNext = 0; slTail = slHead;
} // SList
}; // SList

void SList_push_front( SList& lst, const GrElmn& aData );


ListNode* SList_listSearch( const SList& lst,
const GrElmn& aData );
void SList_deleteAll( SList& lst );

void openFile( string& flNm, fstream& bInOut );


void countRecords( fstream& bInOut, unsigned int& noOfRecords );
void readAtNo( int maxAtNo, int& aa );
void readRandom( GrElmn& a, istream& bin, int atNo );
void writeRandom( const GrElmn& a, ostream& bout );
void editGrNameMM( GrElmn& a );
void saveUpdateList( fstream& bInOut, const SList& lst );
void elmntInList( SList& lst,
fstream& bInOut, int aa, ListNode*& pos );
532 16

int main()
{
fstream bInOut;
string flNm( "elementsGr.dta" );

try
{
SList lst;
openFile( flNm, bInOut );
// .. ( )
unsigned int maxAtNo;
countRecords( bInOut, maxAtNo );
int aa;
do {
// ..
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
ListNode* pos;
elmntInList( lst, bInOut, aa, pos );
editGrNameMM( pos->lnData );
}
} while ( aa != 0 );
saveUpdateList( bInOut, lst );
bInOut.close();
if ( bInOut.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotClose,
flNm.c_str() );
SList_deleteAll( lst );
}
catch( ApplicXptn& x )
//
catch( ... )
{
cout << "unexpected exception" << endl;
}
} // main
.

: -
.
, .. -
.
system crash
(
).
, , GrElmn_save()
ApplicXptn(::cannotWrite). ; , -
memory stick ! -
. 2 3 GrElmn_load() ApplicXptn
(::cannotRead).
. , ...
,
, .

16.13.1 linSearch()
linSearch 12.2.1
533

template< typename T >


int linSearch( const T v[], int n,
int from, int upto, const T& x )
{
if ( v == 0 && n > 0 )
throw MyTmpltLibXptn( "linSearch",
MyTmpltLibXptn::noArray );
int fv( -1 );
if ( v != 0 && (0 <= from && from <= upto && upto < n) )
{
T* ncv( const_cast<T*>(v) );
T save( v[upto+1] ); // v[upto+1]
ncv[upto+1] = x; //
int k( from );
while ( v[k] != x ) ++k;
if ( k <= upto ) fv = k;
else fv = -1;
ncv[upto+1] = save; //
// (from <= fv <= upto && v[fv] == x) ||
// (fv == -1 && (j:from..upto v[j] != x))
}
return fv;
} // linSearch
int T :
v == 0. , -
n 0 -1 ( ) .
T,
:
(
, , 16.8)
ncv[upto+1] = x ncv[upto+1] = save.
.
!= v[k] != x while.
! ;
. T
save(v[upto+1]).10 , ,
.

T -
. , -
...

16.13.2 linSearch()
linSearch , C++
(std::)find : -
( ).
. ,
.
, , :
template< typename T >

10 :
T save;
save = v[upto+1]; // v[upto+1]
534 16

T* find( T* first, T* last, T value )


:
T (==).
[ first..last )
first - T* p ++p. last
.
value .
find() fPos
*fPos == value. value last.
ar T
linSearch() :
unsigned int size, from, upto;
int ndx;
T value;
// . . .
ndx = linSearch( ar, size, from, upto, value );
if ( ndx >= 0 ) //
// . . .
find :
unsigned int from, upto,;
T* pos;
T value;
// . . .
pos = find( ar+from, ar+upto, value );//11
if ( pos != ar+upto ) //
// . . .
. 2, elmntInTable :
void elmntInTable( GrElmn*& grElmnTbl, unsigned int& nElmn,
unsigned int& nReserved, unsigned int incr,
fstream& bInOut, int aa, GrElmn*& pos )
{
GrElmn oneElmn( aa );
GrElmn* lPos( find(grElmnTbl, grElmnTbl+nElmn, GrElmn(aa)) );
if ( lPos == grElmnTbl+nElmn ) //
{
if ( nElmn+1 == nReserved )
{
renew( grElmnTbl, nElmn, nReserved+incr );
nReserved += incr;
}
readRandom( grElmnTbl[nElmn], bInOut, aa );
++nElmn;
pos = &grElmnTbl[nElmn-1];
}
else
pos = lPos;
} // elmntInTable
:
: GrElmn*& pos.
, lPos GrElmn*.
find GrElmn(aa)
grElmnTbl:
( ),

11 , :
pos = find( &ar[from], &ar[upto], value );
535

, :
grElmnTbl+nElmn &grElmnTbl[nElmn].
lPos ==
grElmnTbl+nElmn.
find ;
:
++p p = p->lnNext.
.
.

16.13.3 reserved + incr 2*reserved


.
reserved == incr n .
n/incr .12 k- k*incr (k-
1)*incr .
, :
0*incr + 1*incr + 2*incr + + ((n/incr)-1)*incr = (n/incr)*((n/incr)-1)*incr/2 = O(n2)
C++ (STL), ,
. , incr , k-
2k-1*incr 2k-2*incr (k 2:
). n
== 2p-1*incr . : p = log2(n/incr)+1.
:
20*incr + 21*incr + 22*incr + + 2p-2*incr = incr*(2p-1-1) = O(n)
(memory allocators) -
(containers) C++.
STL,
-
. , , , . ,
. 2, :
renew( grElmnTbl, nElmn, nReserved+incr );
nReserved += incr;
:
renew( grElmnTbl, nElmn, 2*nReserved );
nReserved *= 2;

16.14
(CERT 2009):

.13

.14

12 n = 2N*incr.
13 MEM03: Clear sensitive information stored in reusable resources returned for reuse.
14 MEM06: Ensure that sensitive data is not written out to disk.
536 16

16.3.
:
double* a1( new double );
double* a2;
*a1, *a2. ,
cout << *a1 << " " << *a2 << endl;
:
1.23 4.56
:
delete a1; delete a2;
*a1 :
a1 = new double;
cout << *a1 << endl;
:
4.56
; *a1
*a2. , :
delete, , .
new, .
:
#include <iostream>
using namespace std;

void f1()
{
char m[] = "abcd";
cout << "from f1: m = " << m << endl;
}

void f2()
{
char q[5];
cout << "from f2: q = " << q << endl;
}

int main()
{
f1();
f2();
}
:
from f1: m = abcd
from f2: q = abcd
; f1() m
"abcd". f1()
. new delete -
. f2(), , -
m f1() q f2().
;
. -
.
,
(passwords), -
. -
537

.
: -
\0 C memset():15
memset( a2, '\0', sizeof(double) ); delete a2;
f1:
void f1()
{
char m[] = "abcd";
cout << "from f1: m = " << m << endl;
memset( m, '\0', strlen(m) );
}
:
memset() :
void* memset( void* s, int c, size_t n );
: n c
s. s.
: -
, , -
-
!
.16
:
16.3 -
.

(DBMS)
.
,
( ) (memory dump) ,
. , ,

.
.

16.15

. p
- T* :
p = new T -
T. p *p.
*p T .
*p delete p.
delete p *p .
p = new T[]
T. n
.

15 #include <string> .
16 , Windows API SecureZeroMemory().
538 16

p[0], p[1], p[n-1].


n T.
delete
p[].
..
0 ( NULL
(std::)nullptr).
(delete p; delete p)
. delete 0 .
delete[] 0.
C. :
malloc(), calloc() free()
delete.
new, new [] delete,
delete[] .
, :
.

:
,

.
,
.


16-1 14.7.3 swap() C
string.
string ( ). , -
, . ...
16-2 Horner
(9.4, . 1). , :
const int N = 20;
double a[N];
a
19 . , -
20 -
.
, ,
.
16-3 SList_deleteAll(), SList_clear()
-
.

17
*
:


.
:
.
:






:
17.1 ................................................................................................................................ 541
17.2 - ............................................................................................ 543
17.2.1 * C99 ...................................................................................................................................544
17.3 .................................................................................................................... 545
17.3.1 unsigned ................................................................................................................................547
17.4 * () ..................................................................................................................... 548
17.5 C++ ............................................................................................................................. 549
17.6 ................................................................................................. 552
17.6.1 .......................................................................................................................................553
17.6.2 1 .........................................................................................................................554
17.6.3 0 .........................................................................................................................555
17.6.4 "1" ..........................................................................................................................................................556
17.6.5 .............................................................................................................................................556
17.7 bitmask ........................................................................................................................................... 557
17.8 .................................................................................................. 560
17.9 float ...................................................................................... 560
17.9.1 ............................................................................................................564
17.10 ....................................................................................................... 564
17.11 float ............................................................................................. 565
17.11.1 ...............................................................................................................................................................566
17.11.2 - IEEE ..................................................................................................................567
17.11.3 double long double ..................................................................................................568
17.11.4 C.................................................................................................................569
17.12 .............................................................................................................. 570

539
540 17

17.13 ....................................................................................................... 570


17.13.1 ....................................................................................................................................571
17.13.2 .......................................................................................................................................571
17.14 ..................................................................................... 573
17.15 ................................................................................................................................ 576
................................................................................................................................................................... 578
.............................................................................................................................................................................578
.............................................................................................................................................................................579
.............................................................................................................................................................................579

:

, -
, : 0,1,2,3,4,5,6,7,8,9.
( ), -
: - ().
+ (),
(.. -5109, 2048, +2048). , -
( : ,, . .
: .), (..
48,25).
(positional),

. , 3 6343 300 (3102),
3 3 (3100).
,
(additive) (.. = 10 + 10 + 10
+ 1 + 1 + 1 = 33) ( = 100 + 2 = 102),
.

:
= L-1L-1 + L-2L-2 + ... + 00 (1)
(base, radix) -
1 ( ).
k (k: 0..L-1) [0..) (0 k < ),
L ( ). , -
. -
= 10 : 0, 1, 2,...,9.
, . ..
= 2 3, 8, 10, 16, ,
, , . = 7635,
, :
= 7103 + 6102 + 3101 + 5100 = 7635
3 = 7, 2 = 6, 1 = 3 0 = 5.
= 8 :
0,1,2,...,7. = 7635, ,
5149, :
= 76358 = 783 + 682 + 381 + 580 = 514910
(.. 7635)
. , ,
,
( ).
* 541

, ,
k ( ) .

17.1
(binary) ,
( ).
(two state systems),

.
, 0 1
( = 2).
,
2. , = 12 (8
+ 4 = 23 + 22), :
= 123 + 122 + 021 + 020 = 11002
3 = 1, 2 = 1, 1 = 0 0 = 0.

(hexadecimal) , = 16 :
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F
A, B, C, D, E F ( a, b, c, d, e, f) ()
: , , , , .
153 :
15316 = 1162 + 5161 + 3160 = 256 + 80 + 3 = 33910
1A3F :
1A3F16 = 1163 + A162 + 3161 + F160
= 1163 + 10162 + 3161 + 15160
= 671910
. 17-1 1 20
.
. 17-1 -
. -
, 9 16- 10- , 8-
, 3- 2- .
L -
:
= L (2)
, , = 2 L = 4, 16 (=24) -
( ), . : 0000, 0001, 0010,... 1111.
, -
, L -
:
L = logB (3)
, 16 , 0 15, -
log216 = 4 . 9 -
log39 = 2 . -
(3) . 17-1.
, . 17-1, -
. .. 2010 10100.
542 17

10 16 8 3 2
0 00 00 000 00000
1 01 01 001 00001
2 02 02 002 00010
3 03 03 010 00011
4 04 04 011 00100
5 05 05 012 00101
6 06 06 020 00110
7 07 07 021 00111
8 08 10 022 01000
9 09 11 100 01001
10 0A 12 101 01010
11 0B 13 102 01011
12 0C 14 110 01100
13 0D 15 111 01101
14 0E 16 112 01110
15 0F 17 120 01111
16 10 20 121 10000
17 11 21 122 10001
18 12 22 200 10010
19 13 23 201 10011
20 14 24 202 10100
. 17-1
.

: 010 | 100
, 248. ,
0001 | 0100 : 1416. ,
8 = 23 16 = 24.
2.5 (. 2-1) C++, ,
: unsigned char, unsigned int, unsigned long.
unsigned char 1
(2), 28 = 256 , 0
255. unsigned short int ( ) 16
216 = 65 536 , 0
65 535. , unsigned long 232 = 4 294 967 296 , 0
4 294 967 295. unsigned int; unsigned long unsigned
short int.
.
1.8.1 1.8.2 C++
"0x"
"0X" "0". .., :
k = 255; k = 0XFF; k = 0xff; k = 0377;
. 255 -
. FF16 3778.

1 , . -
. 2 :
sizeof(char) sizeof(short) sizeof(int) sizeof(long)
* 543

C++, 0XFF 0377. -


:
" 0" ()
.

17.2 -
;
+ -, -
: 0 + 1 -. , 7
, 0 2 7 - 1 = 127.
-127 +127. -
- . : 255 ,
unsigned char 256 -128 127! ,
, 0 () : +0
(00000000) -0 (10000000).
, "-
2" (2's complement).

, 12 , :
7 6 5 4 3 2 1 0
00001100
2:
1: 0 1 1 0:
7 6 5 4 3 2 1 0
11110011
( 1)
2: 1
11110011
+ 00000001
11110100
7 6 5 4 3 2 1 0
-12.

-
1 7. ;
20 (00010100) :
11110100
+0 001 0100
10 000 1000
, 1, -
8, : (-12) + 20 = 8.
: -
28+23 = 264. 256 (= 28). ' ,
(modulo arithmetic).
:
2
.
:
2,
,
544 17

2 ,
.
;
7 6 5 4 3 2 1 0
0 1 1 1 1 1 1 1 = 12710
-128 :
7 6 5 4 3 2 1 0
1 0 0 0 0 0 0 0 = -12810
-128. : 1
7, . -
2:
1: 1
7 6 5 4 3 2 1 0
10000000
- 1
01111111
7 6 5 4 3 2 1 0
2: 0 1 1 0:
10000000
27 = 128.
: 00000000.
C++ :
(signed) char, 8 . -128 127
28 = 256.
short int, 16 . -32 768 32 767
216 = 65 536.
int long int, 32 . -2 147 483 648 2 147 483 647
232 = 4 294 967 296.
()
. .
.
; .

17.2.1 * C99
C99 (ISO/IEC 1999) C 64 : long
long int unsigned long long int.
long long int
LLONG_MIN: -9223372036854775807 = -(263 - 1)
long long int
LLONG_MAX: +9223372036854775807 = 263 - 1
unsigned long long int
ULLONG_MAX: 18446744073709551615 = 264 - 1
long long int unsigned long long int C++11.
64 , C99
- .
intN_t uintN_t. N . gcc
(Dev C++), stdint.h, :
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
* 545

typedef unsigned uint32_t;


typedef long long int64_t;
typedef unsigned long long uint64_t;
; 32 -
long int int
:
int32_t x;
.
int_leastN_t
uint_leastN_t ( N: 8, 16, 32, 64). , int_least32_t
32 .
int_fastN_t
uint_fastN_t ( N: 8, 16, 32, 64). int_fast32_t
(, ) 32 .
, intmax_t
.
uintmax_t. gcc, stdint.h, :
typedef long long intmax_t;
typedef unsigned long long uintmax_t;
C++.

17.3
:
#include <iostream>
#include <climits>
using namespace std;
int main()
{
int i( INT_MAX );
i = 4*i;
cout << i << endl;
}
:
-4
: (gcc - Dev) C++ int 32
INT_MAX :
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
01111111111111111111111111111111
:
3 3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 0 = 8589934588
, int
(overflow). 2,
: i 0 31 -
. cout << i << endl,
(31) 1,
! , 1:
11111111111111111111111111111100
- 1
11111111111111111111111111111011
1 0 0 1:
00000000000000000000000000000100
546 17

4.
;
int ( ) -
. -
, .
;
. x, y, int x + y,
. x, y :
INT_MIN x INT_MAX
INT_MIN y INT_MAX

INT_MIN x + y INT_MAX
INT_MIN - y x INT_MAX - y
, :
if (INT_MIN-y <= x && (x <= INT_MAX-y)
s = x + y;
else

INT_MIN - y INT_MAX - y ! .. y
, INT_MAX - y . .
' , x, y
. x, y 0 x INT_MAX - y
. x, y < 0
INT_MIN - y x .
:
int addInt( int x, int y )
{
int fv;

if ( x >= 0 )
{
if ( y < 0 ) fv = x + y;
else if ( x <= INT_MAX - y ) fv = x + y;
else
throw IntOvrflXptn( "addInt", 0, x, y );
}
else // x < 0
{
if ( y >= 0 ) fv = x + y;
else if ( INT_MIN - y <= x ) fv = x + y;
else
throw IntOvrflXptn( "addInt", 0, x, y );
}
return fv;
} // addInt
, , c = a + b c =
addInt(a, b) -
; !
.2 ,
, :
#include <iostream>
#include <string>
#include <climits>

2 : .
* 547

using namespace std;

struct IntOvrflXptn
{
char funcName[100];
int errCode;
int errVal1;
int errVal2;
IntOvrflXptn( const char* fn, int ec, int ev1=0, int ev2= 0 )
{
strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errVal1 = ev1; errVal2 = ev2;
}
}; // IntOvrflXptn

int addInt( int x, int y );

int main()
{
int x, y, z;

cout << " < 100" << endl;


cin >> x >> y;
try
{
z = addInt( x, y );
cout << z << endl;
// . . .
}
catch ( IntOvrflXptn& xp )
{
cout << xp.errVal1 << " + " << xp.errVal2
<<"??? !" << endl;
}
// . . .
do
{
cout << " < 100" << endl;
cin >> x >> y;
} while (x <= 0 || 100 < x || y <= 0 || 100 < y);
z = x + y;
// . . .
} // main
.

. addInt() z .
, x, y,
.

17.3.1 unsigned
6.8 ( 13.3.1) :
unsigned int, unsigned
long int, unsigned short int, unsigned char , : int, long int,
short int, char. .

n = -1024;
cout << n << " " << intSqrt(n) << endl;

unsigned int intSqrt( unsigned int x );
548 17

; x 4294966272
() .
. int 1024 (= 210)
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00000000000000000000010000000000
-1024 2 :
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
11111111111111111111110000000000
n x.
unsigned int.
4294966272.
: -1024
4294966272.

17.4 * ()
(4.8)
Pascal . ,
,
C.

enum Digit { miden = 48, zero = 48, one, two, three, four,
five, six, seven, eight, nine };
:
Digit d1( 49 );
: invalid conversion from int to Digit (gcc Dev
C++).3 :
Digit d1( static_cast<Digit>(49) );
. !
:
d1 = static_cast<Digit>( 9 );
, , ,
static_cast<Digit>(49) static_cast
<Digit>(57).
:
C++ -
0 -

. -
nine 5710 = 1110012.
1111112 = 6310.
-
. , -
neg = -1, -64 63 (-
7 ). neg = -100, -128 127
( 8 ).

3 , (warnings), ! ...
* 549
7 6 5 4 3 2 1 0
7 6 5 4 3 2 1 0 00001100 x
00001100 x
00100100 y
11110011 ~x
00000100 x&y

. 17-2 &
. 17-1 ~
(and).
( 1).

, -
Digit static_cast<Digit>(n) n int.

17.5 C++
C++ -
() -
(bitwise operations).
(shift). :
unsigned char x, y;
// . . .
x = 77;
:
7 6 5 4 3 2 1 0
01001101
y = x << 2 ( 2 ),
:
x 2 ,
2 ( , 7 6) ,
0.
.
, y :
7 6 5 4 3 2 1 0
00110100
. y = x >> 2
( 2 ), y:
7 6 5 4 3 2 1 0
00010011
; :
x unsigned
.
x unsigned 1
.
:
x = x << N x <<= N
x = x >> N x >>= N.
1.
. x 12, ,
7 6 5 4 3 2 1 0

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

y = x << 2 y : 0 0 1 1 0 0 0 0 . 25+24 = 48 = 124,


7 6 5 4 3 2 1 0

y = x >> 2 y : 0 0 0 0 0 0 1 1 . 21+20 = 3 = 12/4,


, :
x << N x 2 x >> N x / 2 ;
,
550 17

7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
00001100 x 00001100 x
00100100 y 00100100 y
00101100 x|y 00101000 x^y

. 17-3 | (or). . 17-4 ^ (xor).

( <<)
(char, short, int, long).
C++
. ,
: -
.
:
, , << >>,
: ()
;
, /
. , . :
int x = 12;
cout << x << 2 << endl;
cout << (x << 2) << endl;
:
122
48
122 , : x,
12 2 122.
: x << 2, , , 48.
C++ ~, &, | ^
( !, &&, || != ). x, y
unsigned char:
~x (. 17-1) x 0 1 -
1 0 ( 1).
x & y x y and .
. 17-2 1 2
1 x y.
x | y x y or . .
17-3 x | y 1
2 1 x y,
3 1 x
5 1 y.
1 x | y x + y. ..
y 00100010 ( 3410) x | y 00101110
4610 = 12 + 34.
x ^ y x y xor .
. 17-4 x ^ y 1
3 1 x
5 1 y.
:
x = x & y x &= y,
* 551

x = x | y x |= y
x = x ^ y x ^= y.
: :
short int m( 3 );
char c( -5 );
: m |= c. c : 111110 11.
| m c
. m short int
1111111111111011 (= -5 short int)!!!
. :
unsigned char c( 251 );
c (11111011)
0000000011111011.
(CERT 2009):4
unsigned.5
<< &.

:
int bitValue( unsigned char b, int pos )
pos b.
; : unsigned char t t 0
pos 1. b & t; t
0 pos P && false false,
b & t: 0 pos.
pos, t 1:
b 0 b & t 0 0 ()
.
b 1 b & t 1 0
.
t ; :
unsigned char t( 1 );
t = t << pos;
:
t 1 1 0 t 0
t = t << pos 1, pos ,
0.

b, pos < 0 > 7 .

int bitValue( unsigned char b, int pos )
{
if ( pos < 0 || 7 < pos ) throw pos;

unsigned char t( 1 );
t <<= pos;

4 INT13: Use bitwise operators only on unsigned operands.


5 ,
. ,
!
552 17

return ( ((b & t) != 0) ? 1 : 0 );


} // bitValue
(unsigned char) 12
unsigned char x( 12 );
:
for ( int pos(7); pos >= 0; --pos )
cout << bitValue( x, pos );
cout << endl;
:
00001100
bitValue() :
void display( ostream& tout, unsigned char b )
{
for ( int pos(7); pos >= 0; --pos )
tout << bitValue( b, pos );
} // display
.
12
20 display():
#include <iostream>
using namespace std;

int bitValue( unsigned char b, int pos );


void display( ostream& tout, unsigned char b );

int main()
{
unsigned char x;
int k;

try
{
x = 12;
display( cout, x ); cout << endl;
x = 20;
display( cout, x ); cout << endl;
}
catch ( int& p )
{
cout << " bitValue "
<< p << endl;
}
} // main

17.6
' , ,
, , ,
. ,
, ,
(1) (0). -
, .. unsigned long, -
(bitsets) (bitmaps)6.

6 bitmap (bitmap graphics).


* 553

: -
.
(T) int, unsigned int, long, un-
signed long, short, unsigned short, char, unsigned char, wchar_t, long long, unsigned
long long.
:
struct BitmapXptn
{
enum { outOfRange, paramErr };
char funcName[100];
int errorCode;
int errVal1, errVal2;
BitmapXptn( const char* mn, int ec, int v1, int v2 = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
errVal1 = v1; errVal2 = v2; }
}; // BitmapXptn
! ( ) -
b[pos] b pos.
C++ .

17.6.1
bitValue :
template < typename T > int bitValue( T b, int pos )
7,

8(sizeof b) - 1
:
// bitValue -- b[pos]
// : 0 <= pos < 8*(sizeof b)
template < typename T >
int bitValue( T b, int pos )
{
if ( pos < 0 || 8*(sizeof b) <= pos )
throw BitmapXptn( "bitValue", BitmapXptn::outOfRange, pos );

T t( 1 );
t <<= pos;
return ( ((b & t) != 0) ? 1 : 0 );
} // bitValue
display()
:7
template < typename T >
void display( ostream& tout, T b )
{
int lastb( 8*(sizeof b) - 1 );

for ( int pos(lastb); pos >= 0; --pos )


tout << bitValue( b, pos );
} // display

7 ,
.
554 17

17.6.2 1
:
template < typename T > void setBit( T& b, int pos )
:
1 pos.
b .
pos, :
0 <= pos < 8(sizeof b)
; ,
T t( 1 );
t <<= pos;
t 0 pos 1. b |
t :
1 pos, t 1 P || true true.
b , t 0
P || false P.
:
// setBit --
// "1" pos
// : 0 <= pos < 8*(sizeof b)
// :
// b[pos] == 1 && k!=pos: b[k]==b[k]
template < typename T >
void setBit( T& b, int pos )
{
if ( pos < 0 || 8*(sizeof b) - 1 < pos )
throw BitmapXptn( "setBit", BitmapXptn::outOfRange, pos );

T t( 1 );
t <<= pos;
b |= t;
} // setBit
:
1
si unsigned short int (16 )
0 10, 3 9:
si = 0;
setBit( si, 10); setBit( si, 3); setBit( si, 9);
display( cout, si ); cout << endl;
:
0000011000001000

2
si unsigned short int
uc unsigned char. , 13 si
1:
display( cout, uc ); cout << endl;
si = uc;
setBit( si, 13 );
display( cout, si ); cout << endl;
:
11111011
0010000011111011
* 555

:
:
1;
. bitValue():
T t( 1 );
t <<= pos;
if ( (b & t) == 0 ) b |= t;
:
b & t if
1 b |= t.
b |= t
.

17.6.3 0
:
template < typename T > void clearBit( T& b, int pos )
:
0 pos.
b .

0 1 and or: ,
t 1 pos 0. b &
t :
0 pos, t 0 P && false
false.
b , t 1
P && true P.
t 1 pos 0;
:
T t( 1 );
t <<= pos; t = ~t;

// clearBit --
// "0" pos
// : 0 <= pos < 8*(sizeof b)
// :
// b[pos] == 0 && k!=pos: b[k]==b[k]
template < typename T >
void clearBit( T& b, int pos )
{
if ( pos < 0 || 8*(sizeof b) - 1 < pos )
throw BitmapXptn( "clearBit", BitmapXptn::outOfRange, pos );

T t( 1 );
t <<= pos; t = ~t;
b &= t;
} // clearBit
556 17


m unsigned short int si
. 2, , m 0
:
m = si;
for ( int k(0); k < 8*sizeof(m); k += 2 )
clearBit( m, k );
display( cout, m ); cout << endl;
:
0010000010101010

17.6.4 "1"
:
template < typename T > size_t count1( T b )
1
b T.
8(sizeof b) . -
b & t t T 1. 1 -
t.
// count1 -- b 1
// : true
// : fv == b 1
template < typename T >
size_t count1( T b )
{
const size_t lastb( 8*(sizeof b) 1 );
T t( 1 );
size_t fv( 0 );

for ( int k(0); k <= lastb; ++k )


{
if ( (b & t) != 0 ) ++fv;
t <<= 1;
}
return fv;
} // count1
b (1: ), count1
.

17.6.5
:
template < typename T > T part( T b, int pos1, int pos2 )
T b pos1 pos2.
: 16 :
1 1 1 1 1 1
5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
0001011010111000

4 9 0:
1 1 1 1 1 1
5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
0000001010110000
* 557

0 3 10 15.
clearBit -
. 6 (=15-9)
:
1 1 1 1 1 1
5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
1010111000000000
10 (= 15-9 + 4) :
1 1 1 1 1 1
5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
0000000000101011
, 4 .
: 15 () 8( sizeof b)1, 4
pos1 9 pos2 :
// part -- b
// pos1 pos2
// : 0 <= pos1 <= pos2 < 8*(sizeof v)
// : k: 0..pos1-1 b[k]==0 &&
// k: pos1..pos2 b[k]==b[k] &&
// k: pos2+1..8*(sizeof v)-1 b[k]==0
template < typename T >
T part( T b, int pos1, int pos2 )
{
const size_t lastb( 8*(sizeof b) 1 );

if ( pos2 < pos1 )


throw BitmapXptn( "part", BitmapXptn::paramErr, pos1, pos2 );
if ( pos1 < 0 || pos2 < 0 || lastb < pos1 || lastb < pos2 )
throw BitmapXptn( "part", BitmapXptn::outOfRange, pos1, pos2 );
// 0 <= pos1 <= pos2 <= lastb
b <<= (lastb - pos2);
b >>= (lastb - pos2 + pos1);
b <<= pos1;
return b;
} // part


si unsigned short int
display( cout, si ); cout << endl;
setBit( si, 12);
unsigned short int sip( part(si, 4, 9) );
display( cout, sip ); cout << endl;
:
0000011010111000
0000001010110000

: pos2 < pos1 -


. -
T(0). .

17.7 bitmask
| . 8, .
/
. 8.12 -
( 6 )
:
struct OpenFlags
558 17

{
bool app;
bool ate;
bool binary;
bool in;
bool out;
bool trunc;
}; // OpenFlags
6
:
struct OpenFlagsBF
{
bool app: 1;
bool ate: 1;
bool binary: 1;
bool in: 1;
bool out: 1;
bool trunc: 1;
}; // OpenFlagsBF
OpenFlagsBF .

. 0 1
bool. , OpenFlagsBF -
unsigned char ( 6 ). ,
0 app,
1 ate, , 5 trunc.
:
const unsigned char appPos = 0, atePos = 1, binaryPos = 2,
inPos = 3, outPos = 4, truncPos = 5;
, in, out binary
:
unsigned char om;
:
om = 0;
setBit( om, inPos ); setBit( om, outPos );
setBit( om, binaryPos );
, , binaryPos 1
bitValue(om, binaryPos) == 1.
setBit; ! , ,
:
const unsigned char app = 1, ate = (app << 1),
binary = (app << 2), in = (app << 3),
out = (app << 4), trunc = (app << 5);

1.8 om
:
om = in | out | binary;
1
:
om = in + out + binary;

8 :
const unsigned char app = 1, ate = (1 << 1), binary = (1 << 2),
in = (1 << 3), out = (1 << 4), trunc = (1 << 5);
* 559

!
setBit:
om = 0;
om |= in; om |= out; om |= binary;
1. ,
, binaryPos 1 (om & binary) !=
0.
bitmask.
bitmask :
N+1 c0 = 1, c1 = (1 << 1), , cN(1 << N).
v1, v2 v1 & v2, v1 | v2, v1 ^ v2, ~v1 .
&, |, ^, ~
&=, |=, ^=.
.
1. ,
N+1 . ,
. N = 5
. :
typedef unsigned char OpenMode;
const OpenMode app = 1, ate = (1 << 1), binary = (1 << 2),
in = (1 << 3), out = (1 << 4), trunc = (1 << 5);
.
2. .
:
enum OpenMode
{ app = 1, ate = (1 << 1), binary = (1 << 2), in = (1 << 3),
out = (1 << 4), trunc = (1 << 5) };
17.4
: OpenMode (
) -
.
(warnings)
,
. &
&=:
OpenMode operator&( OpenMode x, OpenMode y )
{
return static_cast<OpenMode>( static_cast<unsigned char>(x) &
static_cast<unsigned char>(y) );
} // operator&( OpenMode

OpenMode& operator&=( OpenMode& x , OpenMode y )


{
x = x & y;
return x;
} // operator&=( OpenMode
, -
, .
3. bitset STL.
.
bitmask C++
( C).
560 17

17.8
8.6 ios_base::in|ios_base::out
: ios_base::in+ios_base::out.
, -
bitmask. ,
,

.
,
:
+; ;
:
.
.
(CERT 2009):9
.

17.9 float
int Z , float,
R , :
float.
float .
, x :
n n-1 ... 0.-1 -2...
:
x = (n10n + n-110n-1 ... + 0100 + -110-1 + -210-2...)
: ( + - ) k: .
, -
. .
(loss of significant digits). ,
,
.
. float,
, :
10e (1)
(mantissa) (exponent) e.
:
0.1 2345
k, k = 1..5 ( -
). :
1 2
(1) 1
. -
(normalized). , :
1 2345:1 2

9 INT14: Avoid performing bitwise and arithmetic operations on the same data.
* 561

(floating
point).
= 3.1415926535..., :
+31416:+01
( f = +31416:+01 f = 3.1416).
:
+99999:+99 ( = 0.999991099 )
:
+10000:-99 ( = 0.110-99 )
float
1 1:
= min{u|(1u) f 1 f }
u0
, 1 :
+10000:+01
,
, 1:
+10001:+01 ( = 0.10001101 = 1.0001 )
: = 0.0001 .
! x float (x + )f f.
: (10 + )f = 10f (. 14-1). -
: ' 1+ = 1.0001
5 .
,
, .
float
:
float R (: float Q ())
, -
R float.
.
, .
, , -
: 0 () 1 ()!
0 :
+00000:+00
1 :
+10000:+01 ( = 0.1101 = 1 )
0f == 0 1f == 1
f float.
float f, -
float -f:
(-)f == -f
, 3.1415926535..., :
+31416:+01
3.14156 3.1416 . :
1, 2 float,
[1, 2].
562 17

:
> f f
== f == f
< f f
.
: -
. :
+60000:+99 ( = 0.600001099 )

+70000:+99 ( = 0.700001099 )
. , 1.3000010 99
= 0.1300010100 !
' (overflow). -
; -
.
' , -
, . :
float +, -, * / .
, float
int, -
. addFloat,
float; ,
,
.
:
+11000:-99 ( = 0.1110-99 )
:
+10000:-99 ( = 0.110-99 )
0.0110-99 = 0.110-100 ,
! (underflow). ,
0 ()
. , !
. -
14.563 0.16773. -
:
+14563:+02 ( = 0.14563102 = 14.563 )

+16773:+00 ( = 0.16773100 = 0.16773 )



.
( ) 10:

10 , ,
-
. , :
+0016773:+02
:
+1473073:+02
, :
+14731:+02
* 563

+00168:+02
:
+14731:+02
, (roundoff er-
rors). , 14.563 0.0001, -
14.563!
,
int, -
float. :
+f -f *f /f
:
+ - /
.

. :
1 == 2, 1, 2 , :
( )

.

float:
a, b float a +f b = b +f a a *f b = b *f a
.
!

a = 0.100001094, b = 0.550001099, c = -0.500001099
. :
( a +f b ) +f c = (0.000001 +f 0.55000)1099 +f (-0.500001099)
= 0.550001099 +f (-0.500001099)
= 0.500001098
:
a +f ( b +f c ) = 0.100001094 +f (0.550001099 +f 0.500001099)
= 0.100001094 +f 0.050001099
= 0.500011098

' , : a, b float a b 0, :
( a -f b ) +f b == a
: .
: -
: a = 0.100001060, b = 0.100001060, c = 0.1000010-60 :
( a *f b ) *f c = (0.100001060 *f 0.100001060) *f 0.1000010-60
= 0.1000010119 *f 0.1000010-60 (!!)
:
a *f ( b *f c ) = 0.100001060 *f (0.100001060 *f 0.1000010-60)
= 0.100001060 *f 0.1000010-1
= 0.100001058
564 17

-
float, . -
.

17.9.1
.
7.8 -
:
x0 = x;
while ( x0 >= b ) x0 = x0 - T;
// (x0 < b) && (f(x0) == f(x))
while ( x0 < a ) x0 = x0 + T;
// (a x0 < b) && (f(x0) == f(x))
x
T; x0 = x0 - T ( x0 = x0 + T)
x0 while . :
x0 = x;
if (x0 >= b)
{
if (x0 - T == x0)
{
throw " f ";
}
else
{
while (x0 >= b) x0 = x0 - T;
// (x0 < b) && (f(x0) == f(x))
}
}
else if (x0 < a)
{
if (x0 + T == x0)
{
throw " f ";
}
else
{
while (x0 < a) x0 = x0 + T;
// (a x0 < b) && (f(x0) == f(x))
}
}
: . ,
: :
x0 = x - T*floor((x-a)/T);
// (a x0 < b) && (f(x0) == f(x))
, x - a T
x0 , 0. ,
1 (x - a)/T.

17.10
float C++

.
* 565

float, C++ double.


() '
float.
:
float.

.
, 12.34567891234 :
12.345678912 = 12.345 + 0.00067891
= 0.1234510 + 0.6789110-3
2

:
+12345:+02 +67891:-03
: -
( ) . , -
float ( ).
:
+12345:+02 6789123
, , -
.

float. :
+1234:+002 5678912
, " float":
' -
float.
' float,
.
' float.
, float .

17.11 float

float.
(binary) (octal) (hexa-
decimal). .
float :
M 2e
e , .
:
s 1 2... L
s k, k = 1..L L .
:
s 0.1 2 ...N
s 1 2 ...N.0
, 1 .
1 = 1.
566 17

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





. 17-5 .

. 17-5.
31 0 +, 1 -.
30 - 23 : 30 ( )
29 - 23 . 22 - 0 .
(22) 1, 0 ().
(22). :
29 28... 23 , 30 0
e
29 28... 23 , 30 1
0. 22 21... 0 , s310
M
0. 22 21... 0 , s311
() , -127 +127.
0.12 = 0.510.
(22 - 0) 1:
2-1 + 2-2 + ... + 2-23 = 1 2-23 0.99999988 1
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
01111111110000000000000000000000
, - (0.12 = 0.510)
(-127). 2-128 0.29387e-38 .
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00111111111111111111111111111111
: ( 1) (+127). : 2 127
0.17014e+39.
1 :
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00000000110000000000000000000000
: 0.1221.
1
0.
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00000000110000000000000000000001
1 2-2321 0.23842e-06 . .

17.11.1
- :

( 0: +0, -0).
: ,
, 127.
.
(biased) 127.
* 567

float -
. (
) 0 255
-127 128. 256 255
.
, -
127. :
M2e
e :
e = 3029...23 - 1111111 (1111111 2 = 12710).
' ,
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00000000010000000000000000000000
: 0 0 - 127 = -127 -
(0.12 = 0.510).
: 2-128 0.29387e-38 .
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
01111111111111111111111111111111
: 255 255 - 127 = 128 ( 1).
: 2128 0.34028e+39, .
1 :
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
01000000010000000000000000000000
: 0.122128-127.
.

17.11.2 - IEEE
:
1, -
. , , 1,
: 0. .
IEEE
,
.
32 (31 - 0), 31
30 - 23 , 127.
: 22
.1. , :
0.1 22 21... 0 , s31 0
M=
0.1 22 21... 0 , s31 1
e = 3029...23 - 1111111 (1111111 2 = 12710).
32 0. ,
: 12-127 = 5.87710-39.
, (IEEE)
0. - (denormalized subnormal)
( ) .
568 17

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





. 17-6 double.

() , ,
1 (23) 0:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00000000100000000000000000000000
: 121-127 = 2-126 0.11755e-37.
,
(23), 1 1:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
01111111011111111111111111111111
: 22254-127 = 2128 0.34028e+39.
1 :
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00111111100000000000000000000000
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0
00111111100000000000000000000001
2-23 1.1921e-07. 24
, 7 .
(INF) : 1
0.
1
0, (Not a Number, NaN).

17.11.3 double long double


double C++ float (17.10).
IEEE.
, double -
' float.
float 32 , double 64
, 0 63 (. 17-6).
11 (62 - 52) 1023,
52 (51 - 0).
() , ,
(52) 1 0:
: 121-1023 = 2-1022 0.22251e-307. -
, 5.0e-324.
,
(52), 1 1:
: 222046-1023 = 21024 0.17977e+309
2-52 2.220446049250e-16. 53
16 .
* 569

C++ long double, 10 -


, . 80 , 15 64 . 20
() 1.9e-4951 1.1e4932.
, float, double, long double C++
.

17.11.4 C
C () -
. cmath.
int fpclassify( x );
:
= "float" | "double" | "long double" ;
fpclassify()
FP_INFINITE, FP_NAN, FP_NORMAL, FP_SUBNORMAL, FP_ZERO ( #define)
cmath.
:
int isinf( x );
int isnan( x );
int isnormal( x );
int isfinite( x );
:

bool isinf( x );
bool isnan( x );
bool isnormal( x );
bool isfinite( x );
, if ( isnan(sqrt(x) )
isnormal() 1 (true) x (
0, -, , NaN).
isfinite() 1 (true) x NaN.
(!) HUGE_VALF,
HUGE_VAL, HUGE_VALL float, double, long double .11
:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
float x( 0 );
double dn( 1e-100 ), dx( 1e100 );

if ( fpclassify(x) == FP_ZERO )
cout << "x is ZERO" << endl;
cout << dn << " " << isinf(dn) << " " << isnan(dn)
<< " " << isnormal(dn) << " " << isfinite(dn) << endl;
cout << dx << " " << isinf(dx) << " " << isnan(dx)
<< " " << isnormal(dx) << " " << isfinite(dx) << endl;
x = dn;
cout << x << " " << isinf(x) << " " << isnan(x)
<< " " << isnormal(x) << " " << isfinite(x) << endl;

11 C99 ( ) , INFINITY,
.
570 17

x = dx;
cout << x << " " << isinf(x) << " " << isnan(x)
<< " " << isnormal(x) << " " << isfinite(x) << endl;
if ( x == HUGE_VALF )
cout << "It IS HUGE!!!" << endl;
cout << 1/INFINITY << endl;
}
:
x is ZERO
1e-100 0 0 1 1
1e+100 0 0 1 1
0 0 0 0 1
1.#INF 1 0 0 0
It IS HUGE!!!
0

17.12
:
int main()
{
long i1, i2;
float r1, r2;

i1 = 123456787;
i2 = 123456786;
r1 = i1; r2 = i2;
if ( r1 == r2) cout << ", !!!" << endl;
}
Borland C++ long
float 32 , . ,
IEEE. ;
:
, !!!
: i1 i2
,
(4.3). r1 = i1 : i1
r1 . ,
4.3, 7 . ,
.
r2 = i2. if (r1 == r2) cout <<...
r1 r2,
!
:
.

17.13
float
,
.
-
.
* 571

17.13.1
b,
. b 2, 8, 10, 16.
x :
xf = M be
:
M = (-1b-1 + -2b-2 ... -Nb-N)
0 k b - 1, k = 1 .. N
EE e EM
.
(rounding)
(truncation, choping). .
: (-1) b/2 N
. () , |xf - x|, :
|xf - x| (b/2) b-(N+1) be = 0.5 be-N
(relative
error) :
x f x be N be N b N
0.5 0.5 0.5
x x (0. 1 2 )b e
0. 1 2
, 0.12...b 0.100...b (= b-1) :
x f x
(xf) = 0.5b-N+1
x

. : b = 10, = 5, , x:
(xf) 0.510-4 (xf) 0.00005
14.7: b = 2, = 23, :
(xf) 0.52-23
, 0.52-23 = 2-24 10-7.22 0.610-7 :
(xf) 0.00000006
: -.
- .
:
|xf - x| < 1be-N
, -
:
xf x
(xf) = < b-N+1
x

17.13.2
x, y xf, yf
. :
x = xf + x y = yf + y
+, -, , / f
, : +f, -f, *f, /f. :
572 17

(x y) - (xf f yf) = (x y) - (xf f yf) +( xf yf) - (xf yf)


= (xf yf - xf f yf) + (x y - xf yf)
.
f. 17.8
14.563 (= xf) 0.16773 (= yf).
:
(xf + yf) - (xf +f yf) = (14.563 + 0.16773) - (14.563 +f 0.16773)
= 14.73073 - 14.731
= -0.0008
, 14.8,
( )
, :
(xf f yf) = (xf yf)f
, ,
, :
xf yf - xf f yf 0.5 xf yf b1-N
:
(x y - xf yf)
,
()
. (propagated error).
.
:
xy - xf yf = xy - (x - x)(y - y)
= xy + yx - xy

(xf yf) (xf) + (yf) + (xf)(yf)


(xf)(yf) << 1 :
(xfyf) (xf) + (yf)
:
x f x / y x R / y R y R / y x R / x
= =
yf x/ y yR / y

x / x y / y ( x f )( y f )
=
1 y / y 1( y f )
, (xf)(yf) << 1 :
(xf yf) (xf) + (yf)
,
. , , .
.
- : + -,
( ) :
x y - xf yf = x y - (x - x) (y - y)
= x y
|x + |y|
, : 0.123445
0.123454
* 573

. : 0.12345 ( -0.000005) : 0.12345 (-


0.000004) : 0. 0.000009
100%! :
-
. , 5 ,
: 5 . ,
5 , .
5 .
; -
; -
. ( )
. ( ) .
, , ,
.

17.14
: :
float A, B;
:
if ( A == B ) ...
,
, .
:
|A - | A |B - | B

- A A + A - B B + B
:
( - ) - (A + B) A - B ( - ) + (A + B)
, . =
:
- (A + B) A - B (A + B)
, :
if ( fabs(A - B) <= eps ) ...
eps, ' ,
, -
.
A B.
, eps float :

A = min{ u: R u > 0 (A+u)R AR u }
A :
/b < A
b
float. b = 2, /2 < A ||.
: 0 x < A = A + x A == B
, -
, . ,
A,
574 17

float, -
A. eps
A , , eps .
; ! -
, (iterative) : -
[a, b] -
,
a==b. , :
while ( fabs(b-a) > eps )...
, , eps , , . -
a b , . : . ( -
) b a+A. a b (-
[a,b]) , fabs(b-a) = A > eps.


14.3 , , ,
.
#include <iostream>
#include <cmath>

using namespace std;

double q( double x );
void bisection( double (*f)(double),
double a, double b, double epsilon,
double& root, int& errCode );

int main()
{
double riza;
int errCode;

bisection( q, 0.1, 1.0, 1e-20, riza, errCode );


if ( errCode != 0 ) cout << "o " << endl;
else cout << " = " << riza << endl;
} // main
bisection , 14.3
epsilon = 1e-5 0.1585983 epsilon =
1e-20. double, C++ , 14.7.3,
= 2-23 2.220446049250e-16.
, , .
:
# a b |b-a|/2 m
: : : : :
54 0.15859434 0.15859434 5.55111512312578270e-17 0.15859434
55 0.15859434 0.15859434 2.77555756156289135e-17 0.15859434
56 0.15859434 0.15859434 1.38777878078144568e-17 0.15859434
57 0.15859434 0.15859434 1.38777878078144568e-17 0.15859434
58 0.15859434 0.15859434 1.38777878078144568e-17 0.15859434
59 0.15859434 0.15859434 1.38777878078144568e-17 0.15859434
: : : : :
, m = (a+b)/2 fabs(b-a)/2 -
epsilon. epsilon,
(double) . ,
|a| = 0.158594342.220446049250e-16 3.521501756864e-17
* 575

A [1.76e-17, 3.52e-17]. epsilon A.12


; ; :

trEps = max(|m|/b, epsilon)
while fabs(b-a)/2 >= trEps.
float -
. , m
= m b - a/2. b - a/2 m,
. C++; :
m == m + fabs(b-a)/2
, :
-
, :
void bisection( double (*f)(double),
double a, double b, double epsilon,
int nMax,
double& root, int& errCode )
{
double m, d;

if ( f(a)*f(b) > 0 )
errCode = 3;
else
{
int n( 0 );
do {
++n;
m = (a + b) / 2;
if ( f(a)*f(m) <= 0.0 ) b = m;
else a = m;
d = fabs(b - a)/2;
} while ( (d >= epsilon) && (m != m + d) && (n != nMax) );
root = m;
if (d <= epsilon) errCode = 0;
else if (m == (m + d)) errCode = 1;
else if (n == nMax) errCode = 2;
} // if
} // bisection
, ,

. errCode:
errCode == 1 : .
errCode == 2 : nMax
.
errCode == 3 : .
:
bisection( q, 0.1, 1.0, 1e-20, 1000000, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
bisection( q, 0.1, 1.0, 1e-10, 5, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
bisection( q, 0.1, 1.0, 1e-10, 50, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
:

12 , a, b .
576 17

1
= 0.158594
2
= 0.184375
0
= 0.158594
, : n n < nMax
n != nMax ; nMax 0
.

0 m
: 0 .... :
if ( fabs(A) <= eps ) ...

if ( x + A = x ) ...
, 0 x. , x
.

17.15
-
, :
.
. , !

!
, , ; -
. ! ,
, :
.
! -
!
; , ;
. float 32 .
1
: ax2 + bx + c = 0 a = 1.0, b = 1000000000.0 = 109, c = 4.0
:
b b 2 4ac
x
2a
float 14.6.2. ' -
b2 = 1018, 4ac = 16. 1018
x+ = -1000000000.0 x- = 0. .
, b 2 4ac b -b + b () ,
.

. : x+x- = c/a, -
: x- = c/(ax+).
* 577

x+(x1) x- (x2)
. x3 .
int main()
{
float a, b, c, x1, x2, x3;

a = 1.0f; b = 1000000000.0f; c = 4.0f;


x1 = (-b - sqrt(b*b - 4*a*c))/(2*a);
x2 = (-b + sqrt(b*b - 4*a*c))/(2*a);
x3 = c/(a*x1);
cout << x1 << " " << x2 << " " << x3 << endl;
}
:
-1e+009 0 -4e-009



3 . 2 5.5.
double float.

2
1 - t t. -
0 (). :
1 t 2t
1 t = (1 t ) =
1 t 1 t
:
t = 0.0000000001;
x1 = 1 - cos(t);
cout << x1 << endl;
x2 = sin(t)*sin(t)/(1+cos(t));
cout << x2 << endl;
:
0
5e-021
, 1+t 1-t.

.
, , -
,
. , -
, .
:
3

0. , :
z = x/y;
:
if ( y != 0 ) z = x/y;
else ...
, .
:
578 17

if ( fabs(y) > eps ) ...


, y float,
0 . -
. , y
, .
, , z
.

4
. x
y :
z = x + y;
.
. C++ float FLT_MAX
float13. ,
, -
addFloat, addInt int.

,
. , ! ' .
, , .
,
.
:
.
,
, : -
. .

.


17-1 ( count1) xCount1
x, k1 k2
1 k1 k2 x.
17-2 ( ) , rShiftRight, ,
, x, unsigned char, -
p x p
( p ,
, ), . -
x p = 3 :

13 DBL_MAX, LDBL_MAX double long double


.
* 579

7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
01110010 01001110
x
-
.
rShiftLeft, .


17-3 ( ) , shiftLeft, ,
, a, unsigned
char, n p
p ,
. (n = 3):
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
011100101001111001101101
a[2] a[1] a[0]
p = 4. :
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
001010011110011011010111
a[2] a[1] a[0]
-
.
shiftRight, .
17-4 bitValue(), setBit(), clearBit(), count1() part()
T. T sT p
0 nsT - 1, n
.
17-5 17.3 ,
: (subtrInt), (multInt),
(divInt) int.
17-6 float.


17-7 x float, :
x = min{ u: R u > 0 (x+u)f xf u }
x ; x = x;
[ : x / < x x ]
580 17

18

:
()
( )
,
.
:

.
:
define
ifdef



namespace
:
18.1 define, ifdef ......................................................................................................... 582
18.2 ............................................................................................ 586
18.3 ................................................................................................................................... 588
18.4 ................................................................................................................................... 592
18.5 namespace: ................................................................................................... 593
18.6 ............................................................................................................................................... 596
................................................................................................................................................................... 597
.............................................................................................................................................................................597
.............................................................................................................................................................................597

:
, -
(
).
FORTRAN.

!
. -
:
, , -

581
582 18

-
.
,
(linker), (static) (dynamic linking):
: ()

,
.
: DLL (Dynamic Link Library) Win-
dows DSO (Dynamic Shared Object) Unix, Linux.

.
:
,
. , ,
. -
. () -
.

.
(-
), .


.
-
: define undef
ifdef ifndef.
! , ,

. Dev-C++, Win-
dows. , , ( Help) C++
.

18.1 define, ifdef


1.5 include -
.

.
define () :
"#", "define", ,
(macro). -
(macro identifier), -
(macro body).
, ,
. -
(macro expansion).
define undef(ine):
583

"#", "undef",
.
undef (undefined),
define. define (defined).

:
#define NMAX 50
NMAX 50
#undef NMAX.
:
#define NMAX 50

int main()
{
int a[NMAX];
:
for (int k(0); k <= NMAX-1; ++k)
{
#undef NMAX
swap(a[k], a[NMAX-k]);
} // for
:
NMAX 50
for swap(a[k], a[NMAX-k]) -
#undef NMAX.,
Undefined symbol NMAX .
NMAX
#define NMAX 50 #undef NMAX
.

stdlib.h:
#define max(a,b) (((a) > (b)) ? (a) : (b))
:
y = x + max(x+1, y-1);
:
y = x + (((x+1) > (y-1)) ? (x+1) : (y-1));

:
,
(.. #define A A
)
, undef. , -
,
#define NMAX 50

#undef NMAX
#undef 50.
584 18

; ,
.
14.1 inline. ,
define
. C++
const
inline

.
define -
.
-
. .. :
#define NMAX
int main()
{
int a[NMAX];

for (int k(0); k <= NMAX-1; ++k)


{
swap(a[k], a[NMAX-k]);
}
:
#define NMAX
int main()
{
int a[];

for (int k(0); k <= -1; ++k)


{
swap(a[k], a[-k]);
}
define -
, .
, ( )

.
, , N
f
int f( int x )
{ ++x; return x; }
, N, f
int f( int x )
{ return x; }
:1
#ifdef N

int f( int x )
{ ++x; return x; }

#endif

1 #else
...
585

#ifndef N

int f( int x )
{ return x; }

#endif
#ifdef N C++ : #if
N.
#if N :
#ifndef N.
#endif if (#ifdef N
#ifndef N ).

iostream (gcc Dev-C++):
#ifndef _GLIBCXX_IOSTREAM
#define _GLIBCXX_IOSTREAM 1

// . . .

#endif /* _GLIBCXX_IOSTREAM */
. -
, myFuncs.h, . :
#include <iostream>
myprog.cpp, , :
#include <iostream>
#include "myFuncs.h"
; iostream

.
iostream , , :
#include <iostream> myprog.cpp _GLIBCXX_IO-
STREAM . ,
#ifndef _GLIBCXX_IOSTREAM
iostream.

#define _GLIBCXX_IOSTREAM 1
_GLIBCXX_IOSTREAM .2
, myFuncs.h,
#include <iostream>
, iostream. , -

#ifndef _GLIBCXX_IOSTREAM
_GLIBCXX_IOSTREAM

#endif /* _GLIBCXX_IOSTREAM */
-
. , myFuncs.h -
:
#ifndef _MYFUNCS_H
#define _MYFUNCS_H

2 1 define , .
586 18

// . . .

#endif /* _MYFUNCS_H */

18.2
. -
MyTmpltLib -
:
linSearch(), 16.13.1,
C++ find().
renew(), (16.12), -
(containers) C++.
new2d() delete2d() 16.9.
, MyTmpltLib.h,
MyTmpltLibXptn (16.9):
#ifndef _MYTMPLLIB_H
#define _MYTMPLLIB_H

#include <string>
#include <new>

using namespace std;

struct MyTmpltLibXptn
// 16.9

template< typename T >


int linSearch( const T v[], int n,
int from, int upto, const T& x )
// 16.13.1

template< typename T >


void renew( T*& p, int ni, int nf )
// 16.12

template< typename T >


T** new2d( int nR, int nC )
// 16.9

template< typename T >


void delete2d( T**& a, int nR )
// 16.9

#endif // _MYTMPLLIB_H
#ifndef _MYTMPLLIB_H #endif.
#define _MYTMPLLIB_H. #include
"MyTmpltLib.h".
:
#include <string> strncpy().
#include <new> bad_alloc.
using namespace std std::strncpy,
std::bad_alloc.
. 16.12 :
#include <iostream>
587

#include <new>
#include "MyTmpltLib.h"

using namespace std;

int main()
{
int* ip;
double* dp;
// . . .
renew( ip, 3, 7 ); renew( dp, 3, 7 );
// . . .
} // main
: #include "MyTmpltLib.h" renew().
MyTmpltLib.h renew
: int ( renew(ip, 3, 7)) double (
renew(dp, 3, 7)).
. 2 16.13 :
#include <iostream>
#include <fstream>
#include <string>
#include <new>
#include "MyTmpltLib.h"

using namespace std;

struct ApplicXptn
// . . .
#include "MyTmpltLib.h"
MyTmpltLibXptn renew() linSearch(). renew()
GrElmn linSearch() .
(16.9) :
#include <iostream>
#include <fstream>
#include "MyTmpltLib.h"

using namespace std;

void input2DAr( istream& tin, int** a, int nRow, int nCol );


void output2DAr( ostream& tout, int** a, int nRow, int nCol );

int main()
// . . .
#include "MyTmpltLib.h"
MyTmpltLibXptn new2d delete2d.
int.
: ; ;
, -

.
, . , -
:
, C++. -
, , .
; .
588 18

18.3

:
Horner (9.4, . 1) (bisection, 17.14).
:
MyNumerics.cpp. MyNumerics.h :
#ifndef _MYNUMERICS_H
#define _MYNUMERICS_H

#include <string>

using namespace std;

struct MyNumericsXptn
{
enum { domainError, noArray };

char funcName[100];
int errCode;
double errDblVal;
MyNumericsXptn( const char* fn, int ec, double ev = 0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errDblVal = ev; }
}; // MyNumericsXptn

// ph -- , m,
// Horner.
double ph( const double a[], int m, double x );

// bisection -- (root) f(x) = 0


// [,]
// nMax .
// [a,b] f
// f(a)*f(b) <= 0
void bisection( double (*f)(double),
double a, double b, double epsilon,
int nMax,
double& root, int& errCode );

#endif // _MYNUMERICS_H
MyNumerics.cpp :
#include <string>
#include <cmath>
#include "MyNumerics.h"

using namespace std;

double ph( const double a[], int m, double x )


{
if ( a == 0 )
throw MyNumericsXptn( "ph", MyNumericsXptn::noArray );
if ( m < 0 )
throw MyNumericsXptn( "ph",
MyNumericsXptn::domainError, m );
//

void bisection( double (*f)(double),


double a, double b, double epsilon,
int nMax,
double& root, int& errCode )
{
if ( epsilon < 0 )
throw MyNumericsXptn( "bisection",
589

. 18-1 New Project -


Dev C++.
MyNumericsXptn::domainError, epsilon );
//
:
1. , . -
, -
, -
.
2. bisection() epsilon < 0. -
.
MyNumerics1.
Dev-C++ :
File|New|Project
. 18-1. Name:
MyNumerics1 project Console Application. Ok
. MyNumerics1.
MyNumerics1, MyNumerics1.dev.
project.
( Project )
project MyNumerics1, main.cpp
:
#include <cstdlib>
#include <iostream>

using namespace std;

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


{
system("PAUSE");
return EXIT_SUCCESS;
}
, Project|Add to Project project
MyNumerics.cpp. .
, Execute|Rebuild all MyNumerics1
:
main.o
Makefile.win
MyNumerics.o
MyNumerics1.exe
590 18

. 18-2 Project Options -


Dev C++.

MyNumerics.o MyNumerics.cpp.3
.
17.14 :
#include <iostream>
#include <cmath>
#include "MyNumerics.h"

using namespace std;

double q( double x );

int main()
{
double riza;
int errCode;

bisection( q, 0.1, 1.0, 1e-20, 1000000, riza, errCode );


cout << " " << errCode << endl
<< " = " << riza << endl;
bisection( q, 0.1, 1.0, 1e-10, 5, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
bisection( q, 0.1, 1.0, 1e-10, 50, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
}

double q( double x )
{
return ( x - log(x) - 2 );
} // q
testBisection.cpp testBisection.
, bisection()
MyNumerics.h. .
testBisection MyNumerics.h MyNumerics.o.
:
project Console Application, testBisection
testBisection.

3 , MyNumerics.obj.
591

project testBisection.cpp.
, , main.cpp. -
project testBisection.cpp.
Project|Project options
Parameters.
(. 18-2) Add Library or Object
MyNumerics.o. , -
.
, Execute|Rebuild all.
testBisection :
testBisection.exe
testBisection.o
testBisection.exe . testBisection.o -
testBisection.cpp.
:
. -
-
: MyNumerics.h MyNumerics.o.
:
1. testBisection ) project, )
) cpp main.
.
project.
2. ph MyNumerics.cpp
MyNumerics.o, . -
.
3. (Add to project) MyNumerics.cpp project test-
Bisection ,
testBisection.o MyNumerics.o. ,
main bisection(). -
.
4. :
#include <iostream>
#include <cmath>

using namespace std;

extern "C++"
{
struct MyNumericsXptn;
void bisection( double (*f)(double),
double a, double b, double epsilon,
int nMax,
double& root, int& errCode );
}

double q( double x );

int main()
//
, #include "MyNumerics.h" extern
, ,
MyNumericsXptn bisection -
.
592 18

C
extern "C".
. ,
extern, .. extern "Ada", extern "FORTRAN" .
5. Makefile.win.
.
6. Dev C++
Code::Blocks. Borland C++ v.5.5 ()
cmd.exe :
C:\Borland\bc55\bin>bcc32 main.cpp MyNumerics.cpp
main.cpp . , MyNumerics.obj.
:
C:\Borland\bc55\bin>bcc32 testBisection.cpp MyNumerics.obj
testBisection.exe.

18.4
ph()
bisection().
MyNumerics MyNumerics.cpp MyNumer-
ics.h project
MyNumerics : Static Library.
(Add to project) MyNumerics.cpp Execute|Rebuild all.
MyNumerics, MyNumerics.dev MyNumerics.o, MyNumerics.a.
4 -
.
testBisectionL
testBisection.cpp
MyNumerics.a
MyNumerics.h
:
project Console Application testBisectionL
testBisection.cpp ( main.cpp).
Project|Project options
Parameters. (. 18-2),
Add Library or Object, MyNumerics.a.
, Execute|Rebuild all
testBisectionL.exe,
-
ph(), bisection().
, , ,
MyNumerics.a MyNumerics.h.

4 (.. Borland C++)


.lib.
593

18.5 namespace:
, -

Internet. , -
: renew()
ph(). ; , .
. -
. , ...
C++ : (namespace).
. :
namespace test
{
const double x = 1.5;
}
char x = 'A';
int main()
{
int x = 4;
:
cout << x << " " << ::x << " " << test::x << endl;
:
, test, double
x 1.5.
x char 'A'.
int, main, x 4.
main ,
:
4 A 1.5
, x ::x
. test::x : x
test. , :: -
(scope resolution)
.
. -
.. C : , ,
bib.h :
namespace xbib
{
#include "bib.h"
}
bib.h
xbib:: .
, namespace -
: ,
' -
. ' .
, prlib.h -
prlib. :
#include "prlib.h"
using namespace prlib;
prlib
prlib::.
594 18

using namespace ,
using .
f1() cl1 prlib
f2() fl0() prlib. :
double f1(...)
{
using prlib::cl1;
cl1 a, b;
:
} // f1

void f2(...)
{
using prlib::fl0;
:
q = fl0(1, u) + w;
} // f2
using prlib::cl1 -
cl1 f1() . , using prlib::
fl0 fl0
f2() . using .
using namespace std
. C++ std
(standard). . -
std::strncpy, std::cout, std::endl, std::cin, std::bad_alloc, .
. MyTmpltLib.h
:
namespace MyTmplt
{
struct MyTmpltLibXptn
// . . .
template< typename T >
int linSearch( const T v[], int n,
int from, int upto, const T& x )
// . . .
template< typename T >
void renew( T*& p, int ni, int nf )
// . . .
template< typename T >
T** new2d( int nR, int nC )
// . . .
template< typename T >
void delete2d( T**& a, int nR )
// . . .
} // namespace MyTmplt
, : MyTmpltLibXptn, linSearch, renew, new2d delete2d -
MyTmplt.
:
() .
MyTmpltLibXptn
MyTmplt. , . 2 16.13 -
, ,
MyTmplt::MyTmpltLibXptn::domainError
// . . .
catch( MyTmplt::MyTmpltLibXptn& x )
{
switch ( x.errCode )
{
595

case MyTmplt::MyTmpltLibXptn::domainError:
cout << x.funcName << "called with parameters "
<< x.errVal1 << ", " << x.errVal2 << endl;
break;
case MyTmplt::MyTmpltLibXptn::noArray:
cout << x.funcName << "called with NULL pointer"
<< endl;
break;
case MyTmplt::MyTmpltLibXptn::allocFailed:
cout << "cannot get enough memory " << " in "
<< x.funcName << endl;
break;
default:
cout << "unexpected MyTmpltLibXptn from "
<< x.funcName << endl;
} // switch
} // catch( MyTmpltLibXptn
// . . .
, elmntInTable :
// . . .
int lPos( MyTmplt::linSearch( grElmnTbl, nElmn,
0, nElmn-1, oneElmn) );
if ( lPos < 0 )
{
if ( nElmn+1 == nReserved )
{
MyTmplt::renew( grElmnTbl, nElmn, nReserved+incr );
// . . .
. -
MyNumerics.h :
namespace MyNmr
{
struct MyNumericsXptn
// . . .
double ph( const double a[], int m, double x );
// . . .
void bisection( double (*f)(double),
double a, double b, double epsilon,
int nMax,
double& root, int& errCode );
} // namespace MyNmr
MyNumerics.cpp :
// . . .
double MyNmr::ph( const double a[], int m, double x )
{
if ( a == 0 )
throw MyNmr::MyNumericsXptn( "ph",
MyNmr::MyNumericsXptn::noArray );
// . . .
void MyNmr::bisection( double (*f)(double),
double a, double b, double epsilon,
int nMax,
double& root, int& errCode )
{
if ( epsilon < 0 )
throw MyNmr::MyNumericsXptn( "linSearch",
MyNmr::MyNumericsXptn::domainError, epsilon );
// . . .
MyNumerics.cpp
using namespace MyNmr;
596 18

MyNmr; !
ph() bisection() MyNmr
::ph() MyNmr::bisection().
testBisection.cpp :
MyNmr::bisection( q, 0.1, 1.0, 1e-20, 1000000, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
MyNmr::bisection( q, 0.1, 1.0, 1e-10, 5, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
MyNmr::bisection( q, 0.1, 1.0, 1e-10, 50, riza, errCode );
cout << " " << errCode << endl
<< " = " << riza << endl;
:
catch( MyNmr::MyNumericsXptn& x )
{
if ( x.errCode == MyNmr::MyNumericsXptn::domainError )
cout << x.funcName << " called with negative ( "
<< x.errDblVal << " ) epsilon" << endl;
else
cout << "unexpected MyNumericsXptn from "
<< x.funcName << endl;
}
.
, , MyTmplt MyNmr, -
, MyNmspc.
, :
.

using namespace .

18.6
. -
.
.

C++. ,
. -
.


.
-
: .
: , , -
()
.
:
.

-
/ .
597


(.h).


18-1 ph() bisection() R double. -
float long double. -

.
,
NumTmplt. .


18-2 . 15
struct GrElmn
{
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
}; // GrElmn

GrElmn GrElmn_copyFromElmn( const Elmn& a );
void GrElmn_save( const GrElmn& a, ostream& bout );
void GrElmn_load( GrElmn& a, istream& bin );
void GrElmn_setGrName( GrElmn& a, string newGrName );
void GrElmn_display( const GrElmn& a, ostream& tout );
void GrElmn_setGrName( GrElmn& a, string newGrName );
void GrElmn_writeToTable( const GrElmn& a, ostream& tout );
.
GrElmnLib (.a .lib) . -
15.14.1 15.14.2.
! ApplicXptn. :
GrElmnXptn. , !

18-3 . 15
struct Date
{
enum { saveSize = sizeof(int) + 2*sizeof(char) };
unsigned int year;
unsigned char month;
unsigned char day;
Date( int yp=1, int mp=1, int dp=1 )
{ year = yp; month = mp; day = dp; }
}; // Date

void Date_save( const Date& a, ostream& bout );
598 18

void Date_load( Date& a, istream& bin );



bool operator==( const Date& lhs, const Date& rhs );
bool operator<( const Date& lhs, const Date& rhs );
ostream& operator<<( ostream& tout, const Date& rhs );
DateLib (.a .lib)
. Date.
. 15-1 .
! .
() .



19. .......................................................................................................................... 601
project 3: ................................................................................................................ 633
20. - ................................................................................................ 655
21. ....................................................................................................................... 696
22. ................................................................................................................................. 739
project 4: ................................................................................................... 771
project 5: ....................................................................................................................... 825
23. ................................................................................................................................................... 841
project 6: .................................................................................... 885
24. - ................................................................................................................ 917
25. ................................................................................................................................ 951
26. - Standard Template Library (STL) ............................................... 989
project 7: STL ................................................................................................. 1039
project 8: ................................................................................................................ 1067

19

Habeas Corpus
:
.
.
:

.
:


(private)
(public)

:
19.1 ...................................................................................................................................................... 602
19.1.1 const .............................................................................................................................................................609
19.1.2 ....................................................................................................................................609
19.1.3 class public ..................................................................................................................................610
19.1.4 ......................................................................................................................................612
19.1.5 .....................................................................................................................................................613
19.2 ............................................................................................................................. 613
19.3 ................................................................................................................................. 613
19.3.1 .........................................................................................................................614
19.4 inline.................................................................................................................................. 615
19.5 - .................................................................................... 615
19.6 class struct; ........................................................................................................................... 617
19.7 struct GrElmn class GrElmn.................................................................... 619
19.8 ........................................................................................................................ 625
19.8.1 get, set ...........................................................................................................................................626
19.8.2 powerDevice() .....................................................................................................................................626
19.8.3 maxTime() ............................................................................................................................................627
19.8.4 reCharge ..............................................................................................................................................628
19.8.5 .........................................................................................................................................628
19.8.6 ....................................................................................................................................................629
19.9 ( ) ............................................................................................ 630
- ............................................................................................................................................. 631
.............................................................................................................................................................................631
.............................................................................................................................................................................631
.............................................................................................................................................................................632

601
602 19

:
Habeas Corpus.
( ).
.
-
( ) , ,
! Habeas Corpus
Cromwell 1679.
; ()
(-
-, client application). :
15.3 :
Date d1( 2004, 14, 37 );
.
Employee (birth-
Date) (emplDate) (num-
berOfChld) .
GrElmn (geA-
Number) (geAWeight).
C++, -
,
-
.

19.1
Date.1
Date,
:
(dYear > 0) (0 < dMonth 12) (0 < dDay lastDay(dYear, dMonth))
(class invariant) : -
() Date.
lastDay , ,
dMonth dYear. ; :
unsigned int lastDay( int y, int m )
{
unsigned int fv;

if ( m == 1 || m == 3 || m == 5 || m == 7 || m == 8 ||
m == 10 || m == 12 )
fv = 31;
else if ( m == 4 || m == 6 || m == 9 || m == 11 )
fv = 30;
else // m == 2
if ( isLeapYear(y) ) fv = 29;
else fv = 28;
return fv;
} // lastDay

1 : dYear, dMonth, dDay year, month, day.


.
603

isLeapYear(y) ;
bool isLeapYear( int y )
{
bool fv( false );

if ( y%400 == 0 ) fv = true;
else if ( y%4 == 0 && y%100 != 0 ) fv = true;
return fv;
} // isLeapYear
y true, ,
false. 2.
: -
; , ; ,
.
, Date
Date, .
Date.
:
struct Date
{
Date( int ay=1, int am=1, int ad=1 )
{ year = ay; month = am; day = ad; }
private:
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;
}; // Date
private:
Date -
. private .
, d1.dYear = -5; d1.dMonth = 29; :
. (private).
, (public),
Date.

:

.
, : -
. , : -
;
: :
Date( int ay=1, int am=1, int ad=1 )
{
if ( ay <= 0 )
throw . . .;
// ay > 0
dYear = ay;
if ( am <= 0 || 12 < am )
throw . . .;
// dYear > 0 && ( 0 < am && am <= 12 )
dMonth = am;

2 :
bool isLeapYear( int y )
{ return ( y%400 == 0 || (y%4 == 0 && y%100 != 0) ); } // isLeapYear
604 19

if ( ad <= 0 || lastDay(dYear, dMonth) < ad )


throw . . .;
// dYear > 0 && ( 0 < dMonth && dMonth <= 12 ) &&
// ( 0 < ad && ad <= lastDay(dYear, dMonth) )
dDay = ad;
// dYear > 0 && ( 0 < dMonth && dMonth <= 12 ) &&
// ( 0 < dDay && dDay <= lastDay(dYear, dMonth) )
} // Date
,
.
:
lastDay() .
, .
; -
, isLeapYear(), private :
struct Date
{
Date( int ay=1, int am=1, int ad=1 )
//
private:
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;

bool isLeapYear( int y )


//
unsigned int lastDay( int y, int m )
//
}; // Date
,
.

-; ! -
. :
struct DateXptn
{
enum { yearErr, monthErr, dayErr };
char funcName[100];
int errorCode;
int errVal1;
int errVal2;
int errVal3;
DateXptn( const char* mn, int ec,
int ev1=0, int ev2=0, int ev3=0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
errVal1 = ev1; errVal2 = ev2; errVal3 = ev3; }
}; // DateXptn
.
//
. C++ -
: -
. :
struct Date
{
Date( int ay=1, int am=1, int ad=1 );
private:
unsigned int dYear;
unsigned char dMonth;
605

unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
}; // Date

bool Date::isLeapYear( int y )
//
unsigned int Date::lastDay( int y, int m )
//
: isLeapYear() ( )
Date. lastDay().
//
:
Date::Date( int ay, int am, int ad )
{
if ( ay <= 0 )
throw DateXptn( "Date", DateXptn::yearErr, ay );
// ay > 0
dYear = ay;
if ( am <= 0 || 12 < am )
throw DateXptn( "Date", DateXptn::monthErr, am );
// dYear > 0 && ( 0 < am && am <= 12 )
dMonth = am;
if ( ad <= 0 || lastDay(dYear, dMonth) < ad )
throw DateXptn( "Date", DateXptn::dayErr,
dYear, dMonth, ad );
// dYear > 0 && ( 0 < dMonth && dMonth <= 12 ) &&
// ( 0 < ad && ad <= lastDay(dYear, dMonth) )
dDay = ad;
// dYear > 0 && ( 0 < dMonth && dMonth <= 12 ) &&
// ( 0 < dDay && dDay <= lastDay(dYear, dMonth) )
} // Date
:
-
,
.
Date::
. Date::Date -
Date dYear Date::dYear.

. ;
ad 31 -
dMonth 6.
ad 29
dMonth 2 dYear 2001.
: ;
-
- (member fumctions) (methods):
struct Date
{
Date( int ay=1, int am=1, int ad=1 );
unsigned int getYear() const { return dYear; }
unsigned int getMonth()
const { return static_cast<unsigned int>( dMonth ); }
unsigned int getDay() const { return static_cast<unsigned int>( dDay ); }
private:
606 19

unsigned int dYear;


unsigned char dMonth;
unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
}; // Date
getYear(), getMonth(), getDay() . ;
:
Date d1( 2010, 10, 13 );
cout << "d1: "
<< d1.getDay() << '.' << d1.getMonth() << '.' << d1.getYear() << endl;

d1 = Date( 2008, 7, 9 );
cout << "d1: "
<< d1.getDay() << '.' << d1.getMonth() << '.' << d1.getYear() << endl;
:
d1: 13.10.2010
d1: 9.7.2008
, d1
, . 15.3
Date(2008, 7, 9) Date.
d1.
:
d1.getDay(), d1.getMonth(), d1.getYear()

Date::getDay(d1), Date::getMonth(d1), Date::getYear(d1)
! :

.
(encapsulation)
.

. s.length() s.c_str() s (std::)string
bin.open() bin.read() bin (std::)ifstream.
->. :
Date* pd( new Date(2008, 7, 9) );

cout << "*pd: "


<< pd->getDay() << '.' << pd->getMonth() << '.'
<< pd->getYear() << endl;
:
*pd: 9.7.2008
( ) -
. , ,
; :
d1 = Date( d1.getYear(), 5, d1.getDay() );
5 .

. :
struct Date
{
Date( int ay=1, int am=1, int ad=1 );
607

unsigned int getYear() const { return dYear; }


unsigned int getMonth() const { return dMonth; }
unsigned int getDay() const { return dDay; }
void setYear( int ay );
void setMonth( int am );
void setDay( int ad );
private:
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
}; // Date
:
void Date::setYear( int ay )
{
if ( ay <= 0 )
throw DateXptn( "setYear", DateXptn::yearErr, ay );
if ( dDay <= 0 || lastDay(ay, dMonth) < dDay )
throw DateXptn( "setYear", DateXptn::dayErr,
ay, dMonth, dDay );
dYear = ay;
} // Date::setYear
, ; d -
29.02.2000 (d.setYear(2001))
2001.
void Date::setMonth( int am )
{
if ( am <= 0 || 12 < am )
throw DateXptn( "setMonth", DateXptn::monthErr, am );
if ( dDay <= 0 || lastDay(dYear, am) < dDay )
throw DateXptn( "setMonth", DateXptn::dayErr,
dYear, am, dDay );
dMonth = am;
} // Date::setMonth

d 31.12.2010 d.setMonth(6).
void Date::setDay( int ad )
{
if ( ad <= 0 || lastDay(dYear, dMonth) < ad )
throw DateXptn( "setDay", DateXptn::dayErr,
dYear, dMonth, ad );
dDay = ad;
} // Date::setDay
setDay .
:
set , Date,
.
:
( ). : d1 31.05.2007
30.04.2007
. 30.04.2007 31.05.2007
. : Date set.
.
Date d1( 2007, 5, 31 ); // d1 == 31.05.2007

d1 = Date( d1.getYear(), 4, 30 ); // d1 == 30.04.2007


d1 = Date( d1.getYear(), 5, 31 ); // d1 == 31.05.2007
d1 = Date( d1.getYear(), 12, d1.getDay() ); // d1 == 31.12.2007
608 19

d1 = Date( d1.getYear()+1,
d1.getMonth(), d1.getDay() ); // d1 == 31.12.2008
.

. 15-1 Date :
void Date_load( Date& a, istream& bin )
{
bin.read( reinterpret_cast<char*>(&a.year), sizeof(a.year) );
if ( !bin.eof() )
{
bin.read( reinterpret_cast<char*>(&a.month),
sizeof(a.month) );
bin.read( reinterpret_cast<char*>(&a.day), sizeof(a.day) );
if ( bin.fail() )
throw _Xptn( "Date_load", _Xptn::cannotRead );
}
}; // Date_load
Date;
:
ifstream dateFile( ..., ios_base::binary );
Date d;
:
Date_load( d, dateFile );
, load() :
d.load( dateFile );
:
struct Date
{
// . . .
void load( istream& bin );
// . . .
private:
// . . .
}; // Date
:
void Date::load( istream& bin )
{
bin.read( reinterpret_cast<char*>(&dYear), sizeof(dYear) );
if ( !bin.eof() )
{
bin.read( reinterpret_cast<char*>(&dMonth),
sizeof(dMonth) );
bin.read( reinterpret_cast<char*>(&dDay), sizeof(dDay) );
if ( bin.fail() )
throw DateXptn( "load", DateXptn::cannotRead );
}
}; // Date::load

:
void Date_load( Date& a, istream& bin )

void load( istream& bin )


(void )
-. -
.
609

19.1.1 const
. 15-1
void Date_save( const Date& a, ostream& bout )
{
if ( bout.fail() )
throw _Xptn( "Date_save", _Xptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&a.year),
sizeof(a.year) );
bout.write( reinterpret_cast<const char*>(&a.month),
sizeof(a.month) );
bout.write( reinterpret_cast<const char*>(&a.day),
sizeof(a.day) );
if ( bout.fail() )
throw _Xptn( "Date_save", _Xptn::cannotWrite );
}; // Date_save
: :
// . . .
void save( istream& bin ) const;
// . . .
:
void Date::save( ostream& bout ) const
{
if ( bout.fail() )
throw DateXptn( "save", DateXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(dYear),
sizeof(dYear) );
bout.write( reinterpret_cast<const char*>(dMonth),
sizeof(dMonth) );
bout.write( reinterpret_cast<const char*>(dDay),
sizeof(dDay) );
if ( bout.fail() )
throw DateXptn( "save", DateXptn::cannotWrite );
}; // Date::save

const Date_save()
Date::save().
; Date_save() -
a. :
const

.
:
void Date_save( const Date& a, ostream& bout )

void save( ostream& bout ) const


const get set
load().

19.1.2
lastDay() isLeapYear() private
. lastDay ,
, !
610 19

,
. (helper functions)
.3
,
:
bool isLeapYear() const
{
bool fv( false );

if ( dYear%400 == 0 ) fv = true;
else if ( dYear%4 == 0 && dYear%100 != 0 ) fv = true;
return fv;
} // isLeapYear
,
.
unsigned int lastDay() const
{
unsigned int fv;

if ( dMonth == 1 || dMonth == 3 || dMonth == 5 || dMonth == 7


|| dMonth == 8 || dMonth == 10 || dMonth == 12 )
fv = 31;
else if ( dMonth == 4 || dMonth == 6 || dMonth == 9 ||
dMonth == 11 )
fv = 30;
else // month == 2
if ( isLeapYear(dYear) ) fv = 29;
else fv = 28;
return fv;
} // lastDay
lastDay()
dMonth dYear .
.
.
Date d;
d.lastDay(); d!!!
d.isLeapYear() true d;! ,
. .

19.1.3 class public


:
struct Date
{
Date( int ay=1, int am=1, int ad=1 );
unsigned int getYear() const { return dYear; }
unsigned char getMonth() const { return dMonth; }
unsigned char getDay() const { return dDay; }
void setYear( int ay );
void setMonth( int am );
void setDay( int ad );
void load( istream& bin );
void save( ostream& bout ) const;
private:
unsigned int dYear;
unsigned char dMonth;

3 static!
611

unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
}; // Date
:
class Date
{
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
public:
Date( int ay=1, int am=1, int ad=1 );
unsigned int getYear() const { return dYear; }
unsigned char getMonth() const { return dMonth; }
unsigned char getDay() const { return dDay; }
void setYear( int ay );
void setMonth( int am );
void setDay( int ad );
void load( istream& bin );
void save( ostream& bout ) const;
}; // Date
struct
.
private.
class .
public.
:
public private.

public. (inter-
face part) .
class
struct.
:
class Date
{
public:
Date( int ay=1, int am=1, int ad=1 );
unsigned int getYear() const { return dYear; }
unsigned int getMonth() const { return dMonth; }
unsigned int getDay() const { return dDay; }
void setYear( int ay );
void setMonth( int am );
void setDay( int ad );
void load( istream& bin );
void save( ostream& bout ) const;
private:
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
}; // Date
Date .
:
612 19

struct DateXptn
{
enum { yearErr, monthErr, dayErr,
fileNotOpen, cannotRead, cannotWrite };
char funcName[100];
int errorCode;
int errVal1;
int errVal2;
int errVal3;
DateXptn( const char* mn, int ec,
int ev1 = 0, int ev2 = 0, int ev3 = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
errVal1 = ev1; errVal2 = ev2; errVal3 = ev3; }
}; // DateXptn

19.1.4
Date (15.5). ;
;
(<<, <, ==)
:

get.
ostream& operator<<( ostream& tout, const Date& rhs )
{
return tout << rhs.getDay() << '.' << rhs.getMonth() << '.'
<< rhs.getYear();
} // operator<<( ostream& tout, const Date

bool operator<( const Date& lhs, const Date& rhs )


{
bool fv;

if ( lhs.getYear() < rhs.getYear() ) fv = true;


else if ( lhs.getYear() > rhs.getYear() ) fv = false;
else // lhs.getYear() == rhs.getYear()
{
if ( lhs.getMonth() < rhs.getMonth() ) fv = true;
else if ( lhs.getMonth() > rhs.getMonth() ) fv = false;
else // lhs.getYear() == rhs.getMonth() &&
// lhs.getMonth() == rhs.getMonth()
fv = ( lhs.getDay() < rhs.getDay() );
}
return fv;
} // operator<( const Date . . .

bool operator==( const Date& lhs, const Date& rhs )


{
return ( lhs.getYear() == rhs.getYear() &&
lhs.getMonth() == rhs.getMonth() &&
lhs.getDay() == rhs.getDay() );
}; // operator==( const Date
, !
, .
, , inline.
, (-
)
private.
613

19.1.5
Date dYear, dMonth dDay;
(
d). ( ).
m member
() : mYear, mMonth mDay.
_year, _month _day.

19.2

.
19.1 19.1.1.
setYear(). struct Date ; -
:
void Date_setYear( Date& d, int ay )
, , void
. 19.1 :
void setYear( int ay )
getYear() struct Date :
unsigned int Date_getYear( Date d )
, ,
unsigned int Date_getYear( const Date& d )
,
. 19.1.1
:
unsigned int getYear() const
: K
K& a const K& a .
,
,
const.
, C++ (C),
.

19.3

Date:
Date.h ( ):
#ifndef _DATE_H
#define _DATE_H

#include <fstream>
#include <string>

using namespace std;

class Date
//
614 19

struct DateXptn
//

ostream& operator<<( ostream& tout, const Date& rhs );


bool operator<( const Date& lhs, const Date& rhs );
bool operator==( const Date& lhs, const Date& rhs );

#endif // _DATE_H
Date.cpp:
#ifndef _DATE_CPP
#define _DATE_CPP

#include <fstream>
#include "Date.h"

Date::Date( int ay, int am, int ad )


//
void Date::setYear( int ay )
//
void Date::setMonth( int am )
//
void Date::setDay( int ad )
//
void Date::load( istream& bin )
//
void Date::save( ostream& bout ) const
//
bool Date::isLeapYear( int y )
//
unsigned int Date::lastDay( int y, int m )
//

ostream& operator<<( ostream& tout, const Date& rhs )


//
bool operator<( const Date& lhs, const Date& rhs )
//
bool operator==( const Date& lhs, const Date& rhs )
//

#endif // _DATE_CPP
, Date,
#include "Date.cpp".
project
Date.o ( Date.obj). -
#include "Date.h".4 .

19.3.1
: -
lastDay isLeapYear private
. , : , -
, Date.h Date.obj.
; , ; ! :
(information hiding):
.
,

4 , , Date.h
Date.obj.
615

.
( - )
:

:
obj
.

( !)
:

obj
, .

.

19.4 inline
Date, , :
() , get
. . ;

inline .
get inline . -

:
class Date
// . . .
unsigned int getYear() const;
unsigned char getMonth() const;
unsigned char getDay() const;
// . . .
}; // Date
:
inline unsigned int Date::getYear() const { return dYear; }
inline unsigned int getMonth()
const { return static_cast<unsigned int>( dMonth ); }
inline unsigned int getDay() const
{ return static_cast<unsigned int>( dDay ); }

get.
, inline -
.

19.5 -
, -
(class invariant).
(dYear > 0) (0 < dMonth 12) (0 < dDay lastDay(dYear, dMonth))
Date.
616 19

, ,
.
() -
.
( ) .
.
DateXptn
:
yearErr dYear > 0.
monthErr 0 < dMonth 12
dayErr 0 < dDay lastDay(dYear, dMonth).
-
. :
-
.
, Date DateXptn.
load();
: bin eof.
: ( load()) -
.
:
void Date::load( istream& bin )
{
if ( bin.fail() && !bin.eof() )
throw DateXptn( "load", DateXptn::fileNotOpen );
bin.read( reinterpret_cast<char*>(&dYear), sizeof(dYear) );
if ( !bin.eof() )
{
bin.read( reinterpret_cast<char*>(&dMonth),
sizeof(dMonth) );
bin.read( reinterpret_cast<char*>(&dDay), sizeof(dDay) );
if ( bin.fail() )
throw DateXptn( "load", DateXptn::cannotRead );
}
}; // Date::load
bin.fail() true
DateXptn fileNotOpen ( ).
true bin.fail() (
) .
DateXptn cannotRead.
:
1. eof; , , -
.
, , bin.fail(). -
load().
2. load() . , -
, . -
.
-
private: -
.
, Date dYear
617

setYear
.

.
:
,
.. setYear (7) dYear
.
3 4 . , , 4793 -
Date .
(15.5.1)
( ). -
. 4780 ,
2390 Employee ( ,
15.1).
. ,
(object identifier) -
.5

: , myFunc, myFunc -
37 !
.
, ,
(debugger).
, .

19.6 class struct;


,
struct class.
.
class struct; :
class ,
private . ,
public.
struct ,
public . , -
private.
C++
: class
struct. . 6
struct
. C
.
private public class.

5 .
6 C# -
.
618 19

:7
struct
(true).
1

struct complex
{
double re;
double im;
complex( double rp = 0.0, double ip = 0.0 )
{ re = rp; im = ip; };
}; // complex
;
(-DBL_MAX re DBL_MAX) (-DBL_MAX im DBL_MAX)
double
complex. true.

struct.
2
-
. .
26 long
int :
0 1 'A' ,
1 1 'B' ,
...
25 1 'Z' .

class SetOfUCL
{
public:
// . . .
private:
long int bitmap;
}; // SetOfUCL
struct;
true. struct :

()
. ; class,
long int bitmap ( ) private
getBitmap setBitmap.

:
1. true ( )
2. , -

7 (Lockheed-Martin 2005) AV Rule 66 : A class should be used to model an entity that


maintains an invariant, :
class ( struct).
619

.
, struct ( ),
-
.
.
Circle : -
cXC, cYC cR. cR 0.
, . -
; private public -
; ! -
:8
class private.

19.7 struct GrElmn class GrElmn


GrElmn -
15.14:9
struct GrElmn
{
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
}; // GrElmn
; :
0 < geANumber < geAWeight
:

GrElmn a;
a.geANumber, a.geAWeight; : a.geANumber
== a.geAWeight == 0.
geSymbol 1 (.. U) 2 (.. Ca).
.
geSymbol geName geGrName -
. .
( )
; 105 112 ; , ,
() .
,
.
:

8 (CERT 2009) OBJ00: Declare data members private. (Lockheed-Martin


2005) AV Rule 67 : public and protected data should only be used in structsnot classes (
protected ).
9

620 19

((0 < geANumber < geAWeight) ||


(geANumber == 0 && geAWeight 0) || (geAWeight == 0 && geANumber 0))
&& (geSymbol 2)
: geANumber, geAWeight
0 < geANumber < geAWeight 0
. () -
set.
geSymbol geName -
geGrName.
:
class GrElmn
{// I: ((0 < geANumber < geAWeight) ||
// (geANumber == 0 && geAWeight 0) ||
// (geAWeight == 0 && geANumber 0))
// && (geSymbol 2)
public:
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
// . . .
private:
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[4];
char geName[14];
char geGrName[14];
}; // GrElmn
(2 1) :
GrElmn( int aan=0, float aaw=0,
string as="", string anm="", string agn="" );

GrElmn::GrElmn( int aan, float aaw,
string as, string anm, string agn )
{
if ( aan < 0 )
throw GrElmnXptn( "GrElmn", GrElmnXptn::negANumber, aan );
if ( aaw < 0 )
throw GrElmnXptn( "GrElmn", GrElmnXptn::negANumber, aaw );
// aan >= 0 && aaw >= 0
if ( (aan != 0 && aaw != 0) && aan >= aaw )
throw GrElmnXptn( "GrElmn", GrElmnXptn::an_gt_aw,
aan, aaw );
// (aan == 0 && aaw >= 0) || (aaw == 0 && aan >= 0) ||
// (0 < aan < aaw)
geANumber = aan;
geAWeight = aaw;
// (geANumber == 0 && geAWeight >= 0) ||
// (geAWeight == 0 && geANumber >= 0) ||
// (0 < geANumber < geAWeight)
if ( as.length() > 2 )
throw GrElmnXptn( "GrElmn", GrElmnXptn::longSymbol,
as.c_str() );
strncpy( geSymbol, as.c_str(), symbolSz-1 );
geSymbol[symbolSz-1] = '\0';
strncpy( geName, anm.c_str(), nameSz-1 );
geName[nameSz-1] = '\0';
strncpy( geGrName, agn.c_str(), grNameSz-1 );
geGrName[grNameSz-1] = '\0';
} // GrElmn::GrElmn
, , setAWeight() setANumber() 0:
void GrElmn::setAWeight( float aaw )
621

{
if ( aaw <= 0 )
throw GrElmnXptn( "setAWeight",
GrElmnXptn::negAWeight, aaw );
// aaw > 0
if ( geANumber >= aaw )
throw GrElmnXptn( "setAWeight", GrElmnXptn::an_gt_aw,
geANumber, aaw );
// 0 <= geANumber < aaw
geAWeight = aaw;
// 0 <= geANumber < geAWeight
} // GrElmn::setAWeight
: setAWeight() geAWeight 0.
setANumber():
void GrElmn::setANumber( int aan )
{
if ( aan <= 0 )
throw GrElmnXptn( "setANumber",
GrElmnXptn::negANumber, aan );
// aan > 0
if ( geAWeight != 0 && geAWeight <= aan )
throw GrElmnXptn( "setANumber",
GrElmnXptn::an_gt_aw, aan, geAWeight );
// (aan > 0) && (geAWeight != 0 0 < aan < geAWeight)
geANumber = aan;
// (geANumber > 0) &&
// (geAWeight != 0 0 < geANumber < geAWeight)
} // GrElmn::setANumber
:
, 15.14 ,
set, setGrName.
setANumber().

geANumber geSymbol geName geGrName.
(candidate keys) GrElmn.
geANumber . set
geSymbol, geName geGrName
-
.
setANumber() :
geANumber , GrElmn
elementsGr.dta -
. :

.
setANumber() -
.
geANumber -
.
. , :
GrElmn oneElmn( 20, 40.08, "Ca", "Calcium", "" );
:
oneElmn = GrElmn( 6, 12.011, "C", "Carbon", "" );
set .
15.14.1 ,
622 19

GrElmn_copyFromElmn()
GrElmn_save().

fv.geANumber = a.eANumber;
fv.geAWeight = a.eAWeight;
strcpy( fv.geSymbol, a.eSymbol );
strcpy( fv.geName, a.eName );
fv.geGrName[0] = '\0';
5
set.
set
. ,
( ) -
. , ,
:
GrElmn::GrElmn( const Elmn& rhs )
{
geANumber = rhs.eANumber;
geAWeight = rhs.eAWeight;
strcpy( geSymbol, rhs.eSymbol );
strcpy( geName, rhs.eName );
geGrName[0] = '\0';
} // GrElmn::GrElmn
Elmn
GrElmn , -
. , :
//
Elmn oneElmn;
int k( 0 );
Elmn_load( oneElmn, bin );
while ( !bin.eof() )
{
//
GrElmn oneGrElmn( oneElmn );
//
oneGrElmn.save( bout );
++k;
//
Elmn_load( oneElmn, bin );
} // while
GrElmn_save :
void GrElmn::save( ostream& bout ) const
{
if ( bout.fail() )
throw GrElmnXptn( "save", GrElmnXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&geANumber),
sizeof(geANumber) );
bout.write( reinterpret_cast<const char*>(&geAWeight),
sizeof(geAWeight) );
bout.write( geSymbol, symbolSz );
bout.write( geName, nameSz );
bout.write( geGrName, grNameSz );
if ( bout.fail() )
throw GrElmnXptn( "save", GrElmnXptn::cannotWrite );
} // GrElmn::save
15.14.2 GrElmn::save(),
GrElmn_load(), GrElmn_display(), GrElmn_setGrName().
:
void GrElmn::load( istream& bin )
623

{
bin.read( reinterpret_cast<char*>(&geANumber),
sizeof(geANumber) );
if ( !bin.eof() )
{
bin.read( reinterpret_cast<char*>(&geAWeight),
sizeof(geAWeight) );
bin.read( geSymbol, symbolSz );
bin.read( geName, nameSz );
bin.read( geGrName, grNameSz );
if ( bin.fail() )
throw GrElmnXptn( "load", GrElmnXptn::cannotRead );
}
} // GrElmn::load

void GrElmn::display( ostream& tout ) const


{
tout << "atomic number: " << geANumber << endl
<< "atomic weight: " << geAWeight << endl
<< "symbol: " << geSymbol << endl
<< "name: " << geName << endl
<< "greek name: " << geGrName << endl;
} // GrElmn::display

void GrElmn::setGrName( string newGrName )


{
strncpy( geGrName, newGrName.c_str(), grNameSz-1 );
geGrName[grNameSz-1] = '\0';
} // GrElmn::setGrName
writeRandom() :
bout.seekp( (a.geANumber-1)*GrElmn::saveSize );
, geANumber -
get:
unsigned short int getANumber() const { return geANumber; }
, writeRandom :
bout.seekp( (a.getANumber()-1)*GrElmn::saveSize );
GrElmn_writeToTable(), 15.14.2,
:
void GrElmn::writeToTable( ostream& tout ) const
{
tout << geANumber << '\t' << geGrName << " (" << geName
<< ")\t" << geSymbol << '\t' << geAWeight << endl;
} // GrElmn::writeToTable
GrElmn.h:
#ifndef _GRELMN_H
#define _GRELMN_H

#include <fstream>
#include <string>

using namespace std;

struct Elmn
{
unsigned short int eANumber; //
float eAWeight; //
char eSymbol[4];
char eName[14];
}; // Elmn

class GrElmn
{
624 19

public:
enum { symbolSz = 4, nameSz = 14, grNameSz = 14,
saveSize = sizeof(short int) + sizeof(float) +
symbolSz + nameSz + grNameSz };
GrElmn( int aan=0, float aaw=0,
string as="", string anm="", string agn="" );
GrElmn( const Elmn& rhs );
unsigned short int getANumber() const { return geANumber; }
void setAWeight( float aaw );
void setGrName( string newGrName );
void save( ostream& bout ) const;
void load( istream& bin );
void display( ostream& tout ) const;
void writeToTable( ostream& tout ) const;
private:
unsigned short int geANumber; //
float geAWeight; //
char geSymbol[symbolSz];
char geName[nameSz];
char geGrName[grNameSz];
}; // GrElmn

struct GrElmnXptn
{
enum { negANumber, negAWeight, an_gt_aw, longSymbol,
fileNotOpen, cannotWrite, cannotRead };
char funcName[100];
int errorCode;
float errFltVal1;
float errFltVal2;
char errStrVal[100];
GrElmnXptn( const char* mn, int ec, float ev1, int ev2=0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
errFltVal1 = ev1; errFltVal2 = ev2; }
GrElmnXptn( const char* mn, int ec, const char* sv="" )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // GrElmnXptn

#endif // _GRELMN_H
GrElmn.cpp:
#ifndef _GRELMN_CPP
#define _GRELMN_CPP

#include <fstream>
#include "GrElmn.h"

//========================= ==========================
GrElmn::GrElmn( int aan, float aaw,
string as, string anm, string agn )
//
GrElmn::GrElmn( const Elmn& rhs )
//
//========================== setters ============================
void GrElmn::setAWeight( float aaw )
//
void GrElmn::setGrName( string newGrName )
//
//======================= =========================
void GrElmn::save( ostream& bout ) const
//
void GrElmn::load( istream& bin )
//
void GrElmn::display( ostream& tout ) const
625

//
void GrElmn::writeToTable( ostream& tout ) const
//

#endif // _GRELMN_CPP
()
15.14. get set; !
, -
. .

19.8 10
, ,
. -
( -
).
:
. -
( volts), () ( joules) o
( joules).
, ,
:
) powerDevice(): t ( sec),
i ( amperes) , , v, -
( E = vit). :
true ( ) -
.
.
false .
) maxTime(): i ( amperes) , -
, v, ( E = vit) (sec)
. .
) recharge(): ,
.
: 12
volts 5106 joules. -
4 amperes 15 min.
8 amperes.
.
:
0 < bVoltage && 0 < bMaxEnergy && 0 bEnergy bMaxEnergy
:
class Battery
{// I: 0 < bVoltage && 0 < bMaxEnergy && 0 bEnergy bMaxEnergy
public:
// ...
private:
double bVoltage; // volts
double bMaxEnergy; // joules
double bEnergy; // joules
}; // Battery

10 (Mansfield & Antonakos 1997).


626 19

, 19.1.4.
:
struct BatteryXptn
{
enum { . . . };
char funcName[100];
int errorCode;
double errorValue;
BatteryXptn( const char* mn, int ec, double ev = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec; errorValue = ev; }
}; // BatteryXptn

. :
12 5106 joules, (2
1) .
Battery( double v = 12, double me = 5e6 );
:
Battery::Battery( double v, double me )
{
if ( v <= 0 )
throw BatteryXptn( "Battery", BatteryXptn::voltageErr, v );
if ( me <= 0 )
throw BatteryXptn( "Battery", BatteryXptn::energyErr, me );
bVoltage = v;
bMaxEnergy = me;
bEnergy = bMaxEnergy;
} // Battery::Battery
, -
. enum Bat-
teryXptn voltageErr energyErr.

19.8.1 get, set


get ; ,
maxTime() ( getEnergy()
),
. ;
Battery ;
:
double getVoltage() const { return bVoltage; };
double getMaxEnergy() const { return bMaxEnergy; };
set ; -
bVoltage bMaxEnergy, -
(-
) . recharge(),
.

19.8.2 powerDevice()
t ( sec),
i ( amperes) , , v, ( E =
vit). :
627

true ( ) -
.
.
false .
powerDevice()
bool. , :
??? Battery_powerDevice( Battery& ab,
double t, double i, bool& ok )
(ab) (ok).
(13.9) void. :
void Battery::powerDevice( double t, double i, bool& ok )
:
: t 0 && i 0
: (ok == (bVoltage*i*t <= bEnergy)) &&
((ok (bEnergy == bEnergy - bVoltage*i*t))
, t < 0 i < 0 .
bVoltage*i*t <= bEnergy . -

ok.
void Battery::powerDevice( double t, double i, bool& ok )
{
if ( t < 0 )
throw BatteryXptn( "powerDevice", BatteryXptn::timeErr, t );
if ( i < 0 )
throw BatteryXptn( "powerDevice",
BatteryXptn::currentErr, i );
double reqEnergy( bVoltage*i*t );
ok = reqEnergy <= bEnergy;
if ( ok ) bEnergy -= reqEnergy;
} // Battery::powerDevice
, BatteryXptn (time-
Err, currentErr):
enum { voltageErr, energyErr, timeErr, currentErr };

19.8.3 maxTime()
i ( amperes) , ,
v, ( E = vit) ( sec)
. .
:
: i > 0
: maxTime(i) == bEnergy/(bVoltage*i)
:
double Battery::maxTime( double i ) const
{
if ( i <= 0 )
throw BatteryXptn( "maxTime", BatteryXptn::currentErr, i );
return bEnergy/(bVoltage*i);
} // Battery::maxTime
628 19

19.8.4 reCharge
,
.
:
: true
: bEnergy == bMaxEnergy
void Battery::reCharge()
{
bEnergy = bMaxEnergy;
} // Battery::reCharge

19.8.5
Battery.h :
#ifndef _BATTERY_H
#define _BATTERY_H

#include <string>

using namespace std;

class Battery
{// I: 0 < bVoltage && 0 < bMaxEnergy &&
// 0 <= bEnergy <= bMaxEnergy
public:
Battery( double v = 12, double me = 5e6 );
double getVoltage() const { return bVoltage; };
double getMaxEnergy() const { return bMaxEnergy; };
void powerDevice( double t, double i, bool& ok );
double maxTime( double i ) const;
void reCharge();
private:
double bVoltage; // volts
double bMaxEnergy; // joules
double bEnergy; // joules
}; // Battery

struct BatteryXptn
{
enum { voltageErr, energyErr, timeErr, currentErr };
char funcName[100];
int errorCode;
double errorValue;
BatteryXptn( const char* mn, int ec, double ev = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec; errorValue = ev; }
}; // BatteryXptn

#endif // _BATTERY_H
Battery.cpp:
#ifndef _BATTERY_CPP
#define _BATTERY_CPP

#include <fstream>
#include "Battery.h"

Battery::Battery( double v, double me )


//
void Battery::powerDevice( double t, double i, bool& ok )
//
double Battery::maxTime( double i ) const
//
629

void Battery::reCharge()
//

#endif // _BATTERY_CPP

19.8.6
:
:
12 volts 5106 joules. -
4 amperes 15 min.
8 amperes.
.

Battery btr;

Battery btr( 12, 5e6 );
(
sec):
btr.powerDevice( 15*60, 4, ok );
:
cout << " 8 A " << btr.maxTime(8)
<< " sec" << endl;
, :
btr.reCharge();
cout << " 8 A " << btr.maxTime(8)
<< " sec" << endl;
,
. :
#include <iostream>
#include <string>
#include "Battery.h"
#include "Battery.cpp"

using namespace std;

int main()
{
bool ok;

try
{
Battery btr( 12, 5e6 );

btr.powerDevice( 15*60, 4, ok );
cout << " 8 A "
<< btr.maxTime(8) << " sec" << endl;

btr.reCharge();
cout << " 8 A "
<< btr.maxTime(8) << " sec" << endl;
}
catch ( BatteryXptn& xpt )
{
switch ( xpt.errorCode )
{
case BatteryXptn::voltageErr:
cout << xpt.funcName << ": ("
630 19

<< xpt.errorValue << ')' << endl; break;


case BatteryXptn::energyErr:
cout << xpt.funcName << ": ("
<< xpt.errorValue << ')' << endl; break;
case BatteryXptn::timeErr:
cout << xpt.funcName << ": ("
<< xpt.errorValue << ')' << endl; break;
case BatteryXptn::currentErr:
cout << xpt.funcName << ": ("
<< xpt.errorValue << ')' << endl; break;
default:
cout << xpt.funcName
<< ": " << endl;
} // switch
} // catch
} // main

19.9 ( )
() -
()
.
- .
.
.
.
.
.

.
-

.
C++:
struct ( ) class ( ).

public private.

.
.
.

.
:
-
. (
.)
. -
( ) -
.
631


19-1
:
struct Date class Date class Date
{ { {
Date( . . . ); unsigned int dYear; public:
// . . . // . . . Date( . . . );
private: public: // . . .
unsigned int dYear; Date( . . . ); private:
// . . . // . . . unsigned int dYear;
}; // Date }; // Date // . . .
}; // Date
, , .
1 2 3
struct Date class Date struct Date
{ { {
public: Date( . . . ); unsigned int dYear;
Date( . . . ); // . . . // . . .
// . . . private: public:
private: unsigned int dYear; Date( . . . );
unsigned int dYear; // . . . // . . .
// . . . }; // Date }; // Date
}; // Date
:
1
2
1, 3

19-2 , getDayOfWeek, Date,
:
typedef enum { sunday, monday, tuesday, wednesday, thursday,
friday, saturday } WeekDay;
:
WeekDay getDayOfWeek( Date d ) const;
WeekDay getDayOfWeek( Date d );
WeekDay getDayOfWeek() const;
WeekDay getDayOfWeek();
void getDayOfWeek( WeekDat& wd ) const;


19-3 isValidDate ay, am ad
true ( false).
Date;
.: Date.
19-4 GrElmn, Elmn.
elements.dta.
-
. -
.
632 19


19-5 :
:
class Piscina...
() .
(l), (w) (d) m. -
642 (, ).
h ( m) ,
d 0.3. m, lwh.
C.

:
fill():
dh, m,
ta, ( C)

dh.
d 0.3 m. : (*h+ta*dh)/(h+dh).
empty(): dh -
m -
dh.
0.
heat(): dt -
C -
cal. Vcdt V m,
= 103 kgr/m c = 103 calkgr-1grad-1
. , 100 C.
:
531.2. (1 0.6 m )
10 C 15 C. -
. ,
( m) ( cal) .
project

3

:
Prj03.1 ............................................................................................................................................. 633
Prj03.2 () .................................................................................................... 635
Prj03.3 Course ........................................................................................................................................ 636
Prj03.4 Student ....................................................................................................................................... 641
Prj03.5 StudentInCourse ....................................................................................................................... 644
Prj03.6 ........................................................................................................................................... 645
Prj03.6.1 loadCourses() ........................................................................................................................................646
Prj03.6.2 ............................................................................................647
Prj03.6.3 . . . ..................................................................................................................648
Prj03.6.4 . . . ............................................................................................................649
Prj03.6.5 main ......................................................................................................................................................649
Prj03.7 char* string; ........................................................................................................................................ 651
Prj03.8 ............................................................................................................ 652
- ............................................................................................................................................. 653
.............................................................................................................................................................................653

Prj03.1

- (binary) gCourses.dta
:
class SylCourse
{
public:
enum { cCodeSz = 8, cTitleSz = 80, cCategSz = 4 };
// . . .
private:
char cCode[cCodeSz]; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
char cPrereq[cCodeSz]; //
}; // SylCourse
, , .

633
634 Project 03

(text) , enrllmnt.txt, -
/ .
:
2149\t\t
4
0160
0240
0361
0203

2059\t\t
6
0221
0240
0331
0101
0305
0314
.
/ / (.. 2149 2059), -
/ ( ) ( ).

/ /.
.
.
.
:
.
.

:
- , Students.dta,
class Student
{
public:
enum { sNameSz = 20 };
// . . .
private:
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
unsigned int sWH; //
unsigned int sNoOfCourses; //
}; // Student
.
- , enrllmnt.dta,
class StudentInCourse
{
public:
// . . .
private:
enum { sicCCodeSz = 8 };
unsigned int sicSIdNum; //
char sicCCode[sicCCodeSz]; //
float sicMark; //
}; // StudentInCourse
( ) .
635

- , courses.dta,
Course, . Course SylCourse
:
unsigned int cNoOfStudents; // .
.
, log.txt.

30 .
:
gCourses.dta :
void SylCourse::save( ostream& bout ) const
{
if ( bout.fail() )
throw SylCourseXptn( "save", SylCourseXptn::fileNotOpen );
bout.write( cCode, sizeof(cCode) ); //
bout.write( cTitle, sizeof(cTitle) ); //
bout.write( reinterpret_cast<const char*>(&cFSem), sizeof(cFSem) );
//
bout.write( reinterpret_cast<const char*>(&cCompuls), sizeof(cCompuls) );
//
bout.write( &cSector, sizeof(cSector) ); //
bout.write( cCateg, sizeof(cCateg) ); //
bout.write( reinterpret_cast<const char*>(&cWH), sizeof(cWH) );
//
bout.write( reinterpret_cast<const char*>(&cUnits), sizeof(cUnits) );
//
bout.write( cPrereq, sizeof(cPrereq) ); //
if ( bout.fail() )
throw SylCourseXptn( "save", SylCourseXptn::cannotWrite );
} // SylCourse::save

Prj03.2 ()


1. cNoOfStudents Course sNoOfCourses, sWH Student -
. ! Course cNoOfStu-
dents .
Student. ! -
: -
.
.
2. StudentInCourse -
, ..: ( -
) , ( -
) . , .


. , ,
;
.
.
.
636 Project 03

:

cNoOfStudents
enrllmnt.txt
do {

if ( )
{
if ( )
{
//
log
}
else
{

sNoOfCourses sWH
for ( )
{


if ( )
log
else
{
( , )

sNoOfCourses sWH
cNoOfStudents
}
} // for
} // if ( )
} // if ( )
} while ( )
for ( )
if ( sWH > 30 ) log
Students.dta
enrllmnt.dta
gCourses.dta
.

Prj03.3 Course
Course;
-
( ). SylCourse -

, load,
(-)
(, , )
SylCourse Course.
.1
loadSylCourse -
SylCourse
Course.
.

1 SylCourse ( Course).
637

( cNoOfStudents -
). clearStudents()
setNoOfStudents() .
(
). -
(getCode()).
-
( sNoOfCourses sWH ).
getWH.
1 (-
cNoOfStudents ). add1Stu-
dent() cNoOfStudents 1 getNoOfStu-
dents() setNoOfStudents().
- (-
courses.dta). save
.
loadSylCourse(). SylCourse
:
bool (cCompuls).
unsigned int (cFSem, cWH, cUnits).
char (cCode cPrereq cCodeSz (8), cTitle cTitleSz
(80), cCateg cCategSz (4) cSector 1).
:2
bool bBuf;
unsigned int iBuf;
char cBuf[Course::cTitleSz];
SylCourse::save :
bin.read( cBuf, Course::cCodeSz ); //
bin.read( cBuf, Course::cTitleSz ); //
bin.read( reinterpret_cast<char*>(&iBuf), sizeof(unsigned int) );
//
bin.read( reinterpret_cast<char*>(&bBuf), sizeof(bool) );
//
bin.read( cBuf, sizeof(char) ); //
bin.read( cBuf, Course::cCategSz ); //
bin.read( reinterpret_cast<char*>(&iBuf), sizeof(unsigned int) );
//
bin.read( reinterpret_cast<char*>(&iBuf), sizeof(unsigned int) );
//
bin.read( cBuf, Course::cCodeSz ); //
loadSylCourse() :
void loadSylCourse( ifstream& bin, Course& oneCourse )
{
bool bBuf;
unsigned int iBuf;
char cBuf[Course::cTitleSz];

bin.read( cBuf, Course::cCodeSz ); //


if ( !bin.eof() )
{
oneCourse.setCode( cBuf );

2 Course :
public:
enum { cCodeSz = 8, cTitleSz = 80, cCategSz = 4 };
638 Project 03

bin.read( cBuf, Course::cTitleSz ); oneCourse.setTitle( cBuf );


bin.read( reinterpret_cast<char*>(&iBuf), sizeof(unsigned int) );
oneCourse.setFSem( iBuf );
bin.read( reinterpret_cast<char*>(&bBuf), sizeof(bool) );
oneCourse.setCompuls( bBuf );
bin.read( cBuf, sizeof(char) ); oneCourse.setSector( cBuf[0] );
bin.read( cBuf, Course::cCategSz ); oneCourse.setCateg( cBuf );
bin.read( reinterpret_cast<char*>(&iBuf), sizeof(unsigned int) );
oneCourse.setWH( iBuf );
bin.read( reinterpret_cast<char*>(&iBuf), sizeof(unsigned int) );
oneCourse.setUnits( iBuf );
bin.read( cBuf, Course::cCodeSz ); oneCourse.setPrereq( iBuf );
if ( bin.fail() )
throw ProgXptn( "loadSylCourse", ProgXptn::cannotRead );
}
} // loadSylCourse
, setCode() setFSem(), setCompuls(), setSector(),
setCateg(), setWH(), setUnits() setPrereq() ()
cCode, cTitle, cFSem, cCompuls, cSector, cCateg, cWH, cUnits cPrereq .

.
. ,
, . -
, ,
setFSem()
1 8.
void Course::setFSem( int aFSem )
{
if ( aFSem < 1 || 8 < aFSem)
throw CourseXptn( "setFSem", CourseXptn::rangeError, aFSem );
cFSem = aFSem;
} // Course::setFSem
setPrereq()
.
void Course::setPrereq( const string& prCode )
{
if ( (prCode.length() > 0) && (prCode == cCode) )
throw CourseXptn( "setPrereq", CourseXptn::autoRef, prCode.c_str() );
strncpy( cPrereq, prCode.c_str(), cCodeSz-1 ); cPrereq[cCodeSz-1] = '\0';
} // Course::setPrereq
, -

void Course::setCode( string aCode )
{
if ( (aCode.length() > 0) && (aCode == cPrereq) )
throw CourseXptn( "setCode", CourseXptn::autoRef, aCode.c_str() );
strncpy( cCode, aCode.c_str(), cCodeSz-1 ); cCode[cCodeSz-1] = '\0';
} // Course::setCode
, , :
void Course::setTitle( string aTitle )
{
strncpy( cTitle, aTitle.c_str(), cTitleSz-1 ); cTitle[cTitleSz-1] = '\0';
} // Course::setTitle
void Course::setSector( char aSector ) { cSector = aSector; }
void Course::setCateg( string aCateg )
{
strncpy( cCateg, aCateg.c_str(), cCategSz-1 ); cTitle[cCategSz-1] = '\0';
} // Course::setCateg
void Course::setWH( int aWH ) { cWH = aWH; }
639

void Course::setUnits( int aUnits ) { cUnits = aUnits; }


:
unsigned int getNoOfStudents() { return cNoOfStudents; }
void clearStudents() { cNoOfStudents = 0; }
void add1Student() { ++cNoOfStudents; }
unsigned int getWH() const { return cWH; }
setNoOfStudents; :
, Course ac, :
ac.clearStudents();
:
ac.add1Student();
setNoOfStudents :
ac.setNoOfStudents( 0 );
:
ac.setNoOfStudents( ac.getNoOfStudents()+1 );
, setNoOfStudents ( )
( ac.setNoOfStudents(20);) getNoOfStudents()
.

const char* getCode() const { return cCode; }
const. ;
const :
cout << ac.getCode() << endl;
char* p( ac.getCode() );
p[3] = 'X'; p[4] = 'Z';
cout << ac.getCode() << endl;
:
0140
0XZ0
,
.
const ( ) p
:
char* p( new char[strlen(ac.getCode())+1] );
strcpy( p, ac.getCode() );
p ac.cCode .
load() save(). save() SylCourse::save(),
, cNoOfStudents:
void Course::save( ostream& bout ) const
{
if ( bout.fail() )
throw CourseXptn( "save", CourseXptn::fileNotOpen );
bout.write( cCode, sizeof(cCode) ); //
bout.write( cTitle, sizeof(cTitle) ); //
bout.write( reinterpret_cast<const char*>(&cFSem), sizeof(cFSem) );
//
bout.write( reinterpret_cast<const char*>(&cCompuls), sizeof(cCompuls) );
//
bout.write( &cSector, sizeof(cSector) ); //
bout.write( cCateg, sizeof(cCateg) ); //
bout.write( reinterpret_cast<const char*>(&cWH), sizeof(cWH) );
//
bout.write( reinterpret_cast<const char*>(&cUnits), sizeof(cUnits) );
//
bout.write( cPrereq, sizeof(cPrereq) ); //
640 Project 03

bout.write( reinterpret_cast<const char*>(&cNoOfStudents),


sizeof(cNoOfStudents) ); // . .
if ( bout.fail() )
throw CourseXptn( "save", CourseXptn::cannotWrite );
} // Course::save
load() save, :
void Course::load( istream& bin )
{
bin.read( cCode, cCodeSz ); //
if ( !bin.eof() )
{
bin.read( cTitle, cTitleSz ); //
bin.read( reinterpret_cast<char*>(&cFSem), sizeof(cFSem) );
//
bin.read( reinterpret_cast<char*>(&cCompuls), sizeof(cCompuls) );
//
bin.read( &cSector, sizeof(cSector) ); //
bin.read( cCateg, cCategSz ); //
bin.read( reinterpret_cast<char*>(&cWH), sizeof(cWH) );
//
bin.read( reinterpret_cast<char*>(&cUnits), sizeof(cUnits) );
//
bin.read( cPrereq, cCodeSz ); //
bin.read( reinterpret_cast<char*>(&cNoOfStudents),
sizeof(cNoOfStudents) ); // . .
if ( bin.fail() )
throw CourseXptn( "load", CourseXptn::cannotRead );
} // if ( !bin.eof() ). . .
} // Course::load
load() . ; :
ac.load( bin );
ac .
. , .
, .
:
void Course::display( ostream& tout ) const
{
if ( tout.fail() )
throw CourseXptn( "display", CourseXptn::fileNotOpen );
tout << cCode << '\t' << cTitle << '\t';
if ( cCompuls ) tout << "\t";
else tout << "\t";
tout << cSector << '\t' << cCateg << '\t' << cWH << '\t'
<< cUnits << '\t' << cPrereq << '\t' << cFSem << '\t'
<< cNoOfStudents << endl;
if ( tout.fail() )
throw CourseXptn( "display", CourseXptn::cannotWrite );
} // Course::display

class Course
{
public:
enum { cCodeSz = 8, cTitleSz = 80, cCategSz = 4 };
Course( string aCode="" );
const char* getCode() const { return cCode; }
unsigned int getWH() const { return cWH; }
unsigned int getNoOfStudents() const { return cNoOfStudents; }
void setCode( string aCode );
void setTitle( string aTitle );
void setFSem( int aFSem );
void setCompuls( bool aCompuls ) { cCompuls = aCompuls; };
void setSector( char aSector ) { cSector = aSector; };
void setCateg( string aCateg );
641

void setWH( int aWH ) { cWH = aWH; };


void setUnits( int aUnits ) { cUnits = aUnits; };
void setPrereq( const string& prCode );
void clearStudents() { cNoOfStudents = 0; }
void add1Student() { ++cNoOfStudents; }
void save( ostream& bout ) const;
void load( istream& bin );
void display( ostream& tout ) const;
private:
char cCode[cCodeSz]; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
char cPrereq[cCodeSz]; //
unsigned int cNoOfStudents; // .
}; // Course
:
struct CourseXptn
{
enum { rangeError, autoRef,
fileNotOpen, cannotWrite, cannotRead };
char funcName[100];
int errorCode;
int errIntVal;
char errStrVal[100];
CourseXptn( const char* mn, int ec, const char* sv="" )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
CourseXptn( const char* mn, int ec, int iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
errIntVal = iv; }
}; // CourseXptn
:
typedef Course* PCourse;

Prj03.4 Student
Student.
:
readFromText load
, , (text)
set: setIdNum, setSurname, setFirstname

Student( int aIdNum=0, string aSurn="", string aFirstn="" )
if ( ) -
Student.
, (getIdNum).
( , )
. lin-
Search(); , -
. != .
642 Project 03

cNoOfStu-
dents Course, sNoOfCourses sWH
clearCourses().
( sNoOfCourses sWH
) add1Course().
(if (sWH > 30)) -
getWH().
, , save(), -
- (
Students.dta).
, :
unsigned int getIdNum() const { return sIdNum; }
unsigned int getWH() const { return sWH; }
void clearCourses() { sNoOfCourses = 0; sWH = 0; }
void add1Course( int aIncrWH );
:
void Student::add1Course( int aIncrWH )
{
if ( aIncrWH <= 0 )
throw StudentXptn( "add1Course", StudentXptn::nonPosIncr,
aIncrWH );
++sNoOfCourses;
sWH += aIncrWH;
} // Student::add1Course
.
!= :
bool operator!=( const Student& a, const Student& b )
{ return ( a.getIdNum() != b.getIdNum() ); }
,
load() :
void Student::readFromText( istream& tin )
{
string line;
getline( tin, line, '\n' );
if ( !tin.eof() )
{
size_t t1Pos( line.find("\t") );
if ( t1Pos >= line.length() )
throw StudentXptn( "readFromText",
StudentXptn::incomplete );
size_t t2Pos( line.find("\t", t1Pos+1) );
if ( t2Pos >= line.length() )
throw StudentXptn( "readFromText",
StudentXptn::incomplete );
string str1( line.substr(0, t1Pos) );
int iStr1;
iStr1 = atoi( str1.c_str() );
if ( iStr1 <= 0 )
throw StudentXptn( "readFromText",
StudentXptn::negIdNum, iStr1 );
sIdNum = iStr1;
str1 = line.substr( t1Pos+1, t2Pos-t1Pos-1 );
strncpy( sSurname, str1.c_str(), sNameSz-1 );
sSurname[sNameSz-1] = '\0';
str1 = line.substr( t2Pos+1 );
strncpy( sFirstname, str1.c_str(), sNameSz-1 );
sFirstname[sNameSz-1] = '\0';
sNoOfCourses = 0;
sWH = 0;
643

} // if ( !tin.eof . . .
} // Student::readFromText
:
\t
incomplete. ; -
. .
:
. , ,
. .
save() Course:
void Student::save( ostream& bout ) const
{
if ( bout.fail() )
throw StudentXptn( "save", StudentXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&sIdNum),
sizeof(sIdNum) ); //
bout.write( sSurname, sNameSz );
bout.write( sFirstname, sNameSz );
bout.write( reinterpret_cast<const char*>(&sNoOfCourses),
sizeof(sNoOfCourses) ); // . .
bout.write( reinterpret_cast<const char*>(&sWH), sizeof(sWH) );
//
if ( bout.fail() )
throw StudentXptn( "save", StudentXptn::cannotWrite );
} // Student::save
display() :
void Student::display( ostream& tout )
{
tout << sIdNum << '\t' << sSurname << '\t' << sFirstname
<< endl << sNoOfCourses << '\t' << sWH << endl;
} // Student::display
:
class Student
{
public:
unsigned int getIdNum() const { return sIdNum; }
void clearCourses() { sNoOfCourses = 0; sWH = 0; }
unsigned int getWH() const { return sWH; }
void add1Course( int aIncrWH );
void readFromText( istream& tin );
void save( ostream& bout ) const;
void display( ostream& tout );
private:
enum { sNameSz = 20 };
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
unsigned int sWH; //
unsigned int sNoOfCourses; //
}; // Student
:
struct StudentXptn
{
enum { incomplete, negIdNum, nonPosIncr,
fileNotOpen, cannotRead, cannotWrite };
char funcName[100];
int errorCode;
int errValue;
StudentXptn( char* mn, int ec, int ev = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec; errValue = ev; }
644 Project 03

}; // StudentXptn
:
typedef Student* PStudent;

Prj03.5 StudentInCourse
:
( , ) .
, set set.
enrllmnt.dta.
save.
, save() :
void StudentInCourse::save( ostream& bout ) const
{
if ( bout.fail() )
throw StudentInCourseXptn( "save", StudentInCourseXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&sicSIdNum), sizeof(sicSIdNum) );
//
bout.write( sicCCode, sicCCodeSz ); //
bout.write( reinterpret_cast<const char*>(&sicMark), sizeof(sicMark) );
//
if ( bout.fail() )
throw StudentInCourseXptn( "save",
StudentInCourseXptn::cannotWrite );
} // StudentInCourse::save
. -
.

.
,
.
: set.
,
.
set:
void StudentInCourse::setIdNumCCode( unsigned int aIdNum,
string aCCode,
Student stArr[], int nOfStudents,
Course crsArr[], int nOfCourses )
,
.
. -
:
void StudentInCourse::setIdNumCCode( Student& aStudent,
string aCCode,
Course crsArr[], int nOfCourses )
{
crsArr[nOfCourses].setCode( aCCode.c_str() );
int cPos( 0 );
while ( strcmp(crsArr[nOfCourses].getCode(),
crsArr[cPos].getCode())!=0 )
++cPos;
if ( cPos == nOfCourses )
throw StudentInCourseXptn( "StudentInCourse",
StudentInCourseXptn::unknownCCode,
aCCode.c_str() );
645

sicSIdNum = aStudent.getIdNum();
aStudent.add1Course( crsArr[cPos].getWH() );
strcpy( sicCCode, aCCode.c_str() );
crsArr[cPos].add1Student();
} // StudentInCourse::setIdNumCCode

, Course:
Course::setCode.
, :
class StudentInCourse
{
public:
void setIdNumCCode( Student& aStudent, string aCCode,
Course crsArr[], int nOfCourses );
void save( ostream& bout ) const;
void display( ostream& tout ) const;
private:
unsigned int sicSIdNum; //
char sicCCode[8]; //
}; // StudentInCourse
:
void StudentInCourse::display( ostream& tout ) const
{
tout << sicSIdNum << ' ' << sicCCode << endl;
} // StudentInCourse::display
:
struct StudentInCourseXptn
{
enum { unknownCCode };
char funcName[100];
int errorCode;
char errStrVal[100];
StudentInCourseXptn( const char* mn, int ec,
const char* sv="" )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // StudentInCourseXptn
:
typedef StudentInCourse* PStudentInCourse;

Prj03.6
.
. , ;
save . load
( .)
( main):
Course* crsArr;
unsigned int nOfCourses;
:
loadCourses( "gCourses.dta", crsArr, nOfCourses );
646 Project 03

Prj03.6.1 loadCourses()
loadCourses(); ,
crsArr. (
, ), crsArr == 0 nOfCourses == 0
. :
crsArr = 0; nOfCourses = 0;

if ( ) throw ...

if ( )
{ ; throw ... }
while ( )
{
if ( )
(renew)

cNoOfStudents
++nOfCourses;
} // while
MyTmpltLib.h ( )
// renew nf T
// ni (<= nf)
// ni p.
template< typename T >
void renew( T*& p, int ni, int nf )
. renew()
. -
cIncr (=10) .3 , resCourses, -
. , :
const int cIncr( 10 );
unsigned int resCourses; //
crsArr = 0; nOfCourses = 0;
try { crsArr = new Course[cIncr]; }
catch( bad_alloc )
{ throw ProgXptn( "loadCourses", ProgXptn::allocFailed ); }
resCourses = cIncr;
if ( ) :
if ( nOfCourses+1 == resCourses )
{
renew( crsArr, nOfCourses, resCourses+cIncr );
resCourses += cIncr;
}
+1, nOfCourses+1 == resCourses,
.
loadCourses():
void loadCourses( string flNm,
Course*& crsArr, unsigned int& nOfCourses )
{
// ()
const int cIncr( 10 );
unsigned int resCourses;
crsArr = 0; nOfCourses = 0;
try { crsArr = new Course[cIncr]; }
catch( bad_alloc )
{ throw ProgXptn( "loadCourses", ProgXptn::allocFailed ); }
resCourses = cIncr;
//

3 16.13.3.
647

istream bin( flNm.c_str(), ios_base::binary );


if ( bin.fail() )
{ delete[] crsArr; //
throw ProgXptn( "loadCourses", ProgXptn::cannotOpen, flNm.c_str() );
//
loadSylCourse( bin, crsArr[nOfCourses] );
while ( !bin.eof() )
{
++nOfCourses;
crsArr[nOfCourses-1].clearStudents();
if ( nOfCourses+1 == resCourses )
{
renew( crsArr, nOfCourses, resCourses+cIncr );
resCourses += cIncr;
} // if
loadSylCourse( bin, crsArr[nOfCourses] );
} // while
bin.close();
} // loadCourses

: -
: crsArr[nOfCourses] ( ).
( load()) nOfCourses (++nOfCourses)
.
load() , ,
cNoOfStudents.
catch CourseXptn.
(cannotRead fileNotOpen) (throw).

Prj03.6.2
enrllmnt.txt
.
. :
Student* stArr; unsigned int nOfStudents( 0 );
const int sIncr( 10 );
unsigned int resStudents;

StudentInCourse* sic; unsigned int nOfStdInCrs( 0 );


const int sicIncr( 30 );
unsigned int resStdInCrs;
:
try { stArr = new Student[sIncr]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
resStudents = sIncr;
try { sic = new StudentInCourse[scIncr]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
resStdInCrs = sicIncr;
enrllmnt.txt :
ifstream tin( "enrllmnt.txt" );
if ( tin.fail() )
throw ProgXptn( "main", ProgXptn::cannotOpen, "enrllmnt.txt" );

(log):
log.open( "log.txt" );
if ( log.fail() )
648 Project 03

throw ProgXptn( "main",


ProgXptn::cannotOpen, "log.txt" );

Prj03.6.3 . . .
readFromText(); ! readFrom-
Text() stArr , -
( .)
void readAStudent( istream& tin,
PStudent& stArr, unsigned int& nOfStudents,
unsigned int& resStudents, int sIncr )
{
if ( nOfStudents+1 == resStudents )
{
renew( stArr, nOfStudents, resStudents+sIncr );
resStudents += sIncr;
}
stArr[nOfStudents].readFromText( tin );
++nOfStudents;
stArr[nOfStudents-1].clearNoOfCourses();
stArr[nOfStudents-1].clearWH();
} // readAStudent
-
. :
.
-
.
.
readAStudent( tin,
stArr, nOfStudents, resStudents, sIncr );
if ( !tin.eof() )
{
int pos( 0 );
while ( stArr[pos].getIdNum() !=
stArr[nOfStudents-1].getIdNum() ) ++pos;
if ( pos < nOfStudents-1 ) //
{//
;
, noc,
noc .
( )):
void ignoreStudentData( istream& tin )
{
string str1;
getline( tin, str1, '\n' );
int noc( atoi(str1.c_str()) );
for ( int k(0); k < noc; ++k ) getline( tin, str1, '\n' );
} // ignoreStudentData
:
if ( pos < nOfStudents-1 ) //
{//
--nOfStudents;
ignoreStudentData( tin );
log << " multiple entry for student with id num "
<< stArr[pos].getIdNum() << endl;
}
else //
{ . . .
649

Prj03.6.4 . . .
; , :
for ( )
{

if ( )
log
else
{
( , )

sNoOfCourses sWH
cNoOfStudents
}
} // for
:
void readCourseCodes( istream& tin, Student& aStudent,
PCourse crsArr, int nOfCourses,
PStudentInCourse& sic, unsigned int& nOfStdInCrs,
unsigned int& resStdInCrs, int sicIncr,
ostream& log )
{
if ( !tin.eof() )
{
string str1;
getline( tin, str1, '\n' );
if ( !tin.eof() )
{
int noc( atoi(str1.c_str()) );
for ( int k(0); k < noc; ++k )
{
if ( nOfStdInCrs+1 == resStdInCrs )
{
renew( sic, nOfStdInCrs, resStdInCrs+sicIncr );
resStdInCrs += sicIncr;
}
getline( tin, str1, '\n' );
if ( !tin.eof() )
{
try
{
sic[nOfStdInCrs].setIdNumCCode( aStudent,
str1.c_str(),
crsArr,
nOfCourses );
++nOfStdInCrs;
}
catch( StudentInCourseXptn& x )
{
log << " student with id num "
<< aStudent.getIdNum()
<< " asking course " << str1 << endl;
}
} // if ( !tin.eof()...
} // for
}
}
} // readCourseCodes

Prj03.6.5 main
() main:
int main()
650 Project 03

{
PCourse crsArr; unsigned int nOfCourses;

PStudent stArr; unsigned int nOfStudents( 0 );


const int sIncr( 10 );
unsigned int resStudents;

PStudentInCourse sic; unsigned int nOfStdInCrs( 0 );


const int sicIncr( 30 );
unsigned int resStdInCrs;

ofstream log;
try
{
loadCourses( "gCourses.dta", crsArr, nOfCourses );

try { stArr = new Student[sIncr]; }


catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
resStudents = sIncr;
try { sic = new StudentInCourse[sicIncr]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
resStdInCrs = sicIncr;

log.open( "log.txt" );
if ( log.fail() )
throw ProgXptn( "main", ProgXptn::cannotOpen, "log.txt" );
ifstream tin( "enrllmnt.txt" );
if ( tin.fail() )
throw ProgXptn( "main", ProgXptn::cannotOpen, "enrllmnt.txt" );
while ( !tin.eof() )
{
readAStudent( tin, stArr, nOfStudents, resStudents, sIncr );
if ( !tin.eof() )
{
int pos( 0 );
while ( stArr[pos].getIdNum() !=
stArr[nOfStudents-1].getIdNum() ) ++pos;
if ( pos < nOfStudents-1 ) //
{//
--nOfStudents;
ignoreStudentData( tin );
log << " multiple entry for student with id num "
<< stArr[pos].getIdNum() << endl;
}
else //
{
readCourseCodes( tin, stArr[nOfStudents-1],
crsArr, nOfCourses,
sic, nOfStdInCrs, resStdInCrs,
sicIncr, log );
}
}
if ( !tin.eof() )
{
string str1;
getline( tin, str1, '\n' ); // blank line
}
} // while
tin.close();
for ( int k(0); k < nOfStudents; ++k )
{
if ( stArr[k].getWH() > 30 )
log << "student with id num " << stArr[k].getIdNum()
<< ": " << stArr[k].getWH() << " hours/week"
<< endl;
651

} // for
save1DTable( "Students.dta", stArr, nOfStudents );
save1DTable( "enrllmnt.dta", sic, nOfStdInCrs );
save1DTable( "gCourses.dta", crsArr, nOfCourses );
delete[] sic;
delete[] stArr;
delete[] crsArr;
} // try
catch( ProgXptn& x ) { . . . } // catch( ProgXptn
catch( MyLibXptn& x ) { . . . } // catch( MyLibXptn
catch( CourseXptn& x ) { . . . } // catch( CourseXptn
catch( StudentXptn& x ) { . . . } // catch( StudentXptn
catch( StudentInCourseXptn& x )
{ . . . } // catch( StudentInCourseXptn
catch( ... ) { . . . }
log.close();
} // main

30 () .
save1DTable() MyTmpltLib.h:
// save1DTable -- binary flNm n
// tbl.
// T::save( ostream& )
template < class T >
void save1DTable( string flNm, T tbl[], int n )
{
if ( tbl == 0 && n > 0 )
throw MyTmpltLibXptn( "save1DTable",
MyTmpltLibXptn::noArray );
ofstream bout( flNm.c_str(),
ios_base::binary|ios_base::trunc );
if ( bout.fail() )
throw MyTmpltLibXptn( "save1DTable",
MyTmpltLibXptn::cannotCreate,
flNm.c_str() );
for ( int k(0); k < n; ++k )
{
tbl[k].save( bout );
if ( bout.fail() )
throw MyTmpltLibXptn( "save1DTable",
MyTmpltLibXptn::cannotWrite,
flNm.c_str() );
}
bout.close();
} // save1DTable
log try, try
catch. ; -
log catch .
catch! (ProgXptn),
MyTmpltLibXptn, !

Prj03.7 char* string;


(); char* string; -
15.13.1 .
, string -
. , .
:
652 Project 03

string funcName :
-
.
() std::bad_alloc. ,
() -
.
Student
string sSurname;
string sFirstname;
save(); :
char local[sNameSz];
strncpy( local, sSurname.c_str(), sNameSz-1 ); local[sNameSz-1] = \0;
bout.write( local, sNameSz );
strncpy( local, sFirstname.c_str(), sNameSz-1 ); local[sNameSz-1] = \0;
bout.write( local, sNameSz-1 );
; 15.13.1 :
... string
; , () .
:
unsigned int len( sSurname.length() );
char* local( new char[len+1] );
strcpy( local, sSurname,c_str() );
bout.write( reinterpret_cast<const char*>(&len), sizeof(len) );
bout.write( local, len+1 );
delete[] local;
len = sFirstname,length();
local = new char[len+1];
strcpy( local, sFirstname );
bout.write( reinterpret_cast<const char*>(&len), sizeof(len) );
bout.write( local, len+1 );
.
-
.

char
string.
. , -
,
string bad_alloc!4

Prj03.8
StudentInCourse
void setIdNumCCode( Student& aStudent, string aCCode,
Course crsArr[], int nOfCourses );
, , :
StudentInCourse::StudentInCourse( Student& aStudent, string aCCode,
Course crsArr[], int nOfCourses )
// . . .
.

4 : .
string
653

crsArr Stu-
dentInCourse. StudentInCourse;
.
,
.
crsArr
StudentInCourse :
class StudentInCourse
{
public:
// . . .
private:
Course* crsArr;
unsigned int* pNOfCourses;
unsigned int sicSIdNum; //
char sicCCode[8]; //
}; // StudentInCourse
re-
new(). ...


Prj03-1 :
.
.
.
/ .
654 Project 03

20
-

:

C++.
:

.
:




this

:
20.1 : BString............................................................................................................... 658
20.1.1 ...............................................................................................................................................659
20.1.2 at()..........................................................................................................................................661
20.1.3 .................................................................................................................................................662
20.2 ....................................................................................................................... 662
20.3 private ...................................................................................................... 664
20.4 = .................................................................................................................... 664
20.4.1 assign() ............................................................................................................................................666
20.4.2 ..............................................................................................................667
20.5 this ..................................................................................................................................... 668
20.6 ; ............................................................................................................. 669
20.7 ................................................................................................. 669
20.7.1 .....................................................................................................................................670
20.7.2 ................................................................................................................................671
20.7.3 ............................................................................................................................................679
20.7.4 ..............................................................................................................................................681
20.7.5 , ................................................................................................................................683
20.8 ............................................................................................................................... 687
20.8.1 ...........................................................................................................................691
20.9 ... ................................................................................................................. 694
- ............................................................................................................................................. 695
.............................................................................................................................................................................695
.............................................................................................................................................................................695

655
656 20

.............................................................................................................................................................................695

:

. C++. -
(object oriented)
C++
.
(object) (operations)
(state).
-
(instance variables) .
.
(methods).
(interface) (behavior)
. (Wegner 1990)
(class); ,
.
. - (po-
tential)
(actual). -
- . -
(instance creation).
,
class Date
{ // I: (dYear > 0) && (0 < dMonth <= 12) &&
// (0 < dDay <= lastDay(dYear, dMonth))
public:
Date( int ay=1, int am=1, int ad=1 );
unsigned int getYear() const { return dYear; }
unsigned int getMonth()
const { return static_cast<unsigned int>( dMonth ); }
unsigned int getDay() const { return static_cast<unsigned int>( dDay ); }
void load( istream& bin );
void save( ostream& bout ) const;
private:
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;

bool isLeapYear( int y );


unsigned int lastDay( int y, int m );
}; // Date
Date.
I
Date. Date::dYear, Date::dMonth, Date::dDay
.
( ).
Date::lastDay() Date::leapYear() ; :
. -
.
:
Date d1( 2007, 5, 31 ), d2( 2004, 2, 29 );
, d1 d2.
- 657

()
d1.dYear, d1.dMonth d1.dDay 2007, 5 31 . -
-
private.
( )
d2.dYear, d2.dMonth d2.dDay 2004, 2 29
.
d1 : d1.getYear(), d1.getMonth(), d1.getDay(),
d1.load(istream&) d1.save(ostream&).
d1.
-
: (=). Date,
.
public .
Date.
(messages) -
, , : -
. -

. , d1 :
d1.load( bin );

bin.
:
Battery btr;
btr.powerDevice(double,double,bool&), btr.maxTime(
double ), btr.reCharge(). btr :
btr.powerDevice( 15*60, 4, ok );
btr , . ok
.
btr.maxTime(8) btr
.
, -
.
. . .
C++.
.
:

.
;
:
, .

.
658 20

20.1 : BString
-
. BString -
std::string. , BString -
string. BString -
() string.
-
char.
char* bsData;
' -
.1 ;
, , 100 char ()
BString. -
renew(): ,
, .
,
, .
,
, .
, -
, , ...
: 100 , 99
1+2+ ... +99 = 4950 .
, , 1
50, 2 , 1
50 .
-
.2
size_t bsReserved;
.
:
16 . 16; .
. , -
, ,
.
(), BString, -
;
, , '\0'
. : string
c_str() C,
char '\0' . '\0'
.

1 . 2 16.13.
2 C++
. , , :
.
( 16.13.3).
- 659

: s1
, bsLen, bsData | abc
. bsLen 3
bsReserved 16

:
. 20-1 -
char* bsData;
s1 BString (bsIncr = 16.)
char* bsEnd;

.

\0 .
(. 20-1).
class BString
{
public:
// ...
private:
enum { bsIncr = 16 };
char* bsData;
size_t bsLen;
size_t bsReserved;
}; // BString
bsIncr; 16. ,
16
,
.
:
(0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
bsLen < bsReserved (\0)
.
:
struct BStringXptn
{
enum { . . . };
char funcName[100];
int errorCode;
int errorValue;
BStringXptn( char* mn, int ec, int ev = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = \0;
errorCode = ec; errorValue = ev; }
}; // BStringXptn

20.1.1
c_str:
const char* c_str() const
{ bsData[bsLen] = '\0'; return bsData; }
. const
, bsData,
.
! \0
c_str str
\0.
660 20

:
const '\0'
(bsData[bsLen]). bsData (), bsLen,
bsReserved. bsData -

const char* bsData;
,
const. ...
length():
size_t length() const { return bsLen; }
empty():
bool empty() const { return ( bsLen == 0 ); }
:
c_str getData
length getLen.
empty() (predicate). isEmpty -
string.
:
string , length(), size().
; :
size_t size() const { return bsLen; }
! . :
size_t size() const { return length(); }
: size() length()
size(). ,
.
.
, .

. :
BString s0;
s0 .
BString::BString()
{
try { bsData = new char[bsIncr]; }
catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
bsReserved = bsIncr;
bsLen = 0;
} // BString::BString
, -
, bad_alloc BStringXptn (allocFailed).
: C (
char '\0'):
BString s1( "abc" );
:
BString( const char* rhs );
:
BString::BString( const char* rhs )
{
- 661

bsLen = cStrLen( rhs );


bsReserved = ((bsLen+1)/bsIncr+1)*bsIncr;

try { bsData = new char [bsReserved]; }


catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
for ( int k(0); k < bsLen; ++k ) bsData[k] = rhs[k];
} // BString::BString
:
BString( const char* rhs="" );
2 1 .
:
1.
:3
size_t BString::cStrLen( const char cs[] )
{
const char* p( cs );
while ( *p != '\0' ) ++p;
return p-cs;
} // BString::cStrLen
'\0'.
strlen; C.
.
2. ;
bsIncr == 16 .
16
bsLen+1 ( ).
3. BStringXptn::allocFailed .
:
enum { allocFailed };

20.1.2 at()
, at,
. 10.10:
:
if ( s3.at(0) == '' ) s3.at( 0 ) = '';
,
, .
out_of_range
stdexcept. :
#include <iostream>
#include <stdexcept>
#include <string>

using namespace std;

int main()
{
string s3( "abc" );

try
{
s3.at( 7 ) = '@';

3 ; myStrLen . 1 12.3.3.
662 20

}
catch( out_of_range& x )
{
cout << "out_of_range" << endl;
}
}
: s3 BString, s3.at(m)
s3.bsData[m]
. ; 13.4 :
int&
(-l) .
:
char& BString::at( int k ) const
{
if ( k < 0 || bsLen <= k )
throw BStringXptn( "at", BStringXptn::outOfRange, k );
return bsData[k];
} // BString::at
char&
bsData[k] char.
at BStringXptn ( outOfRange).
: at
.

.
const.

20.1.3
:
BString.
;
() bsData .
(destructor) . ,
,
~, :
BString::~BString()
{
delete[] bsData;
} // BString::~BString
, , .

20.2
:
BString s1( "abc" );
cout << "s1: " << s1.c_str() << endl;

BString s2( s1 ), s3( s1.c_str() );


cout << "s2: " << s2.c_str() << endl;
cout << "s3: " << s3.c_str() << endl;
:
s1: abc
s2: abc
- 663

s3: abc
s1
: bsData | abc
bsLen 3
bsReserved 16
BString s2 = s1,
s3 = s1.c_str(); bsData
bsLen 3
bsReserved 16
. s2
. -
s3 . 20-2
s1. : s1 s2 BString s2(s1));
s1.at( 1 ) = 'v';
cout << "s1: " << s1.c_str() << endl;
cout << "s2: " << s2.c_str() << endl;
cout << "s3: " << s3.c_str() << endl;
:
s1: avc
s2: avc
s3: abc
s1 s2; . 20-2
:
(s2)
s1. s1.bsData s2.bsData
.
-
16.8 . . ; -
s3: -
, -
(copy constructor), -
( : s2) ( :
s1):
BString::BString( const BString& rhs )
{
bsReserved = rhs.bsReserved;

try { bsData = new char[bsReserved]; }


catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
for ( int k(0); k < rhs.bsLen; ++k )
bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
} // BString::BString
. -
:
( : s2) bsData,
bsLen bsReserved, rhs ( : s1)
rhs.bsData, rhs.bsLen rhs.bsReserved.
;
rhs.bsReserved. . :
() .
664 20

20.3 private

: (rhs)
private. :
T -
.

20.4 =
:
BString s1( "abc" ), s2;
:
cout << "s1: " << s1.c_str() << endl;

s2 = s1;
cout << "s2: " << s2.c_str() << endl;

s1.at( 1 ) = 'v';
cout << "s1: " << s1.c_str() << endl;
cout << "s2: " << s2.c_str() << endl;
:
s1: abc
s2: abc
s1: avc
s2: avc
-
.
: (. 20-3).
s2
s1.
s1.bsData s2.bsData
.
s2.bsData s2.

.
BString
.
14.6.3.

s1 s1
bsData | abc bsData | abc
bsLen 3 bsLen 3
bsReserved 16 bsReserved 16

bsData bsData
bsLen 0 bsLen 3
bsReserved 16 bsReserved 16
s2 s2
() ()

. 20-3 () s1 s2
. () s1 s2
. , -
s2.
- 665

:
BString s1( "abc" ), s2, s3;

s2 = s1;
s2 s1
s2 , , -
: s3 = (s2 = s1). ;
14.6.4 (
): :
BString& operator=( const BString& rhs );
;


rhs

;

(
.)
:
.

if ( ) throw

rhs
return
: (
) s1 = s1; , bsData rhs.bsData .
! -
, , -
:
if ( ! )
{

if ( ) throw

rhs
}
return
:
;
return ;
this,
. () , this
. :
&rhs == this.
return :
return *this;
C++ :
. , s2 =
s1 s2.operator=(s1).
666 20

if ( ! ) :
if ( &rhs != this )
if () throw
:
char* tmp;
try { tmp = new char[rhs.bsReserved]; }
catch( bad_alloc& )
{ throw BStringXptn( "operator=", BStringXptn::allocFailed ); }
(tmp). , -
, bad_alloc
BStringXptn (allocFailed).
.

delete[] bsData;
rhs
bsData = tmp;
bsReserved = rhs.bsReserved;
for ( int k(0); k < rhs.bsLen; ++k )
bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
= :
BString& BString::operator=( const BString& rhs )
{
if ( &rhs != this ) // if ( ! )
{
//
char* tmp;
try { tmp = new char[rhs.bsReserved]; }
catch( bad_alloc& )
{ throw BStringXptn( "operator=", BStringXptn::allocFailed ); }
//
delete[] bsData;
// rhs
bsData = tmp;
bsReserved = rhs.bsReserved;
for ( int k(0); k < rhs.bsLen; ++k ) bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
}
return *this;
} // BString::operator=
, , :
s1: abc
s2: abc
s1: avc
s2: abc

20.4.1 assign()
(std::)string assign() opera-
tor=(). operator=().
BString& BString::assign( const BString& rhs )
{
if ( &rhs != this ) // if ( ! )
{
//
char* tmp;
try { tmp = new char[rhs.bsReserved]; }
catch( bad_alloc& )
- 667

{ throw BStringXptn( "assign", BStringXptn::allocFailed ); }


//
delete[] bsData;
// rhs
bsData = tmp;
bsReserved = rhs.bsReserved;
for ( int k(0); k < rhs.bsLen; ++k )
bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
}
return *this;
} // BString::assign
-
length() size(): assign() opera-
tor=() inline :
class BString
{
public:
// . . .
BString& operator=( const BString& rhs );
BString& assign( const BString& rhs ) { return (*this = rhs); }
// . . .
private:
// . . .
}; // BString
copy/paste. ; -
,
.
operator= assign(); ,
...

20.4.2
:
std:string s0;
:
s0 = "what\'s this\?"; cout << " s0: " << s0 << endl;
:
s0: what's this?
BString ()-
= :
BString& operator=( const char* rhs );

BString s2;

s2 = "what\'s this\?"; cout << "s2: " << s2.c_str() << endl;
:
s2: what's this?
; , -
=, : ( ) -
( ) (2.2,
11.3). , :
s2 = static_cast<BString>( "what\'s this\?" );
, :
668 20

s2 = BString( "what\'s this\?" );


const char* BString -
(2 1) . ()
:
BString::BString( const char* rhs )
{
cout << "In default constructor; rhs: " << rhs << endl;
bsLen = cStrLen( rhs );
bsReserved = ((bsLen+1)/bsIncr+1)*bsIncr;

try { bsData = new char [bsReserved]; }


catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
for ( int k(0); k < bsLen; ++k ) bsData[k] = rhs[k];
} // BString::BString
:
In default constructor; rhs:
In default constructor; rhs: what's this?
s2: what's this?
s2 .

20.5 this
, , -
- . ;
, , ,
. , -
() , ..:
reinterpret_cast<BString*>( &bsData )
, -
(15.6)
. s1 s2
C++ . -
-
this (. 20-4). s1.this s2.this

this . . 20-4 this -
. this
, ,

: . ! s1.this
class AClass s2.this
{ -
public:
// . . .
void printthis() .
{ cout << this; }
// . . .
private:
// . . .
};
:
AClass a, b;
:
a.printthis(); cout << " " << &a << endl;
b.printthis(); cout << " " << &b << endl;
- 669

, this a a.
b. :
0x0064fdfc 0x0064fdfc
0x0064fdf4 0x0064fdf4
a this a. b.

20.6 ;
(=) at() :
:
= .
at() .
. ;
: x = y = z x = (y = z)
(x = y) = z x y ( ).

. , , -
.
at() - -

.
, const . :4
const.

C++ (C) ( =)
std::string ( at()). ,
BString (
) .

20.7
-
. :
-
. ,
(.. -
). ( ).5
. -
km .
.
. -

4 OBJ35 (CERT 2009) : Do not return references to private data :


,
.
5 , . -
(15.5.1).
670 20

. , Route,
.
kvadra.txt
( \t (tab)):
102
\t\t
1 . \t22.1\t3.2
2 . \t22.6\t3.2
. . .
\t34.5\t5
1 \t26.7\t4
. . .

Route. :
1. ,
25.5 km 3.7.
2. .
3. kvadranew.txt -
.

20.7.1
.
:
class RouteStop
{
public:
// . . .
private:
string sName; //
float sDist; // km
float sFare; //
}; // RouteStop
class struct;
sDist 0 sFare 0
.
. :
RouteStop( string aName="", float aDist=0, float aFare=0 );
:
RouteStop::RouteStop( string aName, float aDist, float aFare )
{
if ( aName.empty() && (aDist > 0 || aFare > 0) )
throw RouteStopXptn( "RouteStop", RouteStopXptn::noName );
if ( aDist < 0 )
throw RouteStopXptn( "RouteStop",
RouteStopXptn::negDist, aDist );
if ( aFare < 0 )
throw RouteStopXptn( "RouteStop",
RouteStopXptn::negFare, aFare );
sName = aName;
sDist = aDist;
sFare = aFare;
} // RouteStop::RouteStop
: / -
. :
sName.empty() sDist == 0 sFare == 0
- 671

! oneStop :
RouteStop oneStop;

; :

.
-
.
RouteStop ( ):
struct RouteStopXptn
{
enum { noName, negDist, negFare };
char funcName[100];
unsigned int errCode;
float errVal;
RouteStopXptn( const char* fn, int ec, float ev=0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errVal = ev; }
}; // RouteStopXptn
:
BString
BStringXptn allocFailed. ,
Prj03.7: string
std::bad_alloc.
,
RouteStop string sName (std::) bad_alloc.
; ( )! !

20.7.2
Route :
class Route
{
public:
// . . .
private:
unsigned int rCode; //
string rFrom; //
string rTo; //
string rInBetween; //
RouteStop* rAllStops; //
unsigned int rNoOfStops; //
}; // Route
rAllStops .
BString: ,
unsigned int rReserved; //
.
, 10, 20, 30. 5
:
enum { rIncr = 5 }; // ""
// rAllStops
672 20

20.7.2.1
; rCode 0 -
:
(0 rNoOfStops < rReserved) && (rReserved % rIncr == 0)
: .
. ,
: -
. -
:
( j, k: 0..rNoOfStops-1 (j k rAllStops[j].sName rAllStops[k].sName) &&
( j, k: 0..rNoOfStops-1 (j k rAllStops[j].sDist rAllStops[k].sDist) &&
( j, k: 0..rNoOfStops-1 (rAllStops[j].sDist > rAllStops[k].sDist)
(rAllStops[j].sFare rAllStops[k].sFare))
:
;
-
( ),
-
( ),
.

:
k: 1..rNoOfStops-1 (rAllStops[k-1].sDist < rAllStops[k].sDist
aStop
rAllStops[k-1].sDist < aStop.sDist < rAllStops[k].sDist
k
:
rAllStops[k-1].sFare aStop.sFare rAllStops[k].sFare
:
k 0 ( )
;
k rNoOfStops ( )
;

. :
1..rNoOfStops.
0
rAllStops[0].sDist == 0 && rAllStops[0].sFare == 0
rNoOfStops+1 :
rAllStops[rNoOfStops+1].sDist == FLT_MAX &&
rAllStops[rNoOfStops+1].sFare == FLT_MAX
rNoOfStops rReserved:
(0 rNoOfStops rReserved-2) && (rReserved % rIncr == 0)
, :
I ID && II
( !)
ID (rCode 0) &&
( j, k: 1..rNoOfStops (j k rAllStops[j].sName rAllStops[k].sName) &&
( j, k: 1..rNoOfStops (j k rAllStops[j].sDist rAllStops[k].sDist) &&
- 673

( j, k: 1..rNoOfStops (rAllStops[j].sDist > rAllStops[k].sDist)


(rAllStops[j].sFare rAllStops[k].sFare))
(business rules)
:
( 0
: Route oneStop).

.
.
(sName) (sDist).
II (0 rNoOfStops rReserved-2) && (rReserved % rIncr == 0) &&
( k: 1..rNoOfStops-1 (rAllStops[k+1].sDist > rAllStops[k].sDist) &&
(rAllStops[0].sDist == 0 && rAllStops[0].sFare == 0) &&
(rAllStops[rNoOfStops+1].sDist == FLT_MAX &&
rAllStops[rNoOfStops+1].sFare == FLT_MAX)
.

. :
II
( k: 1..rNoOfStops-1 (rAllStops[k+1].sDist > rAllStops[k].sDist)
ID
( j, k: 1..rNoOfStops (j k rAllStops[j].sDist rAllStops[k].sDist)
-
.

20.7.2.2
. :
Route( int rc=0 );
:
Route::Route( int rc )
{
if ( rc < 0 )
throw RouteXptn( "Route", RouteXptn::negCode, rc );
rCode = rc;
try
{
rReserved = rIncr;
rAllStops = new RouteStop[ rReserved ];
rNoOfStops = 0;
rAllStops[0] = RouteStop( "guard0", 0.0, 0.0 ); //
rAllStops[rNoOfStops+1] = RouteStop( "guardPte", FLT_MAX, FLT_MAX );
rFrom = "";
rTo = "";
rInBetween = "";
}
catch( bad_alloc& )
{
throw RouteXptn( "Route", RouteXptn::allocFailed );
}
} // Route::Route
, BString
char.
.
674 20

20.7.2.3
rFrom, rTo rInBetween (
). inline:
void setFrom( string aName ) { rFrom = aName; }
void setTo( string aName ) { rTo = aName; }
void setInBetween( string aName ) { rInBetween = aName; }

-
:
void Route::clearRouteStops()
{ rAllStops[1] = rAllStops[rNoOfStops+1];
rNoOfStops = 0; }
-
rReserved.

20.7.2.4
:
, .6 -
deleteRouteStop() :
// I
aRoute.deleteRouteStop( stopName );
// I && ( aRoute stopName)
:
void Route::deleteRouteStop( string stopName )
{
if ( stopName ndx )
{
ndx
--rNoOfStops;
}
}
, :
if ( stopName ndx )
{

rAllStops[ndx+1] ... rAllStops[rNoOfStops+1]

rAllStops[ndx] ... rAllStops[rNoOfStops];
--rNoOfStops;
}

int Route::findNdx( const string& aName ) const
{
rAllStops[rNoOfStops+1].setName( aName );
int ndx( 1 );
while ( rAllStops[ndx].getName() != aName ) ++ndx;
if ( ndx > rNoOfStops ) ndx = -1;
return ndx;
} // Route::findNdx
sName aName 1
deleteRouteStop() :

6 A x
: A = A \ { x } ( =
).
- 675

void Route::deleteRouteStop( string stopName )


{
int ndx( findNdx(stopName) );
if ( ndx >= 0 )
{
try { erase1RouteStop( ndx ); }
catch( bad_alloc& )
{ throw RouteXptn( "deleteRouteStop",
RouteXptn::allocFailed ); }
}
} // Route::deleteRouteStop

void Route::erase1RouteStop( int ndx )


{
for ( int k(ndx); k <= rNoOfStops; ++k )
rAllStops[k] = rAllStops[k+1];
--rNoOfStops;
} // Route::erase1RouteStop
ndx -
.
. -
private.
try/catch ;
: rAllStops[k] = rAllStops[k+1] erase1RouteStop()
bad_alloc!
H deleteRouteStop()

. -
.
:7
bool Route::find1RouteStop( string stopName )
{
return ( findNdx(stopName) >= 0 );
} // Route::find1RouteStop
findNdx(); findNdx()
.
. public -
(19.3.1). ..
findNdx().
:
public find1RouteStop().
private findNdx() -
(.. lastDay()).
:
findNdx().
1. findNdx() RouteStop: setName()
getName().
2. ,
... [] .
aRoute Route
RouteStop aRoute.rAllStops[rNoOfStops+1] setName().

7 find1RouteStop() x A.
676 20

aRoute.rAllStops
RouteStop getName().
: , -
addRouteStop() :
// I
aRoute.addRouteStop( aStop );
// I && ( aRoute aStop)
:8
(aStop.sName)
rAllStops[ndx]
(aStop.sDist). ; ;
aStop.sDist == rAllStops[ndx].sDist.
:
int nmNdx( findNdx(aStop.getName()) );
nmNdx 1, ; -
:
aStop.sDist == rAllStops[nmNdx].sDist aStop.sFare == rAllStops
[nmNdx].sFare aRoute aStop -
! (: ,
.)
, aStop.sDist != rAllStops[nmNdx].sDist aStop.
sFare != rAllStops[nmNdx].sFare
.
:
int nmNdx( findNdx(aStop.getName()) );
if ( nmNdx > 0 ) // name found
{
if ( rAllStops[nmNdx].getDist() != aStop.getDist() ||
rAllStops[nmNdx].getFare() != aStop.getFare() )
throw RouteXptn( "addRouteStop",
RouteXptn::invalidArgument,
rAllStops[nmNdx], aStop );
}

(aStop.sDist) . -
. sDist
binSearch()
9.6

template < class T >
unsigned int binSearch( const T v[], int last, const T& x )
< RouteStop :
bool operator<( const RouteStop& lhs, const RouteStop& rhs )
{
return ( lhs.getDist() - rhs.getDist() < 0 );
} // operator<( const RouteStop
binSearch()
:
else // name not found
{

8 insert1RouteStop() : A = A { x }.
- 677

int distNdx( binSearch(rAllStops, rNoOfStops, aStop) );


if ( rAllStops[distNdx].getDist() == aStop.getDist() )
throw RouteXptn( "addRouteStop", RouteXptn::diffName,
rAllStops[distNdx], aStop );
:
rAllStops[distNdx-1].getDist() < aStop.getDist() rAllStops[distNdx].getDist()
-
. :
rAllStops[distNdx-1].getFare() aStop.getFare() rAllStops[distNdx].getFare()
if ( rAllStops[distNdx-1].getFare() > aStop.getFare() )
throw RouteXptn( "addRouteStop", RouteXptn::fareErr,
rAllStops[distNdx-1], aStop );
if ( aStop.getFare() > rAllStops[distNdx].getFare() )
throw RouteXptn( "addRouteStop", RouteXptn::fareErr,
aStop, rAllStops[distNdx] );
.
:
if ( rReserved <= rNoOfStops+2 )
{
try { renew( rAllStops, rNoOfStops+2, rReserved+rIncr );
rReserved += rIncr; }
catch( MyTmpltLibXptn& )
{ throw RouteXptn( "addRouteStop",
RouteXptn::allocFailed ); }
}
if: !S
S rReserved > rNoOfStops+2
: .
renew()
rNoOfStops+2 .
:

rAllStops[distNdx] ... rAllStops[rNoOfStops+1]

rAllStops[distNdx+1] ... rAllStops[rNoOfStops+2];
rAllStops[distNdx] = aStop;
++rNoOfStops;
9 distNdx.
:
for ( int k(rNoOfStops+1); k >= distNdx; --k )
rAllStops[k+1] = rAllStops[k];
rAllStops[distNdx] = aStop;
++rNoOfStops;
, !
void Route::addRouteStop( const RouteStop& aStop )
{
int nmNdx( findNdx(aStop.getName()) );
if ( nmNdx > 0 ) // name found
{
if ( rAllStops[nmNdx].getDist() != aStop.getDist() ||
rAllStops[nmNdx].getFare() != aStop.getFare() )
throw RouteXptn( "addRouteStop",
RouteXptn::invalidArgument,
rAllStops[nmNdx], aStop );
}
else // name not found

9 ! ; ...
678 20

{
int distNdx( binSearch(rAllStops, rNoOfStops, aStop) );
if ( rAllStops[distNdx].getDist() == aStop.getDist() )
throw RouteXptn( "insert1RouteStop", RouteXptn::diffName,
rAllStops[distNdx], aStop );
if ( rAllStops[distNdx-1].getFare() > aStop.getFare() )
throw RouteXptn( "insert1RouteStop", RouteXptn::fareErr,
rAllStops[distNdx-1], aStop );
if ( aStop.getFare() > rAllStops[distNdx].getFare() )
throw RouteXptn( "insert1RouteStop", RouteXptn::fareErr,
aStop, rAllStops[distNdx] );
insert1RouteStop( aStop, distNdx );
}
} // Route::addRouteStop

void Route::insert1RouteStop( const RouteStop& aStop,


int distNdx )
{
if ( rReserved <= rNoOfStops+2 )
{
try { renew( rAllStops, rNoOfStops+2, rReserved+rIncr );
rReserved += rIncr; }
catch( MyTmpltLibXptn& )
{ throw RouteXptn( "insert1RouteStop", RouteXptn::allocFailed ); }
}
for ( int k(rNoOfStops+1); k >= distNdx; --k )
{
try { rAllStops[k+1] = rAllStops[k]; }
catch( bad_alloc& )
{ throw RouteXptn( "insert1RouteStop", RouteXptn::allocFailed ); }
}
rAllStops[distNdx] = aStop;
++rNoOfStops;
} // Route::insert1RouteStop
insert1RouteStop(), erase1RouteStop(), private.
, :
if ( oneRoute.find1RouteStop("") )
cout << " " << endl;
else
oneRoute.addRouteStop( RouteStop("", 25.5, 3.7) );
, addRouteStop()
RouteStop: getDist() getFare().
:
-
. modify1RouteStop() -
; addRouteStop(), -
. ;
if ( )
{
tmp
tmp

tmp
}

tmp.
const RouteStop& Route::get1RouteStop( string stopName ) const
{
int ndx( findNdx(stopName) );
if ( ndx < 0 )
throw RouteXptn( "get1RouteStop", RouteXptn::notFound,
- 679

stopName.c_str() );
return rAllStops[ndx];
} // Route::get1RouteStop
:
if ( !oneRoute.find1RouteStop("") )
cout << " " << endl;
else if ( oneRoute.find1RouteStop("") )
cout << " " << endl;
else
{
RouteStop tmp( oneRoute.get1RouteStop("") );
oneRoute.deleteRouteStop( "" );
oneRoute.addRouteStop( RouteStop("",
tmp.getDist(),
tmp.getFare()) );
}
:
get1RouteStop RouteStop& const RouteStop&

.
oneRoute.get1RouteStop("")
oneRoute.find1RouteStop("") . ,
get1RouteStop find1RouteStop
.

20.7.3
Route.h :
#ifndef _ROUTE_H
#define _ROUTE_H

#include <string>
#include <new>

#include "RouteStop.h"

using namespace std;

class Route
{
public:
Route( int rc=0 );
~Route() { delete[] rAllStops; }
void setFrom( string aName ) { rFrom = aName; }
void setTo( string aName ) { rTo = aName; }
void setInBetween( string aName ) { rInBetween = aName; }
bool find1RouteStop( string stopName ) const;
const RouteStop& get1RouteStop( string stopName ) const;
void addRouteStop( const RouteStop& aStop );
void deleteRouteStop( string stopName );
void writeToText( ostream& tout ) const;
private:
enum { rIncr = 5 }; // ""
// rAllStops
unsigned int rCode; //
string rFrom; //
string rTo; //
string rInBetween; //
RouteStop* rAllStops; //
unsigned int rNoOfStops; //
unsigned int rReserved; //
680 20

// 5
int findNdx( const string& aName ) const;
void insert1RouteStop( const RouteStop& aStop, int distNdx );
void erase1RouteStop( int ndx );
}; // Route

struct RouteXptn
{
enum { negCode, allocFailed, invalidArgument, notFound,
diffName, fareErr };
char funcName[100];
unsigned int errCode;
int errIntVal;
RouteStop errStop1, errStop2;
char errStrVal[100];
RouteXptn( const char* fn, int ec, int ev=0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errIntVal = ev; }
RouteXptn( const char* fn, int ec, const char* astr )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
strncpy( errStrVal, astr, 99 ); errStrVal[99] = '\0'; }
RouteXptn( const char* fn, int ec,
const RouteStop& aStop1, const RouteStop& aStop2 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec;
errStop1 = aStop1; errStop2 = aStop2; }
}; // RouteXptn

#endif // _ROUTE_H
writeToText() :
void Route::writeToText( ostream& tout ) const
{
tout << rCode << endl;
tout << rFrom << '\t' << rTo << '\t' << rInBetween << endl;
for ( int k(1); k <= rNoOfStops; ++k )
{ rAllStops[k].writeToText( tout ); tout << endl; }
} // Route::writeToText
, writeToText() RouteStop.
RouteStop.h :
#ifndef _ROUTESTOP_H
#define _ROUTESTOP_H

#include <string>
#include <new>

using namespace std;

class RouteStop
{
public:
RouteStop( string aName="", float aDist=0, float aFare=0 );
string getName() const { return sName; }
float getDist() const { return sDist; }
float getFare() const { return sFare; }
void setName( string aName );
void writeToText( ostream& tout ) const;
private:
string sName; //
float sDist; // km
float sFare; //
}; // RouteStop

struct RouteStopXptn
{
- 681

enum { noName, negDist, negFare };


char funcName[100];
unsigned int errCode;
double errVal;
RouteStopXptn( const char* fn, int ec, double ev=0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errCode = ec; errVal = ev; }
}; // RouteStopXptn

bool operator<( const RouteStop& lhs, const RouteStop& rhs );


bool operator>=( const RouteStop& lhs, const RouteStop& rhs );

#endif //_ROUTESTOP_H
writeToText() :
void RouteStop::writeToText( ostream& tout ) const
{
tout << sName << '\t' << sDist << '\t' << sFare;
} // RouteStop::writeToText
operator< ( >= !<)
bool operator<( const RouteStop& lhs, const RouteStop& rhs )
{
return ( lhs.getDist() - rhs.getDist() < 0 );
} // operator<( const RouteStop

bool operator>=( const RouteStop& lhs, const RouteStop& rhs )


{
return ( !(lhs < rhs) );
} // operator>=( const RouteStop

20.7.4
:
#include <iostream>
#include <fstream>
#include <string>

#include "Route.cpp"

using namespace std;

void readFromText( RouteStop& aStop, istream& tin );

int main()
{
try
{
ifstream tin( "kvadra.txt" );
string name, buf;
double dist, fare;

getline( tin, buf, '\n' );

Route oneRoute( atoi(buf.c_str()) );

getline( tin, name, '\t' ); oneRoute.setFrom( name );


getline( tin, name, '\t' ); oneRoute.setTo( name );
getline( tin, name, '\n' ); oneRoute.setInBetween( name );

RouteStop oneStop;
readFromText( oneStop, tin );
while ( !tin.eof() )
{
oneRoute.addRouteStop( oneStop );
readFromText( oneStop, tin );
682 20

} // while
tin.close();

if ( oneRoute.find1RouteStop("") )
cout << " " << endl;
else
oneRoute.addRouteStop( RouteStop("", 25.5, 3.7) );

if ( !oneRoute.find1RouteStop("") )
cout << " " << endl;
else if ( oneRoute.find1RouteStop("") )
cout << " " << endl;
else
{
RouteStop tmp( oneRoute.get1RouteStop("") );
oneRoute.deleteRouteStop( "" );
oneRoute.addRouteStop( RouteStop("",
tmp.getDist(),
tmp.getFare()) );
}
ofstream tout( "kvadranew.txt" );
oneRoute.writeToText( tout );
tout.close();
}
catch( RouteStopXptn& x )
{
switch ( x.errCode )
{
case RouteStopXptn::noName:
cout << "bus stop name cannot be empty in "
<< x.funcName << endl;
break;
case RouteStopXptn::negDist:
cout << "bus stop distance from start (" << x.errVal
<< ") cannot be negative in " << x.funcName
<< endl;
break;
case RouteStopXptn::negFare:
cout << "fare from start to bus stop (" << x.errVal
<< ") cannot be negative in " << x.funcName
<< endl;
break;
default:
cout << "unexpected RouteStopXptn exception from "
<< x.funcName << endl;
}
}
catch( RouteXptn& x )
{
switch ( x.errCode )
{
case RouteXptn::negCode:
cout << "negative Route code (" << x.errIntVal
<< ") in " << x.funcName << endl;
break;
case RouteXptn::allocFailed:
cout << "out of memory in " << x.funcName << endl;
break;
case RouteXptn::invalidArgument:
case RouteXptn::diffName:
cout << "trying to insert bus stop (";
x.errStop2.writeToText( cout );
cout << ") over existing (";
x.errStop1.writeToText( cout );
cout << endl;
break;
case RouteXptn::notFound:
- 683

cout << "no stop " << x.errStrVal << " requested by "
<< x.funcName << endl;
break;
case RouteXptn::fareErr:
cout << "inserting (";
x.errStop2.writeToText( cout );
cout << ") violates increasing fare principle (";
x.errStop1.writeToText( cout );
cout << endl;
break;
default:
cout << "unexpected RouteXptn exception from "
<< x.funcName << endl;
}
}
} // main
:
void readFromText( RouteStop& aStop, istream& tin )
{
string name;
getline( tin, name, '\t' );
if ( !tin.eof() )
{
string buf;
getline( tin, buf, '\t' );
float dist( atof(buf.c_str()) );
getline( tin, buf, '\n' );
float fare( atof(buf.c_str()) );
aStop = RouteStop( name, dist, fare );
}
} // readFromText
; ...

20.7.5 ,
1.
RouteStop Route:
class Route
{
public:
class RouteStop
{
public:
// . . .
private:
// . . .
}; // RouteStop

struct RouteStopXptn
{
// . . .
}; // RouteStopXptn

// . . .
private:
// . . .
}; // Route

bool operator<( const Route::RouteStop& lhs,


const Route::RouteStop& rhs );
bool operator>=( const Route::RouteStop& lhs,
const Route::RouteStop& rhs );
:
684 20

RouteStop Route::RouteStop
RouteStopXptn Route::RouteStopXptn
18.5.
, , :
Route::RouteStop::RouteStop( string aName,
float aDist, float aFare )
{
if ( aName.empty() && (aDist > 0 || aFare > 0) )
throw Route::RouteStopXptn( "RouteStop",
Route::RouteStopXptn::noName );
if ( aDist < 0 )
throw Route::RouteStopXptn( "RouteStop",
Route::RouteStopXptn::negDist, aDist );
if ( aFare < 0 )
throw Route::RouteStopXptn( "RouteStop",
Route::RouteStopXptn::negFare, aFare );
sName = aName;
sDist = aDist;
sFare = aFare;
} // Route::RouteStop::RouteStop
, throw , ..:
throw RouteStopXptn( "RouteStop",
Route::RouteStopXptn::noName );
main :
Route::RouteStop oneStop;
// . . .
oneRoute.addRouteStop( Route::RouteStop("",
25.5, 3.7) );
// . . .
Route::RouteStop tmp( oneRoute.get1RouteStop("") );
// . . .
oneRoute.addRouteStop(
Route::RouteStop( "",
tmp.getDist(), tmp.getFare()) );
// . . .
,
RouteStop public.
; : -

.
: RouteStop Route ;
,

( ).
.
2. readFromText
readFromText() RouteStop .
; .
(. 20-5) readFromText()
readFromText() Route. . 10-8.10
3.

:
try

10 ;
- 685

{
oneRoute.addRouteStop( RouteStop("", 25.5, 3.7) );

RouteStop tmp( oneRoute.get1RouteStop("") );


oneRoute.deleteRouteStop( "" );
oneRoute.addRouteStop( RouteStop("",
tmp.getDist(),
tmp.getFare()) );
}
catch( RouteXptn& x )
{
switch ( x.errCode )
{
case RouteXptn::invalidArgument:
cout << " " << x.errStop2.getName()
<< " " << endl;
break;
case RouteXptn::diffName:
cout << " "
<< x.errStop2.getDist() << " km "
<< x.errStop2.getName() << endl;
break;
case RouteXptn::notFound:
cout << " " << x.errStrVal << " "
<< endl;
break;
default:
throw;
} // switch
} // catch
try-catch try! ! try
if. catch
RouteXptn : invalidArgument, diffName notFound.
: ( default)
catch.
4.
.
< RouteStop
:11
(a == b) ((a.sDist - b.sDist) == 0)
sDist.
sName. sDist .
:
RouteStop( "", 25.6, 3.7 )

RouteStop( "", 25.5, 3.7 )
100 m (0.1 km)
. , ==
bool operator==( const RouteStop& lhs, const RouteStop& rhs )
{
return ( fabs(lhs.getDist()-rhs.getDist()) < 0.15 );
} // operator==( const RouteStop
(0.15 0.1 0.2, , .)
< :
bool operator<( const RouteStop& lhs, const RouteStop& rhs )
{
return ( lhs.getDist() - rhs.getDist() < -0.15 );

11 ; : (a == b) (!(a < b) && !(b < a)).


686 20

} // operator<( const RouteStop


, :
rAllStops[nmNdx].getDist() != aStop.getDist()
addRouteStop() :
fabs(rAllStops[nmNdx].getDist()-aStop.getDist()) >= 0.15
, :
rAllStops[nmNdx].getFare() != aStop.getFare()
:
fabs(rAllStops[nmNdx].getFare()-aStop.getFare()) >= 0.10
.12
5. getAllStops()
Route RouteStop
C++.
Route
. getAllStops() getNoOfStops().
:
unsigned int getNoOfStops() const { return rNoOfStops; }
.
c_str():
const RouteStop* Route::getAllStops() const
{ return rAllStops+1; }
:
-

.
, set<RouteStop> ;13
:
const RouteStop* Route::getAllStops() const
{
RouteStop* fv( 0 );
try
{ fv = new RouteStop[rNoOfStops]; }
catch( bad_alloc& )
{ throw RouteXptn( "getAllStops", RouteXptn::allocFailed ); }
for ( int k(0); k < rNoOfStops; ++k ) fv[k] = rAllStops[k+1];
return fv;
} // Route::getAllStops
. -


delete[].
; -
new delete

void Route::getAllStops( RouteStop*& aStops ) const


{
try { renew( aStops, 0, rNoOfStops ); }
catch( MyTmpltLibXptn& )
{ throw RouteXptn( "getAllStops", RouteXptn::allocFailed ); }
for ( int k(0); k < rNoOfStops; ++k )

12 0.15 0.10 ; !
.
13 set<RouteStop>!!! ;
- 687

aStops[k] = rAllStops[k+1];
} // Route::getAllStops
, ,
getAllStops() :
RouteStop* allStops( new RouteStop[1] );

delete[] allStops;
:
RouteStop* allStops( new RouteStop[1] );
// . . .
oneRoute.getAllStops( allStops );
// . . .
delete[] allStops;
-
.
6. setCode();
setFrom(), setTo() setInBetween() setCode()
Route; rCode ()
.14
, rCode { rFrom, rTo, rInBetween }
. setFrom(), setTo() setInBetween();
:
Route( int rc=0,
string aFrom="", string aTo="", string aInBetween="" );
, :
// . . .
string nameF, nameT, nameIB, buf;
double dist, fare;

getline( tin, buf, '\n' );


getline( tin, nameF, '\t' );
getline( tin, nameT, '\t' );
getline( tin, nameIB, '\n' );

Route oneRoute( atoi(buf.c_str()), nameF, nameT, nameIB );


// . . .
! rTo "" "".
; operator=
Route. :
oneRoute = Route( oneRoute.getCode(), oneRoute.getFrom(),
"", oneRoute.getInBetween() );
, .
, setFrom(), setTo() setInBetween()
:
( : )
.

20.8
Route
Date BString. Route -

14 :
.
688 20

RouteStop. , , -
(relationship) . Route -
(composition) RouteStop. RouteStop -
Route. Route -
RouteStop .
(multiplicity) -- (one-to-many)
1:N 1:*. :
RouteStop (N): Route
2 RouteStop ( ) -
. : 2..*.
Route (1): RouteStop
Route ( ),
. : 1..1.
-
:
,
(.. 21.06.2015 18:00),
. -
. ,
, ,
( ).
-
(),
.

.
. -
.
, -
.
:
1. .
; .
2. . ;
.
3.
. . !

:
:
class RouteStop
:
class Route
:
class Employee
{
public:
// . . .
private:
unsigned int eIdNum; //
string eSurname; //
- 689

string eFirstName; //
char eOccupation; //
}; // Employee
:
class Bus
{
public:
// . . .
private:
string bRegNum; //
unsigned int bNoOfSeats; //
unsigned int* bAllServices; //
}; // Bus
:
class BusService
{
public:
// . . .
private:
unsigned int bseCode; //
Route bseRoute; //
DateTime bseDT; // /
Bus bseBus; //
Employee bseDriver; //
Employee bseConductor; //
}; // BusService
. .
-
: . ;
! . ,
-
. , (redun-
dancy) (update anomalies).

:
-
(modification anomaly).
(deletion anomaly).
() (insertion
anomaly).
,
.
;
:
class BusService
{
public:
// . . .
private:
unsigned int bseRouteCode; //
DateTime bseDT; // /
unsigned int bseBusRegNum; // .
unsigned int bseDriverIdNum; // . .
unsigned int bseConductorIdNum; // . .
}; // BusService
690 20

BusService -
.15
; : -


.
:
BusService Route, Bus Employee (aggre-
gation). Route, Bus Employee -
BusService. BusSer-
vice Route, Bus Employee .
BusServiceRoute. BusService:
( ) : 0..*.
Route: : 1 ..1.
( --, many-to-one.)
BusServiceBus. BusService:
: 0..*. Bus:
: 1..1. ( --
.)
BusServiceEmployee.
(role) .
BusService: ,
: 0..*. Employee: )
( bseDriverIdNum):
: 1..1 )
( bseConductorIdNum, ):
0..1. ( --.)
has_a. -
has_a, is_part_of. -
:
Route has_a RouteStop RouteStop is_part_of Route
BusService has_a Bus Bus is_part_of BusService
(im-
plementation phase).
(design)
.
.
.
(association
class).
BusService
Route, Bus, Employee Employee. ,
() : bseRouteCode, bseBusRegNum, bseDriverIdNum
bseConductorIdNum. bseDT.
-
:

: ( ),

15 BusService (foreign keys).


- 691

Route RouteStop

-rCode: unsigned int -sName: string


-rFrom: string -sDist: float
-rTo: string -sFare: float
-rInBetween: string +getName(): string
-rAllStops[0..*]: RouteStop +getDist(): float
-rNoOfStops: unsigned int +getFare(): float
+setFrom( aName: string ) +setName( aName: string )
+setTo( aName: string ) +writeToText( inout tout: ostream& )
+setInBetween( aName: string ) ()
+clearRouteStops()
+find1RouteStop( stopName: string ): bool
+get1RouteStop( stopName: string )
+addRouteStop( aStop: RouteStop ) oneStop : RouteStop
+deleteRouteStop( stopName: string )
sName = .
+writeToText( inout tout: ostream& )
sDist = 4.3
-findPos: int( aName: string )
sFare = 1.3
-insert1RouteStop( aStop: RouteStop, distNdx: int )
-erase1RouteStop( stopName: string ) ()
()

. 20-5 () Route. () RouteStop.


() oneStop RouteStop.

-
(, , , ).

class BusStop
{
public:
// . . .
private:
string bsName; //
string bsLocation; //
unsigned char bsFaciLevel; //
}; // BusStop
BusStop Route. ( Route) 2
( BusStop) 2...*.
: 1...*.
-- (M:N).
.
. , RouteStop,
(rCode, bsName)
sDist sFare. ,
Route RouteStop ,
.
-
. , -, (entities)
.

20.8.1
-
, -
692 20

1..1 2..*
Route RouteStop
routeStops

1..1 route

0..* 1..1
1..1 busServices
Bus BusService 0..* driver Employee
bus 0..* 0..1
0..* conductor

. 20-6 .

, . .

. ( ) UML (OMG 2010).16
.
(. 20-5): ,
.
.
:
, , :,
:
= + | - | #;
+ public, - private #
protected ( ).
:
, , (, [ ]. ), :,
:
= | , ;
= [ ], , [ ]. :, ;
= in | out | inout;
in.
-
, .
. . 20-6
. 20-7
.
. 20-6:
, Route-RouteStop
RouteStop Route.
Route. -
. RouteStop. -
(uni-directional) : Route
RouteStop (
rAllStops) RouteStop -
Route. -
RouteStop.

16 UML: Unified Modeling Language, OMG: Object Management Group.


- 693

RouteStop
Route BusStop
0..* 2..*

1..* RouteStop
-sDist: float
-sFare: float

driver
Bus 1..* 1..* Employee
BusService
0..*
conductor

BusService
-bseDT: DateTime

. 20-7 - -
. 20-6. RouteStop (-
) . ()
BusService. . 20-6.

BusServiceBus BusService .
Bus -
BusService. -
(bi-directional) . , BusService -
Bus -
( bAllServices).
.
-
. BusServiceEmployee.
()
.
. 20-7 . 20-6.
- (entity-relationship ER diagram).
:
, BusStop, . 20-6.
RouteStop ()
. , BusService
. -
.17
. RouteStop;
Route : ;
BusStop : -
; BusService -
. Route : ,
() ;
Bus, Employee (driver)
Employee (conductor)
(class diagram) -
(structure diagram) .

17 .
694 20

(behavior diagrams)
.

-, -
. 20-6 (
) . ,
: ,
,

. ,

.

20.9 ...

. - -
. Date
:
WeekDay dDayOfWeek;
.
.
,
, . ,
, -
.
, , -
.
. -
.
, , -
- ( ).
.
-
, .18
, (get) (set)
. ; . , BString,
getReserved(); ! bsReserved
-

BString.
, setReserved(. . .).
-
get set. Battery,
, powerDevice() maxTime()
getEnergy() recharge() setEnergy().
, -

18 .
- 695

(use cases),
.


20-1 :
-



eMail
20-2



20-3 RouteStop;
( )
( )
:
class RouteStopCStr
{
public:
// . . .
private:
char sName[20]; //
float sDist; // km
float sFare; //
}; // RouteStopCStr


20-4 20.7.5,
RouteStop
Route.
20-5 readFromText() RouteStop. ,
text (
).
. , . 10-8.
readFromText Route.


20-6 .

:
class Product
696 20

{
public:
// . . .
private:
string prCode; //
string prDescr; //
Component* prComp; //
unsigned int prNoOfComp; //
}; // Person
( ) :
class Component
{
public:
// . . .
private:
char cCode[10]; //
double cQty; //
}; // Product
1. .
2. (
) .
.
3. Product -
. -
save() load() .
,
.

21

:
(
). -
: -
.
:
,
, .
:






RAII


:
21.1 .................................................................................................................................. 698
21.1.1 ...............................................................................................................................700
21.2 .......................................................................................................................... 701
21.3 .................................................................................................... 704
21.4 ............................................................................................................... 706
21.5 ....................................................................................................................................... 708
21.5.1 ...........................................................................................................711
21.5.2 ; ..............................................................................................................................711
21.6 ........................................................................................................................... 712
21.6.1 swap() ..............................................................................................................................................712
21.7 * ......................................................................................................................... 716
21.8 .......................................................................................................................... 717
21.9 renew() ................................................................................................................. 717
21.10 : { } GE SE .................................................................. 719
21.10.1 * string BString: reserve() ...............................................................................721
21.11 ........................................................................................................................... 723
21.11.1 ; ...................................................................................................................................................728
21.11.2 ....................................................................................................................................................729
21.12 * ............................................................................................................................... 730

697
698 21

21.13 ................................................................................................................................... 731


21.13.1 ..................................................................................................................................731
21.13.2 ..................................................................................................................................733
21.14 ............................................................................................................................... 734
21.15 .......................................................................................................................... 736
21.16 ................................................................................................................. 737
- ............................................................................................................................................. 738
.............................................................................................................................................................................738
.............................................................................................................................................................................738

:
,
(instance crea-
tion).
-
. C++
, ..
Date. (crea-
tors) (constructors).
Date, BString, Battery, Route Route-
Stop. BString Route :
() -
. , (destructor) -
() .
, -
.
.
(special functions):
, ,
: -
( ) (implicit) -
. ; . BString.

(conversion functions) .
-
:
,
.
.
.
,
.
-.

21.1
(default constructor)
( ) , ,
.
.
, Date:
699

class Date
{ // I: (dYear > 0) && (0 < dMonth <= 12) &&
// (0 < dDay <= lastDay(dYear, dMonth))
public:
// Date( int yp = 1, int mp = 1, int dp = 1 );
Date();
Date( int yp, int mp = 1, int dp = 1 );
// . . .
, :
Date::Date()
{
cout << "in Date default constructor" << endl;
dYear = 1; dMonth = 1; dDay = 1;
// 1 1 ..
} // Date::Date
:
cout << " " << endl;
Date d;
cout << " " << endl;
Date da[3];
cout << " " << endl;
Date* pd( new Date );
cout << " " << endl;
Date* pda( new Date[2] );
:

in Date default constructor

in Date default constructor
in Date default constructor
in Date default constructor

in Date default constructor

in Date default constructor
in Date default constructor
, , :
.
( ).
.
( ).
.
:
1. :
Date( int yp, int mp = 1, int dp = 1 );

Date( int yp = 1, int mp = 1, int dp = 1 );

, .
2. :
dYear = 1; dMonth = 1; dDay = 1; // 1 1 ..
, ; , , ; . . .
700 21

21.1.1
(default constructor) ...
. -
2 1 ( 1): -
.
.
; !
Date, (19.1):
Date( int yp = 1, int mp = 1, int dp = 1 );
:
Date::Date( int yp, int mp, int dp )
{
cout << "in Date default constructor: ";
if ( yp <= 0 )
throw DateXptn( "Date", DateXptn::yearErr, yp );
dYear = yp;
if ( mp <= 0 || 12 < mp )
throw DateXptn( "Date", DateXptn::monthErr, mp );
dMonth = mp;
if ( dp <= 0 || lastDay(dYear, dMonth) < dp )
throw DateXptn( "Date", DateXptn::dayErr, yp, mp, dp );
dDay = dp;
cout << dDay << '.' << dMonth << '.' << dYear << endl;
} // Date
:
cout << " " << endl;
Date d;
cout << " " << endl;
Date da[3];
cout << " " << endl;
Date* pd( new Date );
cout << " " << endl;
Date* pda( new Date[2] );
:

in Date default constructor: 1.1.1

in Date default constructor: 1.1.1
in Date default constructor: 1.1.1
in Date default constructor: 1.1.1

in Date default constructor: 1.1.1

in Date default constructor: 1.1.1
in Date default constructor: 1.1.1
-
(initializing constructor). :
cout << " " << endl;
Date d( 2006, 8, 26 );
cout << " " << endl;
Date( 2007, 10, 5 );
cout << " " << endl;
Date* pd( new Date(2001, 1, 11) );
cout << " " << endl;
bool before( d < 2008 );
cout << before << endl;
:

in Date default constructor: 26.8.2006
701


in Date default constructor: 5.10.2007

in Date default constructor: 11.1.2001

in Date default constructor: 1.1.2008
1
:
.
.
.
(2008)
(Date).
BString, :
BString( const char* rhs="" );
:
BString::BString( const char* rhs )
{
bsLen = cStrLen( rhs );
bsReserved = ((bsLen+1)/bsIncr+1)*bsIncr;

try { bsData = new char [bsReserved]; }


catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
for ( int k(0); k < bsLen; ++k ) bsData[k] = rhs[k];
} // BString::BString

; -
. Date :
Date( int yp, int mp = 1, int dp = 1 );
BString :
BString( const char* rhs );

21.2
(copy constructors).

, ..:
Date d1( 2002, 7, 2 ), d2( d1 ); // d1 == d2 == 02.07.2002

Date d1( 2002, 7, 2 ), d2 = d1; // d1 == d2 == 02.07.2002


-
. : , , d1
d2.

. 20.2 BString,
:
BString::BString( const BString& rhs )
{
try { bsData = new char[rhs.bsReserved]; }
catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
bsReserved = rhs.bsReserved;
for ( int k(0); k < rhs.bsLen; ++k )
702 21

bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
} // BString::BString
;

C++ .

;
. .
-
.
-
.
:
Date, GrElmn RouteStop .
BString Route

.
:
.
K : K( const
K& rhs ).
.
; ,
const K& rhs -
.
C++ :
.
( return) .
:1
BString appendW( BString s )
{
BString fv;
char* sv( new char[s.length()+2] );
strcpy( sv, s.c_str() );
sv[s.length()] = 'W'; sv[s.length()+1] = '\0';
fv = BString( sv );
cout << "returning from appendW" << endl;
return fv;
} // appendW
BString. :
BString::BString( const char* rhs )
{
cout << "In default constructor; rhs: " << rhs << endl;
bsLen = cStrLen( rhs );
// . . .
:
BString::BString( const BString& rhs )
{
cout << "In copy constructor; rhs: " << rhs.c_str() << endl;
try { bsData = new char [bsReserved]; }

1 (!) ;
703

// . . .
appendW() :
BString q( "abc" ), t;
cout << "going to call appendW" << endl;
t = appendW( q );
cout << "q: " << q.c_str() << " t: " << t.c_str() << endl;
:2
In default constructor; rhs: abc
In default constructor; rhs:
going to call appendW
In copy constructor; rhs: abc
In default constructor; rhs:
In default constructor; rhs: abcW
returning from appendW
In copy constructor; rhs: abcW
q: abc t: abcW
going to call appendW In copy constructor;
rhs: abc. , returning from appendW In copy
constructor; rhs: abcW.
7.3 : ' -
... : [ -
]. -
.
. In copy
constructor; rhs: abc -
s q. ,
:
BString s( q );
, 7.3 return ...
. fv return
appendW(),
. , , tmp,
fv.
:
BString tmp( fv );
In copy constructor; rhs: abcW.
:
return fv return BString(sv) return sv
( ). , -
appendW "abc".
:
,
C++,
.
return C++,
: .
-
. -

2 Borland C++, v.5.5


704 21

( ),
!

21.3
3.
.
.

1
:
0: #include <iostream>
1: using namespace std;
2:
3: class A
4: {
5: int aM;
6: public:
7: A( int ap = 0 ) //
8: { aM = ap;
9: cout << "A object created, aM = " << aM << endl; }
10: A( const A& rhs ) //
11: { aM = rhs.aM;
12: cout << "A object copy created, aM = " << aM << endl; }
13: A& operator=( const A& rhs ) //
14: { aM = rhs.aM;
15: cout << "A assignment, aM = " << aM << endl;
16: return *this; }
17: int getM() const { return aM; }
18: }; // A
19:
20: class C
21: {
22: int cM;
23: public:
24: C( int cp = 0 ) //
25: { cM = cp;
26: cout << "C object created, cM = " << cM << endl; }
27: C( const C& rhs ) //
28: { cM = rhs.cM;
29: cout << "C object copy created, cM = " << cM << endl; }
30: C& operator=( const C& rhs ) //
31: { cM = rhs.cM;
32: cout << "C assignment, cM = " << cM << endl;
33: return *this; }
34: int getM() const { return cM; }
35: }; // C
36:
37: class D
38: {
39: A dA;
40: C dC;
41: public:
42: D( A ap=A(0), C cp=C(0) ) //
43: { dA = A(ap.getM()+1); dC = C(cp.getM()+1);
44: cout << "D object created" << endl; }
45: D( const D& rhs ) //
46: { dA = rhs.dA; dC = rhs.dC;
47: cout << "D object copy created" << endl; }

3 . ...
705

48: }; // D
49:
50: int main()
51: {
52: D d;
53: }
:
C object created, cM = 0
A object created, aM = 0
A object created, aM = 0
C object created, cM = 0
A object created, aM = 1
A assignment, aM = 1
C object created, cM = 1
C assignment, cM = 1
D object created
d (. 52 main): (. 42)
- cp ap ( :
cp ap)
( ) A C.
d:
da dc -
A C (: A object created, C object created),
(. 39, 40).
D: (
) A A(ap.getM()+1) (. 43,
: A object created, aM = 1) da (A assignment, aM =
1). dc (: C object created, cM = 1, C
assignment, cM = 1). , : D object created.

D (. 42-44) :
42: D( A ap=A(0), C cp=C(0) ) //
43: : dA( A(ap.getM()+1) ), dC( C(cp.getM()+1) )
44: { cout << "D object created" << endl; }
: da dc (initialization list)
. 43. :
C object created, cM = 0
A object created, aM = 0
A object created, aM = 1
C object created, cM = 1
D object created
; d
.
.4
2
Date
:
Date::Date( int yp, int mp, int dp )
: year( yp ), month( mp ), day( dp )
{
if ( yp <= 0 )
throw DateXptn( "Date", DateXptn::yearErr, yp );
if ( mp <= 0 || 12 < mp )

4 .
706 21

throw DateXptn( "Date", DateXptn::monthErr, mp );


if ( dp <= 0 || lastDay(year, month) < dp )
throw DateXptn( "Date", DateXptn::dayErr, yp, mp, dp );
} // Date

:

.
. (;)
, ,
.
3
complex (19.5) :
complex::complex( double rp = 0.0, double ip = 0.0 )
: re( rp ), im( ip ) { };

BString; ! bsData(
rhs ) rhs bsData.
, :
DateXptn( const char* mn, int ec, int ev1 = 0,
int ev2 = 0, int ev3 = 0 )
: errorCode( ec ),
errVal1( ev1 ), errVal2( ev2 ), errVal3( ev3 )
{ strncpy( funcName, mn ); funcName[99] = '\0'; }

BStringXptn( char* mn, int ec, int ev = 0 )


: errorCode( ec ), errorValue( ev )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }

21.4

. 5
() .
( -
.) .

.
; ; , ,
.
, ,
; .
:

.
: -
Route. BString
:

5 () . ;
.
707

Route::Route( const Route& rhs )


{
try { rAllStops = new RouteStop[rhs.rReserved]; }
catch( bad_alloc )
{ throw RouteXptn( "Route", RouteXptn::allocFailed ); }
rReserved = rhs.rReserved;
for ( int k(0); k < rhs.rNoOfStops; ++k )
rAllStops[k] = rhs.rAllStops[k];
rNoOfStops = rhs.rNoOfStops;
rCode = rhs.rCode;
rFrom = rhs.rFrom;
rTo = rhs.rTo;
rInBetween = rhs.rInBetween;
} // Route::Route
. rAllStops[k], RouteStop,
(std::)string.
operator= BString (20.4) .
bad_alloc -
. , , :
try
{
for ( int k(0); k < rhs.rNoOfStops; ++k )
rAllStops[k] = rhs.rAllStops[k];
}
catch( bad_alloc )
{ throw RouteXptn( "Route", RouteXptn::allocFailed ); }
! ; :
rAllStops .
:
catch( bad_alloc )
{ delete[] rAllStops;
throw RouteXptn( "Route", RouteXptn::allocFailed ); }
:
Route::Route( const Route& rhs )
{
try { rAllStops = new RouteStop[rhs.rReserved]; }
catch( bad_alloc )
{ throw RouteXptn( "Route", RouteXptn::allocFailed ); }
rReserved = rhs.rReserved;
try
{
for ( int k(0); k < rhs.rNoOfStops; ++k )
rAllStops[k] = rhs.rAllStops[k];
rFrom = rhs.rFrom;
rTo = rhs.rTo;
rInBetween = rhs.rInBetween;
}
catch( bad_alloc )
{ delete[] rAllStops;
throw RouteXptn( "Route", RouteXptn::allocFailed ); }
rNoOfStops = rhs.rNoOfStops;
rCode = rhs.rCode;
} // Route::Route
() try
rFrom, rTo rInBetween .
setFrom, setTo setInBetween. -
!
:
708 21


.
; :
,

.

: RouteStop :
BString sName; //
:
rAllStops[k] = rhs.rAllStops[k] (
) bad_alloc BStringXptn( allocFailed).
;
:
1. RouteStop .
, ( )
, , . -
.
2. try :
m (< rhs.rReserved) ;
! C++ (-
) .

21.5
:
:
{
BString a;
// . . .
} // : a.
a
T, . C++
bsData, bsLen, bsReserved
( bsData) (
bsData). , C++
-, (destructor)
.
.
BString :
BString::~BString()
{
delete[] bsStart;
} // BString::~BString
Date . ,
:
~Date() { };
. :
709


, -
.
K:
( -
),
~K,
.

~K() { };
. -
.
;
: -
. ,
delete[] bsData bsData 0 ()
. -
BString 0 < bsReserved
.
:
.

. BString :
BString::~BString()
{
cout << "destructing BString " << c_str() << endl;
delete[] bsData;
} // BString::~BString

#include <iostream>
#include "BString.cpp"
using namespace std;

struct S
{
BString sName;
float sDist;
}; // S

int main()
{
{
BString a( "aaa" );
// . . .
cout << "going to destroy a" << endl;
} // : a.

BString* b( new BString("bbb") );


// . . .
cout << "going to delete b" << endl;
delete b;

BString* c( new BString[2] );


c[0] = "c0c0"; c[1] = "c1c1";
// . . .
cout << "going to delete c" << endl;
delete[] c;
710 21

{
S s;
s.sName = "sssss"; s.sDist = 7.33;
// . . .
cout << "going to destroy s" << endl;
} // : s.

S* s( new S );
s->sName = "psps"; s->sDist = 7.33;
// . . .
cout << "going to delete s" << endl;
delete s;
}
:
going to destroy a
destructing BString aaa
going to delete b
destructing BString bbb
going to delete c
destructing BString c1c1
destructing BString c0c0
going to destroy s
destructing BString sssss
going to delete s
destructing BString psps
;
: a -

T, . .
:
, .
, : -
S
.
;
-
.
:
.
.
. . 1
21.3 :
~A()
{ cout << "destructing an A object aM = " << aM << endl; }

~C()
{ cout << "destructing a C object aM = " << cM << endl; }

~D()
{ cout << "destructing a D object" << endl; }
:
C object created, cM = 0
A object created, aM = 0
A object created, aM = 1
C object created, cM = 1
D object created
711

destructing an A object aM = 0
destructing a C object aM = 0
destructing a D object
destructing a C object aM = 1
destructing an A object aM = 1
A(0) C(0)
d
destructing a D object.
dc da.

21.5.1
:

.
; :
. :
.
;
, .
( ).
: , ;! ,
BString.
.

21.5.2 ;

.
~BString() ~Date();
! ,
new (16.5).
, :
char* buf( new char[100] );
BString* bs( new (buf) BString );
// . . .
delete[] buf;
*bs buf. , -
bsData, bsLen, bsReserved buf[0], buf[4],
buf[8] . () bsData
( buf). delete[] buf
*bs, bs->bsData, .
. ; :
// . . .
bs->~BString();
delete[] buf;
buf:
char* buf( new char[100] );
BString* bs( new (buf) BString );
// . . .
bs->~BString();
double* d( new (buf) double );
// . . .
712 21

delete[] buf;
:
bs->~BString() bs->bsData
. bs->bsReserved
.

21.6
(20.4) -
BString
:
BString& BString::operator=( const BString& rhs )
{
if ( &rhs != this ) // if ( ! )
{
//
char* tmp;
try { tmp = new char[rhs.bsReserved]; }
catch( bad_alloc& )
{ throw BStringXptn( "operator=", BStringXptn::allocFailed ); }
//
delete[] bsData;
// rhs
bsData = tmp;
bsReserved = rhs.bsReserved;
for ( int k(0); k < rhs.bsLen; ++k )
bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
}
return *this;
} // BString::operator=
:
(tmp). , ,
bad_alloc BStringXptn (allocFailed).

. , a = b
a. ,
-
.
:
(,
)
.
(exception safety)
(strong guarantee). -
.

21.6.1 swap()

(Stepanov6, 2007) .
swap().

6 A.A. Stepanof, ( ), STL.


713

BString. swap(),
, ( ) 14.7.1:
void BString::swap( BString& rhs )
{
BString s( *this );
*this = rhs; rhs = s;
} // BString::swap

. .

!
swap() -
-, :
void BString::swap( BString& other )
{
char* pSave( bsData );
bsData = other.bsData; other.bsData = pSave;

size_t save( bsLen );


bsLen = other.bsLen; other.bsLen = save;

save = bsReserved;
bsReserved = other.bsReserved; other.bsReserved = save;
} // BString::swap
:
bsData rhs.bsData
.
char*
size_t. BString.7
, :8
BString& BString::operator=( const BString& rhs )
{
if ( &rhs != this )
{
BString tmp( rhs );
swap( tmp );
}
return *this;
} // BString::operator=
, BString tmp(rhs)
, swap() *this . tmp
swap()
.
:
( )
. , .
:
(tmp).
.

7 swap() - (no-throw
guarantee).
8 operator=
(canonical form).
714 21

RAII
16.7.1.
-
Route :
Route& Route::operator=( const Route& rhs )
{
if ( &rhs != this )
{
Route tmp( rhs );
swap( tmp );
}
return *this;
} // Route::operator=
, swap() .
swap() private public;
private ,
- . string::
swap() public.
:
1. std::swap() :
void BString::swap( BString& other )
{
std::swap( bsData, other.bsData );
std::swap( bsLen, other.bsLen );
std::swap( bsReserved, other.bsReserved );
} // BString::swap
.
2. .
const BString& rhs , BString rhs
a = b
b rhs .
, tmp !
BString& BString::operator=( BString rhs )
{
if ( &rhs != this )
{
swap( rhs );
}
return *this;
} // BString::operator=

. !
;
3. , ,
(). -
:
BString& BString::operator=( const BString& rhs )
{
if ( &rhs != this )
{
try { BString tmp( rhs );
swap( tmp ); }
catch( BStringXptn& x )
{ strcpy( x.funcName, "operator=" );
throw; }
}
return *this;
715

} // BString::operator=
: BStringXptn, funcName
.
swap()
-
, .. .
: . 20-5.
void RouteStop::readFromText( istream& tin )
RouteStop
: - .
:
void RouteStop::swap( RouteStop& other )
{
sName.swap( other.sName );
std::swap( sDist, other.sDist );
std::swap( sFare, other.sFare );
} // RouteStop::swap
string::swap() .
tin text .
:
0: void RouteStop::readFromText( istream& tin )
1: {
2: try
3: {
4: string line;
5: getline( tin, line, '\n' );
6: if ( tin.fail() )
7: throw RouteStopXptn( "readFromText",
8: RouteStopXptn::cannotRead );
9: if ( line.empty() )
10: throw RouteStopXptn( "readFromText",
11: RouteStopXptn::lineEmpty );
12: size_t t1Ndx( line.find('\t', 0) );
13: if ( t1Ndx == string::npos )
14: throw RouteStopXptn( "readFromText",
15: RouteStopXptn::incomplete );
16: size_t t2Ndx( line.find('\t', t1Ndx+1) );
17: if ( t1Ndx == string::npos )
18: throw RouteStopXptn( "readFromText",
19: RouteStopXptn::incomplete );
20: RouteStop tmp;
21: if ( t1Ndx == 0 )
22: throw RouteStopXptn( "readFromText",
23: RouteStopXptn::noName );
24: tmp.sName = line.substr( 0, t1Ndx );
25: string buf( line.substr(t1Ndx+1, t2Ndx-t1Ndx-1) );
26: tmp.sDist = atof( buf.c_str() );
27: if ( tmp.sDist < 0 )
28: throw RouteStopXptn( "readFromText",
29: RouteStopXptn::negDist,
30: tmp.sDist );
31: buf = line.substr( t2Ndx+1 );
32: tmp.sFare = atof( buf.c_str() );
33: if ( tmp.sFare < 0 )
34: throw RouteStopXptn( "readFromText",
35: RouteStopXptn::negFare,
36: tmp.sFare );
37: this->swap( tmp );
38: }
39: catch( bad_alloc )
40: { throw RouteStopXptn( "readFromText",
716 21

41: RouteStopXptn::allocFailed ); }
42: } // RouteStop::readFromText
. 4, getline() (. 5). getline()
, ... (. 6-8).
(. 9-11).
'\t':
find() string
t1Ndx (. 12).
find() t1Ndx+1 -
t2Ndx (. 16).
find() (. 13-15, 17-19).
'\t' t1Ndx
0 .. t1Ndx1 ( t1Ndx == 0). '\t'
t2Ndx t1Ndx+1 .. t2Ndx1
t2Ndx+1 .
(. 20). (. 21-
36).
, :
this->swap( tmp );
: swap( tmp ).
bad_alloc
string.
:
1. RouteStopXptn::lineEmpty:
; , : -
! ,
, readFromText().
:
do {
try {
RouteStop oneStop;
oneStop.readFromText( tin );
oneRoute.insert1RouteStop( oneStop );
}
catch( RouteStopXptn& x )
{
if ( x.errCode != RouteStopXptn::lineEmpty &&
x.errCode != RouteStopXptn::cannotRead )
throw;
}
} while ( !tin.eof() );
2. this->swap(tmp) *this = tmp;
, , sName = tmp.sName , , .
swap() : -
bad_alloc
.

21.7 *
19.1 :
d1 = Date( 2008, 7, 9 );
717

20.4.2 s2 = "what\'s this\?"


:
s2 = BString( "what\'s this\?" );
-
(temporary) .
-
. -
.
; -
. ,
.

21.8

(rule of three Law of The Big Three)
: , ,
, .
BString Route .
, :
; :
, -
,
.

21.9 renew()
renew()
16.12 .
:
try
{
T* temp( new T[nf] );
for ( int k(0); k < ni; ++k ) temp[k] = p[k];
delete[] p; p = temp;
}
catch( bad_alloc& )
{
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::allocFailed );
}
bad_alloc new T[nf]
temp[k] = p[k]. T -
.
:
T* temp;
try
{ temp = new T[nf]; }
catch( bad_alloc& )
{ throw MyTmpltLibXptn( "renew",
MyTmpltLibXptn::allocFailed ); }
try
{
for ( int k(0); k < ni; ++k ) temp[k] = p[k];
718 21

}
catch( bad_alloc& )
{ delete[] temp;
throw MyTmpltLibXptn( "renew",
MyTmpltLibXptn::allocFailed ); }
delete[] p; p = temp;
, nf T temp
-
,
temp.
-
BString:
(20.4),
, BStringXptn BStringXptn
::allocFailed.

temp.
; try catch
BStringXptn.
:
catch( bad_alloc& )
{ throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::allocFailed ); }
catch( BStringXptn& x )
{
if ( x.errorCode == BStringXptn::allocFailed )
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::allocFailed);
else
throw;
}
:
catch( bad_alloc& )
{ delete[] temp;
throw MyTmpltLibXptn( "renew",
MyTmpltLibXptn::allocFailed ); }
catch( BStringXptn& x )
{
delete[] temp;
if ( x.errorCode == BStringXptn::allocFailed )
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::allocFailed);
else
throw;
}

template < typename T, typename TXptn >


void renew( T*& p, int ni, int nf )
BStringXptn TXptn.
, ,
, ,
allocFailed.
:
renew() :

temp bad_alloc.
719

O
.
.

bad_alloc TXptn allocFailed.
p[k]
temp[k].
. -
, bad_alloc TXptn allocFailed.
:
template< typename T >
void renew( T*& p, int ni, int nf )
{
if ( ni < 0 || nf < ni )
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::domainError,
ni, nf );
// 0 <= ni <= nf
if ( p == 0 && ni > 0 )
throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::noArray );
// (0 <= ni <= nf) && (p != 0 || ni == 0)
T* temp;
try
{ temp = new T[nf]; }
catch( ... )
{ throw MyTmpltLibXptn( "renew", MyTmpltLibXptn::allocFailed ); }
try
{
for ( int k(0); k < ni; ++k ) temp[k] = p[k];
}
catch( ... )
{ delete[] temp;
throw MyTmpltLibXptn( "renew",
MyTmpltLibXptn::allocFailed ); }
delete[] p; p = temp;
} // void renew
-
.
renew() T
.9
renew() -
:

.

21.10 : { } GE SE
20.8
. .
, , ,
,
:
(, class invariant),
(, default constructor),

9 .
720 21

(, copy constructor),
(, =),
(, destructor),
get (GE) ,
set (SE) .
- ;
. -

/ get /
set. Battery: getEnergy,
setEnergy, setMaxEnergy, setVoltage
.
-:
(, class invariant):
(:
),
,

public.
, set -
. ;
. , -
.
E (, default constructor):
: , -
. .
, -
, . ,
(2 1).
(, copy constructor): )
, )
) .

; (
).
(, =):
() . -
.
( ).
K (, destructor):
, ..
.
.
get (GE) :
! .. BString
getReserved() bsReserved:
. ,
, get BString::length()
getLen BString::c_str() getData.
721

set (SE) : ; ! ,
BString bsLen bsReserved.
set -
.
.
(-)
:
,
,
(, , )
() .
BString
[].
.
:
1. get
set . 10 (19.5)
.11 :

true ( )
,
,
.
2. ,
. .. : ~Date() { }.12
.
3. , K
: ( ) -
( ). , .
.
4. , .

.

.

21.10.1 * string BString: reserve()



: getReserved()
setReserved(); string capacity() reserve();
C++ string

10 .. (Lockheed Martin 2005) AV Rule 123 : The number of accessor and mutator functions should
be minimized, : get set .
11 (Lockheed Martin 2005) AV Rule 66 : A class should be used to
model an entity that maintains an invariant.
12 : virtual ~Date() { } .
722 21

. ;
reserve(). :
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1( "test text" );

cout << s1
<< " " << s1.length() << " " << s1.capacity() << endl;

s1.reserve( 40 );
cout << s1
<< " " << s1.length() << " " << s1.capacity() << endl;
}
:
test text 9 9
test text 9 40
s1.capacity() (size_t)13
s1 -
. s1.reserve(40) 40 () .
s1.reserve( n )
s1.
n > s1.capacity() n ( )
n > s1.max_size().
n < s1.capacity() .
BString. capacity()
getReserved():
size_t capacity() const { return bsReserved; }
reserve() :
void BString::reserve( int newRes )
{
if ( newRes < 0 )
throw BStringXptn( "reserve",
BStringXptn::domainError, newRes );
if ( newRes > bsReserved ||
(newRes < bsReserved/2 && newRes > bsLen) )
{
char* tmp;
newRes = (newRes/bsIncr+1)*bsIncr;
try { tmp = new char[newRes]; }
catch( bad_alloc& )
{ throw BStringXptn( "reserve", BStringXptn::allocFailed ); }
bsReserved = newRes;
for ( int k(0); k < bsLen; ++k ) tmp[k] = bsData[k];
delete[] bsData;
bsData = tmp;
}
} // BString::reserve
bsReserved :
newRes > bsReserved
bsLen < newRes < bsReserved/2
, newRes
(newRes/bsIncr+1)*bsIncr.

13 : string::size_type.
723

, reserve() -
BStringXptn::domainError string::reserve() () -
bad_alloc.14
, setReserved!
BString :
test text 9 16
test text 9 48

21.11
. 3 16.13 ( SList), -
GrElmn. , SList
.
():
aNode :
(*slHead == aNode)15
(, xor)
bNode aNode
(*(bNode.lnNext) == aNode)16
:

slTail (slTail->lnNext == 0)
.
:
content GrElmn:
, *slTail,
content. content :
(aNode != bNode) (aNode.lnData != bNode.lnData)
content ( ,
*slTail).
, .
: ListNode
SList.
, :
class SList
{
public:
struct ListNode
{
GrElmn lnData;
ListNode* lnNext;
}; // ListNode
// . . .
private:
ListNode* slHead;
ListNode* slTail;
}; // SList

14 : n > max_size().
15 : slHead == &aNode.
16 : bNode.lnNext == &aNode.
724 21

,
SList::ListNode.
E ():
. 16.13 :
ApplicXptn SListXptn:
SList::SList()
{
try { slHead = new ListNode; }
catch( bad_alloc& )
{ throw SListXptn( "SList", SListXptn::allocFailed ); }
slHead->lnNext = 0; slTail = slHead;
} // SList
(): :
. ()
:
SList::SList( const SList& other )
{
try
{
slHead = new ListNode;
slTail = slHead;
ListNode* p( other.slHead );
while ( p != other.slTail )
{
slTail->lnData = p->lnData;
slTail->lnNext = new ListNode;
slTail = slTail->lnNext;
p = p->lnNext;
}
slTail->lnNext = 0;
}
catch( bad_alloc& )
{ throw SListXptn( "SList", SListXptn::allocFailed ); }
} // SList::SList
; -
200 bad_alloc
110
109 ! :
SList::SList( const SList& other )
{
try { slHead = new ListNode; }
catch( bad_alloc& )
{ throw SListXptn( "SList", SListXptn::allocFailed ); }
slTail = slHead;
ListNode* p( other.slHead );
while ( p != other.slTail )
{
slTail->lnData = p->lnData;
try { slTail->lnNext = new ListNode; }
catch( bad_alloc& )
{
while ( slHead != slTail )
{
ListNode* p( slHead );
slHead = slHead->lnNext;
delete p;
}
delete slHead;
throw SListXptn( "SList", SListXptn::allocFailed );
}
slTail = slTail->lnNext;
p = p->lnNext;
725

}
slTail->lnNext = 0;
} // SList::SList
, catch
.
.
K ():
:
SList::~SList()
{
while ( slHead != slTail )
{
ListNode* p( slHead );
slHead = slHead->lnNext;
delete p;
}
delete slHead;
slTail = slHead = 0;
} // SList::~SList
. ,
SList_deleteAll().
():
:
SList& SList::operator=( const SList& rhs )
{
if ( &rhs != this )
{
SList tmp( rhs );
this->swap( tmp );
}
return *this;
} // SList::operator=
:
void SList::swap( SList& other )
{
std::swap( slHead, other.slHead );
std::swap( slTail, other.slTail );
} // SList::swap
get (GE):
get. , list STL getHead()
getTail() begin() end() . . -
inline:
ListNode* begin() { return slHead; }
ListNode* end() { return slTail; }
-
.
set (SE):
.
: -
Route.
GrElmn. -
findNdx().
:
SList::ListNode* SList::findPtr( int aAn ) const
{
ListNode* fv;
if ( aAn <= 0 )
726 21

fv = slTail;
else
{
slTail->lnData = GrElmn( aAn );
fv = slHead;
while ( (fv->lnData).getANumber() != aAn ) fv = fv->lnNext;
}
return fv;
} // SList::findPtr
:
1. lnData
aAn.
(== slTail).
2.
.
3.
.
.
: findPtr(), findNdx(), private.
- :
bool SList::find1Elmn( int aAn ) const
{
return ( findPtr(aAn) != slTail );
} // SList::find1Elmn
true aAn.
:
:
const GrElmn& SList::get1Elmn( int aAn ) const
{
ListNode* ptrToNode( findPtr(aAn) );
if ( ptrToNode == slTail )
throw SListXptn( "get1Elmn", SListXptn::notFound, aAn );
return ptrToNode->lnData;
} // SList::get1Elmn
get1RouteStop() , ,
.
get1RouteStop().
: push_front()
. :
void SList::insert1Elmn( const GrElmn& aItem )
{
ListNode* ptrToNode( findPtr(aItem.getANumber()) );
if ( ptrToNode == slTail ) //
{
push_front( aItem );
}
} // SList::insert1Elmn
push_front() -
. push_front()
private.
insert1RouteStop(), -
.
: : -
(pop_front). , -
aAn, :
ListNode* ptrToNode( findPtr(aAn) );
727
lnData lnNext
8
lnData lnNext 15.9994 lnData lnNext lnData lnNext

20 Oxygen 38 xxx
40.08 87.63
Ca Sr
Calcium Strontium

slHead slTail ptrToNode pnln


()
lnData lnNext
38
lnData lnNext 87.63 lnData lnNext lnData lnNext
Sr
20 Strontium 38 xxx
40.08 87.63
Ca Sr
Calcium Strontium

slHead slTail ptrToNode pnln


()
lnData lnNext
38
lnData lnNext 87.63 lnData lnNext
Sr
20 Strontium xxx
40.08
Ca
Calcium

slHead slTail ptrToNode pnln


()
. 21-1
ptrToNode. () -
ListNode* pnln(ptrToNode->lnNext). () -
*ptrToNode = *pnln. ()
delete pnln.
(ptrToNode != slTail)
ptrToNode.
: lnNext -
! :
ListNode* pnln( ptrToNode->lnNext );
*ptrToNode = *pnln;
delete pnln;
: ( , )
. . 21-1 ()
. () -
. lnNext -
. () .
728 21

(*pnln)
slTail.
lnNext:
void SList::erase1Elmn( int aAn )
{
ListNode* ptrToNode( findPtr(aAn) );
if ( ptrToNode != slTail ) //
{
ListNode* pnln( ptrToNode->lnNext );
if ( pnln != slTail )
*ptrToNode = *pnln;
else
{
ptrToNode->lnNext = 0;
slTail = ptrToNode;
}
delete pnln;
}
} // SList::erase1Elmn
: -
RouteStop:
GrElmn tmp( lst.get1Elmn(n) );
tmp
lst.erase1Elmn( n );
lst.insert1Elmn( tmp );

21.11.1 ;
.
; , .
, , saveUpdateList().
.
:
void saveUpdateList( fstream& bInOut, const SList& lst )
{
for ( const SList::ListNode* p(lst.begin());
p != lst.end();
p = p->lnNext )
writeRandom( p->lnData, bInOut );
} // saveUpdateList
p (-) const
SList::ListNode*. lst.slHead, lst.slTail lst.begin(), lst.end()
.
, ,
;!
; ! :
-
. , , -

.
.
p =
p->lnNext.
, ,
:
void SList::save( ostream& bout,
729

void (*wrProc)(const GrElmn&, ostream&) ) const


{
for ( ListNode* p(slHead); p != slTail; p = p->lnNext )
(*wrProc)( p->lnData, bout );
} // save

. :
lst.save( bInOut, writeRandom );
; ...
,
.
saveUpdateList().

21.11.2
:
#include <iostream>
#include <fstream>
#include <string>

#include "GrElmn.cpp"
#include "SList.cpp"

using namespace std;

struct ApplicXptn
//

void openFile( string& flNm, fstream& bInOut );


void countRecords( fstream& bInOut, size_t& noOfRecords );
void readAtNo( int maxAtNo, int& aa );
void readRandom( GrElmn& a, istream& bin, int atNo );
void writeRandom( const GrElmn& a, ostream& bout );
void editGrNameMM( GrElmn& a );
//

void saveUpdateList( fstream& bInOut, const SList& lst );


//

int main()
{
fstream bInOut;
string flNm( "elementsGr.dta" );

try
{
SList lst;

openFile( flNm, bInOut );


// .. ( )
unsigned int maxAtNo;
countRecords( bInOut, maxAtNo );
int aa;
do {
// ..
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
GrElmn tmp;
if ( lst.find1Elmn(aa) )
{
tmp = lst.get1Elmn( aa );
730 21

lst.erase1Elmn( aa );
}
else
readRandom( tmp, bInOut, aa );
editGrNameMM( tmp );
lst.insert1Elmn( tmp );
}
} while ( aa != 0 );
saveUpdateList( bInOut, lst );
bInOut.close();
if ( bInOut.fail() )
throw ApplicXptn( "main", ApplicXptn::cannotClose,
flNm.c_str() );
}
catch( GrElmnXptn& x )
// . . .
catch( SListXptn& x )
// . . .
catch( ApplicXptn& x )
// . . .
} // main
elmntInList
ListNode* pos;
elmntInList( lst, bInOut, aa, pos );
editGrNameMM( pos->lnData );

GrElmn tmp;
if ( lst.find1Elmn(aa) )
{
tmp = lst.get1Elmn( aa );
lst.erase1Elmn( aa );
}
else
readRandom( tmp, bInOut, aa );
editGrNameMM( tmp );
lst.insert1Elmn( tmp );

21.12 *
SList::save : GrElmn
save(), display() writeToTable()
. , SList::save(),
; ,
-.
GrElmn::display(). ostream&. -
SList::save void
: const GrElmn& ostream&.
GrElmn::display() ! :
void exDisplay( const GrElmn& aElmn, ostream& outF )
{
aElmn.display( outF );
} // exDisplay

SList::save().
:
, SList GrElmn.
:
void SList::toFile( ostream& out, OutFunc outProc ) const
731

{
for ( ListNode* p(slHead); p != slTail; p = p->lnNext )
((p->lnData).*outProc)( out );
} // toFile
outProc save display writeToTable.
(callback,
14.4) . OutFunc;
GrElmn :
class GrElmn
{
// . . .
void save( ostream& bout ) const;
void display( ostream& tout ) const;
void writeToTable( ostream& tout ) const;
// . . .
}; // GrElmn
:
typedef void (*OutFunc)( ostream& ) const;
: OutFunc void const
ostream&; ! :
typedef void (GrElmn::*OutFunc)( ostream& ) const;
: OutFunc GrElmn void const
ostream&.
GrElmn SList
:
ofstream tout( "test.txt" );
lst.toFile( tout, &GrElmn::display );
tout.close();
test.txt.

21.13
:
BString(const char* rhs)
BString .
, c_str() (const char*) (
\0 .)
Date 2008
(01.01.2008)
, , C++
:
.
-
.
,
.

21.13.1
(21.1.1): -
;
732 21

. (conversion constructor)
:
. -
: .
.

21.1.1
BString( const char* rhs );
const char*17
BString a BString :
a = BString( "abc" );

Date( int yp, int mp = 1, int dp = 1 );
int Date
d Date :
d = Date( 375 );
d 01.01.375.
15.14.1
GrElmn GrElmn_copyFromElmn( const Elmn& a )
Elmn GrElmn
. 19.6

GrElmn::GrElmn( const Elmn& rhs )

:
2 1 Date BString
.
:
BString& operator=( const char* rhs );

a = "abc";
. ;
"abc" BString.
a = BString("abc"). .
Date .
if ( d < 2012 )
{ . . .
d < Date(2012) d
01.01.2012 . d > 2012
d 01.01.2012 d
31.12.2012. .

17 . :
BString( const char* rhs, int n=0 );
rhs n . a
= BString("abcde", 2) a "cde".
733

C++ .
:
explicit Date( int yp, int mp = 1, int dp = 1 );
explicit : . -
. d = 375, d < 2012, d > 2012
d = Date( 375 ), d < Date(2012), d > Date(2012).
, ( ) .
, GrElmn :
explicit GrElmn( int aan=0, float aaw=0,
string as="", string anm="", string agn="" );
88 GrElmn -
.
BString :
explicit BString( const char* rhs );
, , . , -
, OBJ32 (CERT 2009):18

explicit.

21.13.2
-
. ,
c_str() C++ .
c_str() :
public:
// . . .
operator const char*() const
{ bsData[bsLen] = '\0'; return bsData; };
:
BString q( "abc" );
char z[30];
, :
strcpy( z, q.c_str() );
cout << z << endl;
, , :
strcpy( z, q );
cout << z << endl;
strcpy .
, :
public:
// . . .
operator const char*()
{ bsData[bsLen] = '\0'; return bsData; };
operator size_t() { return bsReserved; };
:
size_t n( q );
, , , -
.

18 OBJ32: Ensure that single-argument constructors are marked "explicit".


734 21

: strcpy(z, q)
strcpy(z, q.c_str()); , .
c_str() .19

21.14
: -
Date . ; -
1
1 (
). :
! C++ -
.
- objCnt -
:
class Date
{
public:
// ...
private:
static size_t objCnt;
unsigned int dYear;
// ...
}; // Date

size_t Date::objCnt = 0;
:
~Date() { --objCnt; };
:
Date::Date()
{
dYear = 1; dMonth = 1; dDay = 1;
// 1 1 ..
++objCnt;
} // Date::Date

Date:: Date( int yp, int mp, int dp )


{
if ( yp <= 0 )
throw DateXptn( "Date", DateXptn::yearErr, yp );
dYear = yp;
if ( mp <= 0 || 12 < mp )
throw DateXptn( "Date", DateXptn::monthErr, mp );
dMonth = mp;
if ( dp <= 0 || lastDay(dYear, dMonth) < dp )
throw DateXptn( "Date", DateXptn::dayErr, yp, mp, dp );
dDay = dp;
++objCnt;
} // Date::Date

Date::Date( const Date& d )


{
dYear = d.dYear; dMonth = d.dMonth; dDay = d.dDay;
++objCnt;

19 . (Lockheed-Martin 2005) AV Rule 177 : User-defined conversion


functions should be avoided : ()
!
735

} // Date::Date
, :
static int getObjCnt() { return objCnt; };
:
Date k1, k2, k3[5];
cout << Date::getObjCnt() << endl;
{
Date s1( 1950, 2, 1 ), s2( 2000, 2, 3 ),
s3( 1960, 3, 1 ), *c;
cout << Date::getObjCnt() << endl;
c = new Date [3];
cout << Date::getObjCnt() << endl;
delete [] c;
cout << Date::getObjCnt() << endl;
}
cout << Date::getObjCnt() << endl;
:
7
10
13
10
7
7 Date: k3 2 k1, k2.
, 3 Date: s1, s2, s3
10. new 3
13. (delete) c -
10. -
s1, s2, s3 7 .
:
1. () objCnt .
2. , objCnt
.
3. objCnt (Date::obj-
Cnt) (.objCnt).
4. getObjCnt, objCnt, , , .
,
Date::.
static ,
.
; ! objCnt -
(const) .
.
19.1.2 ...
static. , lastDay() isLeapYear()

( ) dYear, dMonth, dDay. cStrLen
BString. , static
.
. 19-3
isValidDate() :
static bool isValidDate( int ay, int am, int ad )
{
bool fv( true );
try{ Date( ay, am, ad ); }
736 21

catch( DateXptn& ) { fv = false; }


return fv;
} // isValidDate
:
if ( Date::isValidDate(iy, im, id) ) . . .

21.15
19.1.1, C++ const -
. ; const
. , BString :
// . . .
BString& operator=( const BString& rhs );
inline const char* c_str() const;
inline size_t length() const;
inline bool empty() const;
BString& operator+=( const BString& rhs );
BString& append( const BString& rhs );
int compare( const BString& rhs ) const;
// . . .
c_str(), length(), empty() compare() .
const ;
.
.
.
, .
, ..:
const BString aSt( "qwdfvbnh" );
const, ..:
aSt,swap( bSt );
.

. mutable () -
.
-; -
:
, ..:
struct DateXptn
{
enum { yearErr, monthErr, dayErr, outOfLimits };
// . . .
}; // DateXptn
yearErr, monthErr, dayErr, outOfLimits :
DateXptn::yearErr, DateXptn::monthErr, DateXptn::dayErr, DateXptn::outOfLimits.
-
:
#include <iostream>
#include <string>

using namespace std;

class A
{
private:
737

// . . .
static const int size = 10;
public:
// . . .
static const double cx;
static const string car;
static const char carc[size];
}; // A
const double A::cx = 1.234;
const string A::car = "123456789";
const char A::carc[A::size] = "123456789";

int main()
{
cout << A::cx << " " << A::car << " " << A::carc << endl;
}
, size.
, cx, car, carc, -
.
, , :
class BString
{ // I: (0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
public:
// ...
private:
static const size_t bsIncr = 16;
char* bsData;
size_t bsLen;
size_t bsReserved;
}; // BString

21.16
- -
; ,
(19.7)
bVoltage bMaxEnergy,
() .
:
class Battery
{
public:
// . . .
private:
const double bVoltage; // volts
const double bMaxEnergy; // joules
double bEnergy; // joules
}; // Battery
! , bVoltage bMaxEnergy
; -
()
. :
Battery( double v = 12, double me = 5e6 );
:
Battery::Battery( double v, double me )
: bVoltage( v ), bMaxEnergy( me )
{
if ( v <= 0 )
throw BatteryXptn( "Battery", BatteryXptn::voltageErr, v );
738 21

if ( me <= 0 )
throw BatteryXptn( "Battery", BatteryXptn::energyErr, me );
bEnergy = bMaxEnergy;
} // Battery::Battery
, .
.


21-1 :
string os1( 7, '#' );
os1 "#######". BString
.


21-2 setToday() Date
.
21-3 , today(), Date
. ; -
.

22

:
.

.
.
:
-
. -
.
:

friend
friend

pimpl
:
22.1 : .................................................................................. 740
22.2 ...................................................................................................................... 741
22.3 friend ..................................................................................................... 743
22.4 ........................................................................................................................ 744
22.5 ......................................................................................................................................... 744
22.5.1 ...........................................................................................................................745
22.5.2 ..........................................................................................................................746
22.6 - ................................................................................................... 746
22.6.1 .........................................................................................................................................746
22.6.1.1 [] BString ............................................................................................................... 747
22.6.1.2 += BString ............................................................................................................... 747
22.6.1.3 += Date..................................................................................................................... 749
22.6.1.4 * C ........................................................................................................................................ 749
22.6.1.5 * forward() ......................................................................................................................... 750
22.6.1.6 * ++ Date () ........................................................................................................... 751
22.6.2 () ....................................................................................................................751
22.6.2.1 * - ........................................................................................................... 754
22.6.3 ................................................................................................................................................754
22.7 .......................................................................................................................... 755
22.7.1 @= @ .....................................................................................................................................756
22.7.2 .....................................................................................................................................757
22.7.3 BString ..................................................................................................................757
22.7.3.1 * ............................................................................................................................... 760
22.8 Vector3 ............................................................................................................................ 760
22.9 ++ - ............................................................................. 761
739
740 22

22.9.1 ->.......................................................................................................................................764
22.10 * pimpl.......................................................................................... 764
- ............................................................................................................................................. 770
.............................................................................................................................................................................770

:
, ,
. , , .
;
, -
( , ). ..

T T ==,

<.
!
next nextDay epomenh epomeni epom ++ !
:
,
.
14.6 20
21 =.
, , -
( ) 14.6.4.

22.1 :
,
::, ., .*, ?:
: -
operator@ @.
== 15.5.1:
bool operator==( const Date& lhs, const Date& rhs )
{
return ( lhs.year == rhs.year && lhs.month == rhs.month &&
lhs.day == rhs.day );
}; // operator==( const Date
19.1.4:
bool operator==( const Date& lhs, const Date& rhs )
{
return ( lhs.getYear() == rhs.getYear() &&
lhs.getMonth() == rhs.getMonth() &&
lhs.getDay() == rhs.getDay() );
}; // operator==( const Date
; 19 Date private! -
get
inline. -
;
: , , -
++ Date. lastDay() -
private.
741

get
:
.
()
.
. , ,
, , .

- get inline.
: = BString. -
:
BString& BString::operator=( const BString& rhs );
, a = rhs
*this a. 1,
19.1 19.1.1 :
BString& operator=( BString& lhs, const BString& rhs );
= :
(*this).
, = a a
= .
( : +=, []
) .
.

. == BString: :
bool BString::operator==( const BString& rhs ) const;
a == "qwerty" "qwerty" == a
"qwerty" BString. :
.

.

22.2
14.6,
:
.
.
-
.
- .
=
BString assign(). =
:
BString& operator=( const BString& rhs );

1 =
742 22

assign(), -
:
BString& assign( const BString& rhs );
; ;
, . -
, ,
.

operator=() assign() . 20.4.1
operator= inline assign() :
BString& assign( const BString& rhs ) { return (*this = rhs); }
, :
BString a, b;
:
b.assign( a );
b = a.
assign(), inline
BString& operator=( const BString& rhs )
{ return ( this->assign(rhs) ); }
, :
b = a;
b.assign( a ).
-
.
, +=,
append() BString +=, forward(), Date.
:
, a b,
a b a.
, ..:
+ +=. BString
std::string . a + b
a b
a b. a += b a b
a. , + +=
, +=.
+ - . ,
Date +
+: Date int y Date
: d1 = d + n d1 n
d. +=
d += n d = d + n
- .
++: ++d d = d + 1 d += 1.
, forward, +=
+= + ++.
++ . . 22-1
, , -, -- -=.
743

+, +=, ++, -, -=,


.
*, *=,/, /= ...
:
; ,
!
...

22.3 friend
-
.
C++ : , -
Date, (friend) (), operator==():
class Date
{
friend bool operator==( const Date& lhs, const Date& rhs );
public:
Date();
// . . .
;
friend () ,
.
, , :
bool operator==( const Date& lhs, const Date& rhs )
{
return ( lhs.dYear == rhs.dYear && lhs.dMonth == rhs.dMonth &&
lhs.dDay == rhs.dDay );
}; // operator==( const Date
.
get -
inline.
, ,
:
class Date
{
friend bool operator==( const Date& lhs, const Date& rhs )
{
return ( lhs.dYear == rhs.dYear && lhs.dMonth == rhs.dMonth &&
lhs.dDay == rhs.dDay );
}; // operator==( const Date
public:
Date();
// . . .
( : operator==())
inline.
. ..:
class A
{
friend class B;
public:
// ...
744 22

B friend
A,
A. :
.
: B friend A -
friend B A.
, -
.
, == = .
.
,
friend (-) (-) .
:
class Date;

class K
{
public:
K( int aa=5 ) { a = aa; };
int f( const Date& d ) const;
int g( const Date& d ) const;
private:
int a;
}; // K
:
class Date
{
friend int K::f( const Date& d ) const;
// . . .
K::f d
K::g.
class Date; ; ...

22.4

class K
{
// . . .
int f( const Date& d ) const;
// . . .
Date. -
(forward declaration)
class Date;

.

22.5
14.6.4
.
.
745

22.5.1
14.6.4:
@
Trv operator@( T a )
Trv , T .
, C :
T C& ( ):
Trv operator@( )
T C const C& :
Trv operator@( ) const


++ Date. ;
. ;
C++ (C) .
14.6.4 :
Date& operator++( Date& a )
:
Date& Date::operator++()
{
if ( dDay < lastDay(dYear, dMonth) )
++dDay;
else //
{
dDay = 1;
if ( dMonth < 12 )
++dMonth;
else //
{
dMonth = 1;
++dYear;
} // if ( dMonth...
} // if ( dDay...
return *this;
} // Date::operator++
;
Date d1( 2011, 3, 31 );
cout << d1 << endl;
++d1;
cout << d1 << endl;
++d1 :
d1.operator++();
;
++ ( )
friend last-
Day, private.
:
22.2, ++ Date
...

.
746 22

22.5.2
14.6.4:
@
Trv operator@( T a, int )
Trv , T .
: C
T C& C:
Trv operator@( int )
T C const C& :
Trv operator@( int ) const


++ Date. T
Date&. :
Trv operator++( int )
Trv ; Date Date&;
.
.
Date&. :
Date operator++( int )
,
++:
Date Date::operator++( int )
{
Date sv( *this );
++(*this);
return sv;
} // Date::operator++(int)

22.6 -
- -
. (-
const).

22.6.1
14.6.4:
@
Trv operator@( Tl a, Tr b )
Trv , Tl Tr
.
: , Tl C& C
const C& C :
Tl C& :
Trv operator@( Tr b )
Tl C const C& :
Trv operator@( Tr b ) const
747

[] BString +=
BString Date.

22.6.1.1 [] BString
:
string q( "qazwsx" );
:
cout << q << " " << q[2] << endl;
:
qazwsx z
:2
q[2] = 'a';
cout << q << endl;
:
qaawsx
BString, [] :
char& operator[]( BString a, int b )
char& (-l) char.

char& operator[]( int pos ) const { return bsData[pos]; }
, :
BString q( "qazwsx" );
:
cout << q.c_str() << " " << q[2] << endl;
q[2] = 'a';
cout << q.c_str() << endl;
:
qaawsx
qaawsx a
:
cout << q.c_str() << " " << q.operator[](2) << endl;
q.operator[](2) = 'b';
cout << q.c_str() << endl;

22.6.1.2 += BString
"+="
.3 :
BString& operator+=( BString& lhs, const BString& rhs )
:
s0 += s1;
:
BString& BString::operator+=( const BString& rhs )

2 : std::string at operator[]
at
operator[] .
3 s1, s2 , s1 += s2 s1 s1^s2, ^
.
748 22

. (
s0 rhs s1):
. ; bsLen + rhs.bsLen + 1
bsReserved. :
for ( int j(0), k(bsLen); j < rhs.bsLen; ++j, ++k )
bsData[k] = rhs.bsData[j];
bsLen += rhs.bsLen;
bsLen + rhs.bsLen + 1 > bsReserved .
BString& BString::operator+=( const BString& rhs )
{
if ( bsLen + rhs.bsLen + 1 > bsReserved )
{
char* tmp;
size_type tmpRes( ((bsLen+rhs.bsLen+1)/bsIncr+1)*bsIncr );
try { tmp = new char[tmpRes]; }
catch( bad_alloc )
{ throw BStringXptn( "operator+=",
BStringXptn::allocFailed ); }
for ( int k(0); k < bsLen; ++k ) tmp[k] = bsData[k];
delete[] bsData;
bsData = tmp;
}
for ( int j(0), k(bsLen); j < rhs.bsLen; ++j, ++k )
bsData[k] = rhs.bsData[j];
bsLen += rhs.bsLen;
return *this;
} // BString::operator+=
,
(
).
:
BString s2( "qazwsxedcrf" ), s3( "res" ), s4( "qwerty" );

cout << s2.c_str() << " " << s2.length() << endl
<< s3.c_str() << " " << s3.length() << endl
<< s4.c_str() << " " << s4.length() << endl;

s4 += s3;
cout << s4.c_str() << " " << s2.c_str() << " "
<< s3.c_str() << endl;
s4 += s2;
cout << s4.c_str() << " " << s2.c_str() << " "
<< s3.c_str() << endl;
:
qazwsxedcrf 11
res 3
qwerty 6
qwertyres qazwsxedcrf res
qwertyresqazwsxedcrf qazwsxedcrf res
: s4.operator+=(s3) s4 += s3
s4.operator+=(s2) s4 += s2 .
string append "+=".
(
void):
append operator+=:
BString& BString::append( const BString& rhs )
// operator+=
, , (inline)
749

BString& append( const BString& rhs ) { return (*this += rhs); }

22.6.1.3 += Date
Date, forword,
. , :
Date d( 2007, 10, 15 );
:
d.forward( 5 );
d 5 20.10.2007.
, forward(d, 5) -
void.
+=,
. : d += 5
d.
; , : ++.
++d d += 1 .
:
Date& operator+=( Date a, int dd )

Date& operator+=( long int dd );
forword() . :
Date& forward( long int dd );

C. -
.

22.6.1.4 * C

ctime:
#include <ctime>
:
time_t time( time_t* timer );
01.01.1970, 00:00:00 GMT4.
time_t long int.
:
time_t t1;
: t1 = time(0) time(&t1).
t1 0, 01.01.1970,
00:00:00 GMT ( 02:00:00 ). LONG_MAX
19.01.2038, 03:14:07 GMT ( 05:14:07 ).

tm* localtime( const time_t* timer );
time_t :
struct tm
{
int tm_sec; // seconds
int tm_min; // minutes

4 GMT: Greenwich Mean Time. (02:00:00)


750 22

int tm_hour; // hour (0 - 23)


int tm_mday; // day of month (1 - 31)
int tm_mon; // month (0 - 11)
int tm_year; // year ( - 1900)
int tm_wday; // (0 6, 0 )
int tm_yday; // (0 -365)
int tm_isdst; // .
}; // struct tm

time_t mktime( tm* t );
Date;
:
Date d1;
t1 time_t d1.
:
tm tm1;
:
tm1.tm_sec = 0;
tm1.tm_min = 0;
tm1.tm_hour = 12; //
tm1.tm_mday = d1.dDay;
tm1.tm_mon = d1.dMonth - 1;
tm1.tm_year = d1.dYear - 1900;
tm1.tm_wday = 0;
tm1.tm_yday = 0;
tm1.tm_isdst = 0;
mktime():
t1 = mktime( &tm1 );
, t1 d1 :
tm1 = *localtime( &t1 );
:
d1.dYear = tm1.tm_year + 1900;
d2.dMonth = tm1.tm_month + 1;
d2.dDay = tm1.tm_day;

22.6.1.5 * forward()

Date& Date::forward( int dd );
:
:
tm currD = { 0, 0, 12, dDay, dMonth-1, dYear-1900, 0, 0, 0 };
time_t currT( mktime(&currD) );
dd 246060dd (= 86400dd) :
dd *= 86400; //
dd currT:
currT += dd;
, time_t Date:
currD = *localtime( &currT );
dYear = currD.tm_year+1900;
dMonth = currD.tm_mon+1;
dDay = currD.tm_mday;
:
Date& Date::forward( long int dd )
751

{
const unsigned long secsPerDay = 86400;
tm currD = { 0, 0, 12, dDay, dMonth-1, dYear-1900, 0, 0, 0 };
time_t currT( mktime(&currD) );
dd *= secsPerDay; //
if ( dd < 0 )
{
if ( currT < (-dd) ) // currT + dd < 0
throw DateXptn( "operator+=", DateXptn::outOfLimits,
dd/secsPerDay, *this );
}
else // dd >= 0
{
if ( dd > LONG_MAX - currT ) // currT + dd > LONG_MAX
throw DateXptn( "operator+=", DateXptn::outOfLimits,
dd/secsPerDay, *this );
}
currT += dd;
currD = *localtime( &currT );
dYear = currD.tm_year+1900;
dMonth = currD.tm_mon+1;
dDay = currD.tm_mday;
return *this;
} // Date::forward
if .
+= (inline)
Date& operator+=( long int dd ) { return forward( dd ); }

22.6.1.6 * ++ Date ()
, 22.2,
++ :
Date& operator++() { return forward( 1 ); }
,
; , !

22.6.2 ()

(). C:
struct C
{
// . . .
double operator()( double x ) const;
// . . .
};

C f;
:
if ( f(a)*f(b) < 0 ) m = f(a) + c/2;
// . . .
, f .
(function objects,
functors).
, , -
-
752 22

( [])
, , .
; : -
.

bisection() 14.3.
. , ;
. 2 14.7.1 -
.
; :
bisection()
f f(x) = 0 .
, -!

. :
template < class Func >
void bisection( double a, double b, double epsilon,
double& root, int& errCode )
{
Func f;
double m;

if ( f(a)*f(b) > 0 )
errCode = 1;
else
{
while ( fabs(b - a)/2 >= epsilon )
{
m = (a + b) / 2;
if ( f(a)*f(m) <= 0.0 ) b = m;
else a = m;
} // while
root = m;
errCode = 0;
} // if
} // bisection
, Func, f, -
, f(a), f(b), f(m).
, :
class qF
{
public:
double operator()( double x ) const
{ return ( x - log(x) - 2 ); }
}; // qF

class cosF
{
public:
double operator()( double x ) const
{ return cos( x ); }
}; // cosF
:
bisection< qF >( 0.1, 1.0, 1e-5, riza, errCode );
if ( errCode != 0 ) cout << "o " << endl;
else cout << " = " << riza << endl;
bisection< cosF >( 0.0, pi, 1e-5, riza, errCode );
if ( errCode != 0 ) cout << "o " << endl;
753

else cout << " = " << riza << endl;


: bisection()

q(x) = 0
(x) = 0.
.
, qFXptn qF :
struct qFXptn
{
enum { domain };
char funcName[100];
int errorCode;
double errDblVal;
qFXptn( const char* mn, int ec, double dv=0.0 )
: errorCode( ec ), errDblVal( dv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // qFXptn

class qF
{
public:
double operator()( double x ) const
{
if ( x <= 0 )
throw qFXptn( "operator()", qFXptn::domain, x );
return ( x - log(x) - 2 );
}
}; // qF
:
try {
// . . .
bisection< qF >( -1, 1.0, 1e-5, riza, errCode );
// . . .
}
catch( qFXptn& x )
{
cout << "domain error (" << x.errDblVal << ")" << endl;
}
:
domain error (-1)


bool mult7( int a ) { return ( (a%7) == 0 ); }
true 7, false. -
(predicate).

#include <iostream>
using namespace std;

struct Mult7
{
bool operator()( int a ) { return ( (a%7) == 0 ); }
};

int main()
{
Mult7 aMult7;

cout << boolalpha;


754 22

cout << aMult7(35) << " " << aMult7(37) << endl;
}
:
true false
, bool, -
.

22.6.2.1 * -
21.12
.
;
SList::toFile() .
; , C++ .
:
class SList
{
public:
// . . .
template < class OutFunc >
void toFile( ostream& out ) const
{
OutFunc toStream;
for ( ListNode* p(slHead); p != slTail; p = p->lnNext )
toStream( out, p->lnData );
} // toFile
// . . .
};
,
save(), display() writeToTable() GrElmn:
struct SaveGE
{
void operator()( ostream& bout, const GrElmn& geObj )
{ geObj.save( bout ); }
}; // SaveGE

struct DisplayGE
{
void operator()( ostream& tout, const GrElmn& geObj )
{ geObj.display( tout ); }
}; // DisplayGE

struct WriteToTableGE
{
void operator()( ostream& tout, const GrElmn& geObj )
{ geObj.writeToTable( tout ); }
}; // writeToTableGE

lst.toFile< DisplayGE >( tout );
SList .

22.6.3

Trv operator@( Tl a, Tr b )
:
755

Tl , , .
Tr , ,
,
. ,
14.6.4.
, 15.5 << Date :
ostream& operator<<( ostream& tout, const Date& rhs )
:
ostream,
Date .
19.1.4 :
ostream& operator<<( ostream& tout, const Date& rhs )
{
return tout << rhs.getDay() << '.' << rhs.getMonth() << '.'
<< rhs.getYear();
} // operator<<( ostream& tout, const Date
friend; , get inline.
<< BString:
ostream& operator<<( ostream& tout, const BString& rhs )
{
return tout << rhs.c_str();
} // operator<<( ofstream, BString
. c_str()
( ) \0 . 20.1

BString \0 .
bsData "ab\0cd" d
b. :
ostream& operator<<( ostream& tout, const BString& rhs )
{
for ( int k(0); k < rhs.bsLen; ++k ) tout << rhs.bsData[k];
return tout;
} // operator<<( ofstream, BString
:
class BString
{
friend ostream& operator<<( ostream& tout, const BString& rhs );
public:
// . . .
length() operator[] inline
:
ostream& operator<<( ostream& tout, const BString& rhs )
{
for ( int k(0); k < rhs.length(); ++k ) tout << rhs[k];
return tout;
} // operator<<( ofstream, BString
friend.

22.7


+, . 22.1
756 22

== BString .
+ ( ).

friend .
, BString +
BString operator+( const BString lhs, const BString rhs );
; += .

22.7.1 @= @
+= (: @=) + (: @) :
BString operator+( const BString& lhs, const BString& rhs )
{
BString fv( lhs );
fv += rhs;
return fv;
} // BStribg operator+
, "+=".
: BString& BString. ;

. += ( append)
(*this) .

friend.
" +"
Date; , .
-
+=. ; : d = d + 5 d += 5 (d.for-
watd(5)) .
.
:
:
Date d( 2007, 10, 15 ), d1;
:
d1 = d + 5;

d1 = 5 + d;
.
, :5
+: Date int y Date
+: int Date y Date

. , BString
:
Date operator+( const Date& lhs, int rhs )
{
Date fv( lhs );
fv += rhs;
return fv;
} // Date operator+

5 ; += .
757

Date operator+( int lhs, const Date& rhs )


{
return ( rhs + lhs );
} // Date operator+
, Date& Date,
BString.

22.7.2
6 -
( ) . , ==
< Date, 19.1.4 .

:7
@
@.
== < !=
>= :
bool operator!=( const Date& lhs, const Date& rhs )
{ return !(lhs == rhs); }

bool operator>=( const Date& lhs, const Date& rhs )


{ return !(lhs < rhs); }
:
Date (21.13.1):
explicit Date( int yp, int mp = 1, int dp = 1 );
d == 2013 2013 == d , , d ==
Date(2013) Date(2013) == d . ,
== ( ) (
), ..:
bool Date::operator==( const Date& rhs ) { /*. . .*/ }
BString, explicit,
.

22.7.3 BString
(==,
<, ) BString. -
, .
:
char lhs[10], s2[12];
len1 len2. :
minLen = min( len1, len2 );

6 ; , < : lhs <


rhs true rhs < lhs false.
, .
7 36 (ELLEMTEL 1998) : When two operators are opposites (such as == and !=), it is
appropriate to define both. Project 2 (Prj02.3).
758 22

lhs[len1] s2[len2] '\0',


:
k = 0;
while ( lhs[k] == s2[k] && k < minLen-1 ) ++k;
d = static_cast<int>(lhs[k]) - static_cast<int>(s2[k]);
d :
) lhs abcd s2 : abcd. minLen = min(4, 4) = 4
lhs[k] == s2[k] k 0 2 while k == 3.
lhs[3] == s2[3] == '\0' d 0.
) lhs abcd s2: abce. minLen = min(4, 4) = 4
lhs[k] == s2[k] k 0 2 while k == 3.
lhs[3] == 'd' s2[3] == 'e' d static_cast<int>('d') -
static_cast<int>('e') = 100 - 101 = -1 < 0.
) lhs abcd s2: abcc. minLen = min(4, 4) = 4
lhs[k] == s2[k] k 0 2 while k == 3.
lhs[3] == 'd' s2[3] == 'c' d static_cast<int>('d') -
static_cast<int>('c') = 100 - 99 = 1 > 0.
:
lhs () s2 ( ) d
.
lhs s2 ( ) d .
lhs s2 ( ) d 0 ().
, ' , -
. ' .
:
) lhs ab s2: abcd. minLen = min(2, 4) = 2
lhs[k] == s2[k] k == 0 while k == 1. lhs[1] == 'b'
s2[1] == 'b' d static_cast< int>('b') - static_cast<int>('b') = 98 - 98
= 0.
) lhs abcd s2: ab. minLen = min(4, 2) = 2
lhs[k] == s2[k] k == 0 while k == 1. lhs[1] == 'b'
s2[1] == 'b' d static_cast< int>('b') - static_cast<int>('b') = 98 - 98
= 0.
) lhs ab_ s2: ab. minLen = min(3, 2) = 2
lhs[k] == s2[k] k == 0 while k == 1. lhs[1] == 'b'
s2[3] == 'b' d static_cast< int>('b') - static_cast<int>('b') = 98 - 98
= 0.
d == 0 . -
; . ,
,
.
, -, BString,
8:
int BString::stringCmpr( const char* lhs, const char* rhs, int n )
{
int k( 0 );
while ( lhs[k] == rhs[k] && k < n-1 ) ++k;
return ( static_cast<int>(lhs[k]) - static_cast<int>(rhs[k]) );

8 STL
Silicon Graphics Inc (SGI).
759

} // BString::stringCmpr
stringCmp()9 n (0 .. n-1) lhs s2
:
n lhs (-
) n s2,
n lhs n -
s2,
0 () n lhs n
s2.
n:
stringCmpr().
string 10 :
int compare( const BString& rhs ) const;
int compare( int pos, int n, const BString& rhs) const;
int compare( int pos, int n,
const BString& rhs, int pos2, int n2 ) const;
compare()
stringCmpr(). stringCmpr()
BString.
:
BString bs1, bs2;
bs1.compare(bs2) ,
0 , , bs1 ,
bs2. :
int BString::compare( const BString& rhs ) const
{
int fv( stringCmpr(bsData, rhs.bsData, min(bsLen, rhs.bsLen)) );
if ( fv == 0 ) fv = bsLen - rhs.bsLen;
return fv;
} // BString::compare
. -
. :
bool operator==( const BString& lhs, const BString& rhs )
{
int fv( BString::stringCmpr(lhs.bsData, rhs.bsData,
min(lhs.bsLen, rhs.bsLen)) );
if ( fv == 0 ) fv = lhs.bsLen - rhs.bsLen;
return ( fv == 0 );
} // operator==
, operator< Date,
friend () operator==:
class BString
{
friend bool operator==( const BString& lhs, const BString& rhs );
public:
BString( const char* cs = "" );
// ...
.

9 stringCmpr() , lastDay() leapYear() Date.


10 . string .
760 22

22.7.3.1 *
-
. -
. -
928 :
.
(collating sequence).
.
256 :
int cs[256];
cs -
. ..:
for ( int k = 0; k <= 255; ++k ) cs[k] = k;
// ...
//
cs[''] = cs['a'] = 65;
cs['B'] = cs['b'] = 66;
// ...
//
cs[256+''] = cs[256+''] = cs[256+''] = cs[256+''] = 161;
cs[256+''] = cs[256+''] = 162;
// ...
cs[256+''] = cs[256+''] = cs[256+''] = cs[256+'']
= cs[256+''] = cs[256+''] = cs[256+''] = 213;
// ...
, ( signed) char, -
11. . 3.
stringCmpr() :
int BString::stringCmprCS( const char* lhs, const char* rhs, int n ) const
{
int k = 0;

while ( cs[ lhs[k] ] == cs[ rhs[k] ] && k < n-1) ++k;


return ( cs[ lhs[k] ] - cs[ rhs[k] ] );
} // BString::stringCmprCS

22.8 Vector3
Vector3, Project 2,
.
: Vector3 ,
-
. Project 2 . -

.
() - (). v = (x, y, z)
-v = (-x, -y, -z). 14.6.4 :
Vector3 operator-( Vector3 rhs )
( ) 22.3.1
:
Vector3 operator-() const { return Vector3( -x, -y, -z ); }

11 cs[256+static_cast<int>('')] = 193
.
761
lnNext
-
... lnData ...
+=, -=, *=:
Vector3& Vector3::operator+=( const Vector3& rhs )
{
x += rhs.x; y += rhs.y; z += rhs.z; iPNode
return *this;
} // Vector3::operator+= . 22-1 :
, iPNode,
Vector3& Vector3::operator-=( const Vector3& rhs )
{
x -= rhs.x; y -= rhs.y; z -= rhs.z; .
return *this;
} // Vector3::operator-=

Vector3& Vector3::operator*=( double rhs )


{
x *= rhs; y *= rhs; z *= rhs;
return *this;
} // operator*=( const Vector3&
abs() abs2():
double abs2() const { return x*x + y*y + z*z; }
double abs() const { return sqrt( abs2() ); }

operator+, operator-, operator* 22.6.1, ..:
Vector3 operator+( const Vector3& lhs, const Vector3& rhs )
{
Vector3 fv( lhs );
fv += rhs;
return fv;
} // operator+( const Vector3&

22.9 ++ -
21.11 :
. ...
. ,
- p = p->lnNext
p->lnNext .
:
++n n ,
++d d
++ p .
() * *p p->lnData.
-.
, : C++
. :
(iterator) , ! . 22-1
. :
class SList
{
private:
struct ListNode
{
GrElmn lnData;
ListNode* lnNext;
}; // ListNode
762 22

public:
class Iterator
{
public:
// . . .
terator& operator++()
{ iPNode = iPNode->lnNext; return *this; };
GrElmn& operator*() { return ( iPNode->lnData ); }
private:
ListNode* iPNode;
}; // Iterator

SList();
// . . .
private:
ListNode* slHead;
ListNode* slTail;
// . . .
}; // SList
:
SList private.
private ListNode

ListNode* iPNode;
, , ++
*. !
SList; begin() end()
. :
Iterator begin() { return Iterator( slHead ); }
Iterator end() { return Iterator( slTail ); }
:
explicit Iterator( ListNode* p = 0 ) { iPNode = p; }
; :
for ( SList::Iterator it(lst.begin());
it != lst.end();
++it )
writeRandom( *it, bInOut );
:
it lst.begin() lst.end().
++it.12
-
*it.
: !=.
:
bool operator!=( const SList::Iterator& a, const SList::Iterator& b )
{ return ( a.iPNode != b.iPNode ); }
friend.
explicit Iterator
:

12 :
( ++).
(forward) .
( --).
(bidirectional).
763

bool operator!=( const Iterator& rhs ) const


{ return ( iPNode != rhs.iPNode ); }
:
bool operator==( const Iterator& rhs ) const
{ return ( !(*this != rhs) ); }
;
.
SListXptn.
++ :
SList::Iterator& SList::Iterator::operator++()
{
if ( iPNode->lnNext == 0 )
throw SListXptn( "Iterator::operator++", SListXptn::listEnd );
iPNode = iPNode->lnNext;
return *this;
} // SList::Iterator::operator++
*:
GrElmn& SList::Iterator::operator*()
{
if ( iPNode->lnNext == 0 )
throw SListXptn( "Iterator::operator*", SListXptn::listEnd );
return ( iPNode->lnData );
} // SList::Iterator::operator*
SList :
class SList
{
private:
struct ListNode
{
GrElmn lnData;
ListNode* lnNext;
}; // ListNode
public:
class Iterator
{
friend bool operator!=( const Iterator& a, const Iterator& b);
public:
explicit Iterator( ListNode* p = 0 ) { iPNode = p; }
Iterator& operator++();
GrElmn& operator*();
bool operator!=( const Iterator& rhs ) const
{ return ( iPNode != rhs.iPNode ); }
bool operator==( const Iterator& rhs ) const
{ return ( !(*this != rhs) ); }
private:
ListNode* iPNode;
}; // Iterator

SList();
SList( const SList& rhs );
~SList();
SList& operator=( const SList& rhs );
void swap( SList& rhs );
Iterator begin() { return Iterator( slHead ); }
Iterator end() { return Iterator( slTail ); }
// . . .
}; // SList

struct SListXptn
{
enum { noMemory, notFound, listEnd };
// . . .
764 22

}; // SListXptn
:
++ * -
== GrElmn (std::)find()
.
21.11 SList,
include <algorithm> main, do-while,
:
do {
readAtNo( maxAtNo, aa );
if ( aa != 0 )
{
SList::Iterator it;
it = std::find( lst.begin(), lst.end(), GrElmn(aa) );
if ( it != lst.end() ) (*it).display( cout );
else cout << "not found" << endl;
}
} while ( aa != 0 );

do-while .

22.9.1 ->
-> SList::Iterator
(*it).display(cout)

it->display(cout)
.
-> , , : ( -
)
. (
). ( ) -
operator*(). operator*() iPNode->lnData :
GrElmn* operator->() const
{
if ( iPNode->lnNext == 0 )
throw SListXptn( "Iterator::operator->",
SListXptn::listEnd );
return ( &(iPNode->lnData) );
} // SList::Iterator::operator->
-
-> . :
(&(iPNode->lnData))->display(cout)
:
(iPNode->lnData).display(cout)
it->display(cout) :
(it.operator->())->display(cout)

22.10 * pimpl
19.3:
(
19.3.1).
765

:
C ( ) C.obj ( C.o)
C.h
public . private
C.obj.
.
: private .
.
BString, , :
class BString
{
friend bool operator==( const BString& lhs, const BString& rhs );
friend ostream& operator<<( ostream& tout, const BString& rhs );
public:
BString( const char* rhs="" );
BString( const BString& rhs );
~BString();
BString& operator=( const BString& rhs );
BString& assign( const BString& rhs ) { return (*this = rhs); }
const char* c_str() const;
size_type length() const { return bsLen; }
bool empty() const { return ( bsLen == 0 ); }
char& at( int k ) const;
char& operator[]( int pos ) const { return bsData[pos]; }
BString& operator+=( const BString& rhs );
BString& append( const BString& rhs )
{ return (*this += rhs); }
void swap( BString& rhs );
int compare( const BString& rhs ) const;
private:
enum { bsIncr = 16 };
char* bsData;
size_type bsLen;
size_type bsReserved;

static size_type cStrLen( const char* cs );


static int stringCmpr( const char* lhs, const char* rhs,
int n );
}; // BString

BString operator+( const BString& lhs, const BString& rhs );


: :
struct BStringImpl
{
enum { bsIncr = 16 };
char* bsData;
size_type bsLen;
size_type bsReserved;

static size_type cStrLen( const char* cs );


static int stringCmpr( const char* lhs, const char* rhs,
int n );
}; // BStringImpl
private :
private:
BStringImpl* bsHandle;
}; // BString
bsHandle
BStringImpl:
struct BStringImpl;
766 22

.
BString (
BString.h). .
.
public :
class BString
{
friend bool operator==( const BString& lhs, const BString& rhs );
friend ostream& operator<<( ostream& tout, const BString& rhs );
public:
BString( const char* rhs="" );
BString( const BString& rhs );
~BString();
BString& operator=( const BString& rhs );
BString& assign( const BString& rhs );
const char* c_str() const;
size_type length() const;
bool empty() const;
char& at( int k ) const;
char& operator[]( int pos ) const;
BString& operator+=( const BString& rhs );
BString& append( const BString& rhs );
void swap( BString& rhs );
int compare( const BString& rhs ) const;
private:
struct BStringImpl;
BStringImpl* bsHandle;
}; // BString

BString operator+( const BString& lhs, const BString& rhs );


BString.cpp.
.
, ,
BStringImpl BStringImpl.h BStringImpl.cpp.
#include "BStringImpl.h" #include "BStringImpl.cpp"
BString.cpp.
:
() : pointer to ( private)
implementation ( ). handle
class, Cheshire Cat compiler firewall. BStringImpl (opaque)
bsHandle
(handle).

API .
.
:
BString::BString( const char* rhs )
{
try { bsHandle = new BStringImpl( rhs ); }
catch( bad_alloc& )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
} // BString::BString
:
BStringImpl( const char* rhs="" );
BStringImpl:
BString::BStringImpl::BStringImpl( const char* rhs )
{
bsLen = cStrLen( rhs );
767

bsReserved = ((bsLen+1)/bsIncr+1)*bsIncr;

bsData = new char[bsReserved];


for ( int k(0); k < bsLen; ++k ) bsData[k] = rhs[k];
} // BString::BStringImpl::BStringImpl
BString::BStringImpl.
new bad_alloc catch
BString. :
BStringImpl a;
bad_alloc ;
private BString
.
BStringImpl
:
BString::BString( const BString& rhs )
{
try { bsHandle = new BStringImpl( *(rhs.bsHandle) ); }
catch( bad_alloc& )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
} // BString::BString
new BStringImpl( *(rhs.bsHandle) )
BStringImpl. bsData
:
BString::BStringImpl::BStringImpl( const BString::BStringImpl& rhs )
{
bsData = new char[rhs.bsReserved];
bsReserved = rhs.bsReserved;
for ( int k(0); k < rhs.bsLen; ++k )
bsData[k] = rhs.bsData[k];
bsLen = rhs.bsLen;
} // BString::BStringImpl::BStringImpl
bad_alloc -
.
() -
:
BString& BString::operator=( const BString& rhs )
{
if ( &rhs != this )
{
try { BString tmp( rhs );
swap( tmp ); }
catch( BStringXptn& x )
{ strcpy( x.funcName, "operator=" );
throw; }
}
return *this;
} // BString::operator=
21.6.1 ( ) -
swap():
void BString::swap( BString& rhs )
{
std::swap( bsHandle, rhs.bsHandle );
} // BString::swap

BStringImpl:
BString::BStringImpl& BString::BStringImpl::operator=(
const BString::BStringImpl& rhs )
768 22

{
BString::BStringImpl tmp( rhs );
if ( &rhs != this )
swap( tmp );
return *this;
} // BString::BStringImpl::BStringImpl& operator=
,
BString.
:
BString::~BString() { delete bsHandle; }

BString::BStringImpl::~BStringImpl() { delete bsData; }


BStringImpl ; swap():
void BString::BStringImpl::swap( BString::BStringImpl& rhs )
{
std::swap( bsData, rhs.bsData );
std::swap( bsLen, rhs.bsLen );
std::swap( bsReserved, rhs.bsReserved );
} // BString::BStringImpl::swap
BString::swap .
BString :

bsHandle-> bsData, bsLen, bsReserved.
BStringImpl:: bsIncr ()
cStrLen, stringCmpr.
+=:
BString& BString::operator+=( const BString& rhs )
{
if ( bsHandle->bsLen + (rhs.bsHandle)->bsLen + 1 >
bsHandle->bsReserved )
{
char* tmp;
size_type tmpRes( ((bsHandle->bsLen+(rhs.bsHandle)->bsLen+1)/
BStringImpl::bsIncr+1)*BStringImpl::bsIncr );
try { tmp = new char[tmpRes]; }
catch( bad_alloc& )
{ throw BStringXptn( "operator+=",
BStringXptn::allocFailed ); }
for ( int k(0); k < bsHandle->bsLen; ++k )
tmp[k] = bsHandle->bsData[k];
delete[] bsHandle->bsData;
bsHandle->bsData = tmp;
}
for ( int j(0), k(bsHandle->bsLen);
j < (rhs.bsHandle)->bsLen;
++j, ++k )
bsHandle->bsData[k] = (rhs.bsHandle)->bsData[j];
bsHandle->bsLen += (rhs.bsHandle)->bsLen;
return *this;
} // BString::operator+=
:
if
bsLen + rhs.bsLen + 1 > bsReserved

bsHandle->bsLen + (rhs.bsHandle)->bsLen + 1 > bsHandle->bsReserved
tmpRes BStringImpl::bsIncr bsIncr.
for
bsHandle->bsData[k] = (rhs.bsHandle)->bsData[j];
769


bsData[k] = rhs.bsData[j];
== <<
friend:13
ostream& operator<<( ostream& tout, const BString& rhs )
{
for ( int k(0); k < (rhs.bsHandle)->bsLen; ++k )
tout << (rhs.bsHandle)->bsData[k];
return tout;
} // operator<<( ofstream, BString

bool operator==( const BString& lhs, const BString& rhs )


{
int fv( BString::BStringImpl::stringCmpr(
(lhs.bsHandle)->bsData,
(rhs.bsHandle)->bsData,
min((lhs.bsHandle)->bsLen, (rhs.bsHandle)->bsLen)) );
if ( fv == 0 )
fv = (lhs.bsHandle)->bsLen - (rhs.bsHandle)->bsLen;
return ( fv == 0 );
} // operator==
18.3 BString.cpp (
BString.h) BString.o ( BString.obj).
BString.h :
#ifndef _BSTRING_H
#define _BSTRING_H

#include <fstream>
#include <string>

using namespace std;

class BString
{
friend bool operator==( const BString& lhs, const BString& rhs );
friend ostream& operator<<( ostream& tout, const BString& rhs );
public:
BString( const char* rhs="" );
BString( const BString& rhs );
~BString();
BString& operator=( const BString& rhs );
BString& assign( const BString& rhs );
const char* c_str() const;
size_type length() const;
bool empty() const;
char& at( int k ) const;
char& operator[]( int pos ) const;
BString& operator+=( const BString& rhs );
BString& append( const BString& rhs );
void swap( BString& rhs );
int compare( const BString& rhs ) const;
private:
struct BStringImpl;
BStringImpl* bsHandle;
}; // BString

BString operator+( const BString& lhs, const BString& rhs );

struct BStringXptn
{
enum { allocFailed, outOfRange };

13 + 22.6.1.
770 22

char funcName[100];
int errorCode;
int errorValue;
BStringXptn( char* mn, int ec, int ev = 0 )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec; errorValue = ev; }
}; // BStringXptn

#endif // _BSTRING_H
, BString.o (.obj) BString.h,
BString .
: -
( public -
)
.


22-1 -, -- -= Date
( ) .
22-2 Date BString.
project

4

:
Prj04.1 ............................................................................................................................................. 771
Prj04.2 Course ........................................................................................................................................ 772
Prj04.3 ... ............................................................................................................... 779
Prj04.3.1 add1Course() delete1Course() ......................................................................................783
Prj04.3.2 save() load() ....................................................................................................................................785
Prj04.3.3 ..............................................................................................................................786
Prj04.3.4 []; ......................................................................................................................787
Prj04.4 ........................................................................................................................................ 788
Prj04.5 Student ....................................................................................................................................... 788
Prj04.5.1 ..........................................................................................................................789
Prj04.5.2 get set............................................................................................................................790
Prj04.5.3 ........................................................................................................791
Prj04.5.4 ...............................................................................................................................793
Prj04.5.5 Student ......................................................................................................................................794
Prj04.6 ........................................................................................................................... 795
Prj04.6.1 , ...........................................................................................................798
Prj04.7 StudentInCourse ....................................................................................................................... 799
Prj04.8 StudentInCourseCollection ...................................................................................................... 802
Prj04.9 ............................................................................................................. 806
Prj04.10 ...................................................................................................................... 807
Prj04.10.1 CourseCollection ......................................................................................................................807
Prj04.10.2 StudentCollection .....................................................................................................................810
Prj04.11 1 .............................................................................................................. 812
Prj04.11.1 .......................................................................................813
Prj04.11.2 .................................................................................................................................815
Prj04.11.3 .......................................................................................................................................................816
Prj04.11.4 ... .................................................................................................................................816
Prj04.12 2 ......................................................................................................... 818
Prj04.13 ............................................................................................................................. 821

Prj04.1

Project 3. :
. Student
.
:
Student students.dta . ,
15.13. -

771
772 Project 04

-
(index)
struct IndexEntry
{
unsigned int sIdNum;
size_t loc;
}; // IndexEntry

index (-) students.ndx.
.
, -
.
:
/ /
students.dta.
.
.
, :
21.8,


: -
.
19.4.
: -
Project 3, -
-
. 21.8
.

Prj04.2 Course
Course -
Student:
Student -
.
.
linSearch()
!= cCode. :
char cCode[cCodeSz];
( ), CourseKey,
:
class Course
{
public:
enum { cCodeSz = 8 };
struct CourseKey
{
char s[cCodeSz];
explicit CourseKey( string aKey="" )
{ strcpy( s, aKey.c_str(), cCodeSz-1 ); s[cCodeSz-1] = \0; }
}; // CourseKey
// . . .
773

:
// . . .
private:
// . . .
CourseKey cCode; //
!= :
bool operator!=( const Course::CourseKey& lhs, const Course::CourseKey& rhs )
{ return ( strcmp(lhs.s, rhs.s) != 0 ); }
.
, :
((strlen(cCode.s) == cCodeSz-1) || (strlen(cCode.s) == 0)) && (strlen(cTitle) < cTitleSz) &&
(1 <= cFSem <= 8) && (cSector {,,,,})1 &&
(cCateg {,,,})2 && (cWH >= 0) && (cUnits >= 0) &&
((strlen(cPrereq.s) == cCodeSz-1) || (strlen(cPrereq.s) == 0)) &&
((strlen(cPrereq.s) == cCodeSz-1) (cPrereq != cCode)) &&
(cNoOfStudents >= 0)
:
1. strlen(cCode.s) == cCodeSz-1 strlen(cTitle) < cTitleSz :
7 (
. Prj03-1 .)
. -
80 . 80
79 (cTitleSz-1) .
2. strlen(cCode.s) == 0
Course c0 ( ).
3. cWH == 0 cUnits == 0
set.
4.
((strlen(cPrereq.s) == cCodeSz-1) || (strlen(cPrereq.s) == 0)) &&
((strlen(cPrereq.s) == cCodeSz-1) (cPrereq != cCode))
: -
. -
-
Course .
5. ( )

.
:
struct CourseXptn
{
enum { . . . };
Course::CourseKey objKey;
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
CourseXptn( const Course::CourseKey& obk, const char* mn, int ec,
const char* sv="" )
: objKey( obk ), errorCode( ec )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }

1 .
2 ...
774 Project 04

}; // CourseXptn
objKey.
.

objKey Course::cCodeSz
public Course.
, : :
Course c0;
Course c1( "0101" );
Course c2( "0101", " ()" );
21.11.1,
(
string), :
explicit Course( string aCode="", string aTitle="" );
:
Course::Course( string aCode, string aTitle )
{
if ( aCode.length() != cCodeSz-1 &&
(aCode.length() != 0 || aTitle.length() != 0) )
throw CourseXptn( CourseKey(""), "Course", CourseXptn::keyLen,
aCode.c_str() );
cCode = CourseKey( aCode );
strncpy( cTitle, aTitle.c_str(), cTitleSz-1 ); cTitle[cTitleSz-1] = '\0';
cFSem = 0;
cCompuls = false;
cCateg[0] = '\0';
cWH = 0;
cUnits = 0;
cPrereq = CourseKey( "" );
cNoOfStudents = 0;
} // Course::Course
: -
7. 0 Course c0.
:
Course c2( "", " ()" );
. , ,
:
(strlen(cCode.s) == cCodeSz-1) || (strlen(cCode.s) == 0 && strlen(cTitle) == 0)

.

; , CourseKey("") ( ). -
(aCode) .
, cCode = CourseKey( aCode )
:
CourseKey cCode;
strcpy( cCode.s, aCode.c_str() );
cPrereq = CourseKey( "" ) :
cPrereq.s[0] = '\0';
:
explicit CourseKey; !
char[cCodeSz]. struct
.
775

, :
. , -
.
, :
.
, :
:
~Course() { };
GE, get:
const char* getCode() const { return cCode.s; }
const char* getTitle() const { return cTitle; }
unsigned int getFSem() const { return cFSem; }
bool getCompuls() const { return cCompuls; }
char getSector() const { return cSector; }
const char* geCateg() const { return cCateg; }
unsigned int getWH() const { return cWH; }
unsigned int getUnits() const { return cUnits; }
unsigned int getNoOfStudents() const { return cNoOfStudents; }
const char* getPrereq() const { return cPrereq.s; }
:
const char* CourseKey,
.
SE, set: setCode :
void Course::setCode( string aCode )
{
if ( aCode.length() != cCodeSz-1 )
throw CourseXptn( CourseKey(cCode), "setCode", CourseXptn::keyLen,
aCode.c_str() );
if ( (aCode.length() != 0) && (CourseKey(aCode) == cPrereq) )
throw CourseXptn( CourseKey(cCode), "setCode", CourseXptn::autoRef,
aCode.c_str() );
strcpy( cCode.s, aCode.c_str() );
} // Course::setCode

7.3
CourseKey(aCode) == cPrereq -
== CourseKey:
bool operator==( const Course::CourseKey& lhs, const Course::CourseKey& rhs )
{ return ( !(lhs != rhs) ); }
!(CourseKey(aCode) != cPrereq)
!=; ! , == .
:
==: !=. -
return ( strcmp(lhs.s, rhs.s) == 0 ); ,
.
, , , -
.
setTitle() :
void Course::setTitle( string aTitle )

3 -
; set -
() :
c0 = Course();
776 Project 04

{
strncpy( cTitle, aTitle.c_str(), cTitleSz-1 ); cTitle[cTitleSz-1] = '\0';
} // Course::setTitle

void Course::setFSem( int aFSem )
{
if ( aFSem < 1 || 8 < aFSem)
throw CourseXptn( cCode, "setFSem", CourseXptn::rangeError, aFSem );
cFSem = aFSem;
} // Course::setFSem
CourseXptn:
:
int errIntVal;
:
CourseXptn( const Course::CourseKey& obk, const char* mn,
int ec, int iv )
{ objKey = obk;
strncpy( funcName, mn, 99 ); funcName[99] = '\0';
errorCode = ec;
errIntVal = iv; }
setCompuls() :
void setCompuls( bool aCompuls ) { cCompuls = aCompuls; };
bool -
:
void setCompuls() { cCompuls = true; };
void clearCompuls() { cCompuls = false; };
setSector() setCateg():
void Course::setSector( char aSector )
{
if ( aSector != '' && aSector != '' &&
aSector != '' && aSector != '' && aSector != '' )
throw CourseXptn( cCode, "setSector",
CourseXptn::noSuchSector, aSector );
cSector = aSector;
} // Course::setSector

void Course::setCateg( string aCateg )


{
if ( aCateg != "" && aCateg != "" &&
aCateg != "" && aCateg != "" )
throw CourseXptn( cCode, "setCateg",
CourseXptn::noSuchCateg, aCateg.c_str() );
strcpy( cCateg, aCateg.c_str() );
} // Course::setSector
setWH() setUnits() setFSem():
void Course::setWH( int aWH )
{
if ( aWH <= 0 )
throw CourseXptn( cCode, "setWH", CourseXptn::rangeError, aWH );
cWH = aWH;
} // Course::setWH

void Course::setUnits( int aUnits )


{
if ( aUnits <= 0 )
throw CourseXptn( cCode, "setUnits", CourseXptn::rangeError, aUnits );
cUnits = aUnits;
} // Course::setUnits
777

:
.
setNoOfStudents() cNoOf-
Students :
void clearStudents() { cNoOfStudents = 0; }
void add1Student() { ++cNoOfStudents; }

. :
void Course::delete1Student()
{
if ( cNoOfStudents <= 0 )
throw CourseXptn( cCode, "delete1Student", CourseXptn::noStudent );
--cNoOfStudents;
} // Course::delete1Student
setPrereq() :
void Course::setPrereq( const string& prCode )
{
if ( prCode.length() != cCodeSz-1 && prCode.length() != 0 )
throw CourseXptn( cCode, "setPrereq", CourseXptn::keyLen,
prCode.c_str() );
if ( cCode != CourseKey("") && CourseKey(prCode) == cCode )
throw CourseXptn( cCode, "setPrereq", CourseXptn::autoRef,
prCode.c_str() );
cPrereq = CourseKey( prCode );
} // Course::setPrereq
,
,
.
.
save() load(). save()
. cCode
cPrereq :
// . . .
bout.write( cCode.s, sizeof(cCode.s) ); //
// . . .
bout.write( cPrereq.s, sizeof(cPrereq.s) ); //
// . . .
load() :
21.6 . -
, ...
.
void Course::load( istream& bin )
{
Course tmp;
bin.read( tmp.cCode.s, cCodeSz ); //
if ( !bin.eof() )
{
bin.read( tmp.cTitle, cTitleSz ); //
bin.read( reinterpret_cast<char*>(&tmp.cFSem), sizeof(cFSem) );
//
bin.read( reinterpret_cast<char*>(&tmp.cCompuls), sizeof(cCompuls) );
//
bin.read( &tmp.cSector, sizeof(cSector) ); //
bin.read( tmp.cCateg, cCategSz ); //
bin.read( reinterpret_cast<char*>(&tmp.cWH), sizeof(cWH) );
//
bin.read( reinterpret_cast<char*>(&tmp.cUnits), sizeof(cUnits));
//
bin.read( tmp.cPrereq.s, cCodeSz ); //
778 Project 04

bin.read( reinterpret_cast<char*>(&tmp.cNoOfStudents),
sizeof(cNoOfStudents) ); // . .
if ( bin.fail() )
throw CourseXptn( cCode, "load", CourseXptn::cannotRead );
*this = tmp;
} // if ( !bin.eof() ). . .
} // Course::load
; tmp Course -
.
(*this) tmp. swap;
! , -
. *this = tmp
swap(tmp) ( .)
:
class Course
{ // version 2
public:
enum { cCodeSz = 8 };
struct CourseKey
{
char s[cCodeSz];
explicit CourseKey( string aKey="" )
{ strncpy( s, aKey.c_str(), cCodeSz-1 ); s[cCodeSz-1] = '\0'; }
}; // CourseKey
explicit Course( string aCode="", string aTitle="" );
~Course() { };
// getters
const char* getCode() const { return cCode.s; }
const char* getTitle() const { return cTitle; }
unsigned int getFSem() const { return cFSem; }
bool getCompuls() const { return cCompuls; }
char getSector() const { return cSector; }
const char* geCateg() const { return cCateg; }
unsigned int getWH() const { return cWH; }
unsigned int getUnits() const { return cUnits; }
unsigned int getNoOfStudents() const { return cNoOfStudents; }
const char* getPrereq() const { return cPrereq.s; }
// setters
void setCode( string aCode );
void setTitle( string aTitle );
void setFSem( int aFSem );
void setCompuls( bool aCompuls ) { cCompuls = aCompuls; };
void setSector( char aSector );
void setCateg( string aCateg );
void setWH( int aWH );
void setUnits( int aUnits );
void clearStudents() { cNoOfStudents = 0; }
void add1Student() { ++cNoOfStudents; }
void delete1Student();
void setPrereq( const string& prCode );
// other
void save( ostream& bout ) const;
void load( istream& bin );
private:
CourseKey cCode; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
CourseKey cPrereq; //
unsigned int cNoOfStudents; // .
779

}; // Course

bool operator!=( const Course::CourseKey& lhs, const Course::CourseKey& rhs )


{ return ( strcmp(lhs.s, rhs.s) != 0 ); }

bool operator==( const Course::CourseKey& lhs, const Course::CourseKey& rhs )


{ return ( !(lhs != rhs) ); }
:
struct CourseXptn
{ // version 2
enum { keyLen, rangeError, noSuchSector, noSuchCateg, autoRef, noCourse,
noStudent, fileNotOpen, cannotWrite, cannotRead };
Course::CourseKey objKey;
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
CourseXptn( const Course::CourseKey& obk, const char* mn,
int ec, const char* sv="" )
: objKey( obk ), errorCode( ec )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
CourseXptn( const Course::CourseKey& obk, const char* mn,
int ec, int iv )
: objKey( obk ), errorCode( ec ), errIntVal( iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // CourseXptn

Prj04.3 ...
Project 3 -
Course.
.
:
class CourseCollection
{
public:
// . . .
private:
enum { ccIncr = 30 };
Course* ccArr;
size_t ccNOfCourses;
size_t ccReserved;
// . . .
}; // CourseCollection
(;) .
CourseCollection
.
,
. : ( -
) ,
. :
;
;
Course-
Collection. :
class CourseCollection
{
public:
780 Project 04

// . . .
private:
enum { ccIncr = 30 };
Course* ccArr;
size_t ccNOfCourses;
size_t ccReserved;

CourseCollection( const CourseCollection& rhs ) { };


CourseCollection& operator=( const CourseCollection& rhs ) { };
// . . .
}; // CourseCollection
( main) :
CourseCollection allCourses;
// . . .
CourseCollection otherCollection( allCourses );
:
'CourseCollection::CourseCollection(const CourseCollection &)' is not accessi-
ble in function main()
, :
CourseCollection otherCollection;
// . . .
otherCollection = allCourses;
:
'CourseCollection::operator =(const CourseCollection &)' is not accessible in
function main()
.

:
II (0 ccNOfCourses < ccReserved) && (ccReserved % ccIncr == 0)
:
, Collection. ,
:
x, y: Course (x, y Collection x y)
; !
:4
x: Course (x Collection strlen(x.cCode) == cCodeSz-1)
Prj04.2 :
. -

Course -
. : 5
x: Course (x Collection && x.cPrereq "")
y: Course (y Collection && y.cCode == x.cPrereq)
:
I ID && II
:
ID (x, y: Course (x, y Collection x y)) &&
(x: Course (x Collection strlen(x.cCode) == cCodeSz-1)) &&

4 (constraint)
(entity integrity)...
5 ... (referential integrity).
781

(x: Course (x Collection && x.cPrereq "")


y: Course (y Collection && y.cCode == x.cPrereq))

cCode .
ccNOfCourses
ccArr ID :
ID (j, k: [0 .. ccNOfCourses) (j k ccArr[j].cCode ccArr[k].cCode)) &&
(k: [0 .. ccNOfCourses) strlen(ccArr[k].cCode) == cCodeSz-1) &&
(k: [0 .. ccNOfCourses) (ccArr[k].cPrereq ""
j: [0 .. ccNOfCourses) ccArr[j].cCode == ccArr[k].cPrereq))
:
:
CourseCollection::CourseCollection()
{
try
{
ccReserved = ccIncr;
ccArr = new Course[ ccReserved ];
ccNOfCourses = 0;
}
catch( bad_alloc& )
{
throw CourseCollectionXptn( "CourseCollection",
CourseCollectionXptn::allocFailed);
}
} // CourseCollection::CourseCollection
:
~CourseCollection() { delete[] ccArr; };
get
size_t getNOfCourses() const { return ccNOfCourses; }
const Course* getArr() const { return ccArr; }
set.

Route (20.7.2.3).
rAllStops:
ccArr rAllStops:
. , find1RouteStop(), get1RouteStop(), delete-
RouteStop() erase1RouteStop() addRouteStop() insert1RouteStop() -
find1Course(), get1Course(), delete1Course() erase1Course() add1Course()
insert1Course() .
rAllStops , , sName
sDist. ccArr , , -
cCode. -
(15.5.1), Student.
rAllStops !=
sDist
. linSearch
MyTmpltLib .
. -
linSearch() != Course
. , Date ( Student),
:
bool operator!=( const Course& a, const Course& b )
782 Project 04

{ return ( strcmp(a.getCode(), b.getCode()) != 0 ); }


.
-
.
!= CourseKey Course . ,
.
:
bool operator!=( const Course& lhs, const Course& rhs )
{ return ( Course::CourseKey(lhs.getCode()) !=
Course::CourseKey(rhs.getCode()) ); }
, CourseKey. -
, Course
.
ccArr rAllStops
rAllStops. ccArr -
. 20.7.2
.
find1Course() :
bool find1Course( const string& code ) const
{ return ( findNdx(code) >= 0 ); };
:
int CourseCollection::findNdx( const string& code ) const
{
int ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = -1;
else
ndx = linSearch( ccArr, ccNOfCourses, 0, ccNOfCourses-1, Course(code) );
return ndx;
} // CourseCollection::findNdx
:
findNdx() ( -1 -
) find1Course() true false.
findNdx() private
Route (20.7.2.3).
Course code
.
erase1Course(). 20.7.2:
void CourseCollection::delete1Course( string code )
{
if ( code ndx )
{
ndx
--ccNOfCourses;
}
}
:
void CourseCollection::delete1Course( string code )
{
int ndx( findNdx(code) );
if ( ndx >= 0 ) // code found
{
ccArr[ndx] = ccArr[ccNOfCourses-1];
--ccNOfCourses;
}
783

} // CourseCollection::delete1Course
,
.
.
insert1Course() insert1RouteStop() .
-
. , :
void CourseCollection::insert1Course( const Course& aCourse )
{
if ( ccReserved <= ccNOfCourses+1 )
{
try { renew( ccArr, ccNOfCourses, ccReserved+ccIncr );
ccReserved += ccIncr; }
catch( MyTmpltLibXptn& )
{
throw CourseCollectionXptn( "insert1Course",
CourseCollectionXptn::allocFailed );
}
}
ccArr[ccNOfCourses] = aCourse;
++ccNOfCourses;
} // CourseCollection::insert1Course

Prj04.3.1 add1Course() delete1Course()


insert1Course()
. , ,
add1Course(), insert1Course() :
cCodeSz-1:
if ( strlen(aCourse.getCode()) != cCodeSz-1 )
throw CourseCollectionXptn( "add1Course", CourseCollectionXptn::entity);
:
int ndx( findNdx(aCourse.getCode()) );
if ( ndx >= 0 )
throw CourseCollectionXptn( "add1Course", CourseCollectionXptn::key,
aCourse.getCode() );
! -
.

:
if ( strcmp(aCourse.getPrereq(), "") != 0 ) //
{
int ndx( findNdx(aCourse.getPrereq()) );
if ( ndx < 0 ) //
throw CourseCollectionXptn( "add1Course", CourseCollectionXptn::ref,
aCourse.getPrereq() );
}
.
cNoOfStudents; , ! , -
( const Course& aCourse) -
:
ndx = findNdx( aCourse.getCode() );
ccArr[ndx].clearStudents();
add1Course() :
void CourseCollection::add1Course( const Course& aCourse )
{
784 Project 04

if ( strlen(aCourse.getCode()) != Course::cCodeSz-1 )
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::entity );
int ndx( findNdx(aCourse.getCode()) );
if ( ndx < 0 ) //
{
if ( strcmp(aCourse.getPrereq(), "") != 0 )//
{ //
int ndx( findNdx(aCourse.getPrereq()) );
if ( ndx < 0 ) //
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::ref,
aCourse.getPrereq() );
}
//
insert1Course( aCourse );
ndx = findNdx( aCourse.getCode() );
ccArr[ndx].clearStudents();
}
} // CourseCollection::add1Course
-
(private) insert1Code().
:
(-) (-).
erase1Course() delete1Course(),
erase1Course() .
: Project 3,
. cNoOfStudents > 0
,
Student
.
!
void CourseCollection::delete1Course( string code )
{
int ndx( findNdx(code) );
if ( ndx >= 0 ) //
{
ccArr[ccNOfCourses] = Course();
ccArr[ccNOfCourses].setPrereq( code ); //
int k(0);
while ( strcmp(ccArr[k].getPrereq(), code.c_str()) != 0 )
++k;
if ( k < ccNOfCourses )
throw CourseCollectionXptn( "delete1Course",
CourseCollectionXptn::cannotDel,
code.c_str() );
int enrStdnt( ccArr[ndx].getNoOfStudents() );
if ( enrStdnt > 0 ) //
throw CourseCollectionXptn( "delete1Course",
CourseCollectionXptn::enrollRef,
code.c_str(), enrStdnt );
erase1Course( ndx );
}
} // CourseCollection::delete1Course
(code) -
cPrereq.
code .
ccArr[ndx].getNoOfStudents() > 0.
785

:

.
delete1Course(), erase1Course() :
void CourseCollection::erase1Course( int ndx )
{
ccArr[ndx] = ccArr[ccNOfCourses-1];
--ccNOfCourses;
} // CourseCollection::erase1Course
, ,
.

Prj04.3.2 save() load()


save() load() Course.
void CourseCollection::save( ofstream& bout )
{
if ( bout.fail() )
throw CourseCollectionXptn( "save", CourseCollectionXptn::fileNotOpen);
bout.write( reinterpret_cast<const char*>(&ccNOfCourses),
sizeof(ccNOfCourses) );
for ( int k(0); k < ccNOfCourses; ++k )
ccArr[k].save( bout );
if ( bout.fail() )
throw CourseCollectionXptn( "save", CourseCollectionXptn::cannotWrite);
} // CourseCollection::save
load() ,
. , 21.6, -
...
.

CourseCollection tmp;
. , -
tmp *this,
void CourseCollection::swap( CourseCollection& rhs )
{
Course* sv( ccArr );
ccArr = rhs.ccArr; rhs.ccArr = sv;
std::swap( ccNOfCourses, rhs.ccNOfCourses );
std::swap( ccReserved, rhs.ccReserved );
} // CourseCollection::swap

:
size_t n;
bin.read( reinterpret_cast<char*>(&n), sizeof(ccNOfCourses) );
n Course .
:
for ( int k(0); k < n && !bin.fail(); ++k )
{
Course oneCourse;
oneCourse.load( bin );
tmp.insert1Course( oneCourse );
}
insert1Course() add1Course() -
.
786 Project 04

for .
tmp () swap:
if ( bin.fail() )
throw CourseCollectionXptn( "load",
CourseCollectionXptn::cannotRead );
swap( tmp );
load() tmp
.
load() . -
RAII.
load:
void CourseCollection::load( ifstream& bin )
{
CourseCollection tmp;
unsigned int n;

bin.read( reinterpret_cast<char*>(&n), sizeof(ccNOfCourses) );


if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Course oneCourse;
oneCourse.load( bin );
tmp.insert1Course( oneCourse );
}
if ( bin.fail() )
throw CourseCollectionXptn( "load",
CourseCollectionXptn::cannotRead );
swap( tmp );
}
} // CourseCollection::load

Prj04.3.3
private Course -
. -
! get-delete-edit-add
Route; !


(-
).
,
() ( )
. ; CourseCollection -
Course.
:
void add1Student( string code );
void delete1Student( string code );
:
void CourseCollection::add1Student( string code )
{
int ndx( findNdx(code) );
if ( ndx < 0 ) //
throw CourseCollectionXptn( "add1Student",
CourseCollectionXptn::notFound,
code.c_str() );
787

ccArr[ndx].add1Student();
} // CourseCollection::add1Student

void CourseCollection::delete1Student( string code )


{
int ndx( findNdx(code) );
if ( ndx < 0 ) //
throw CourseCollectionXptn( "delete1Student",
CourseCollectionXptn::notFound,
code.c_str() );
ccArr[ndx].delete1Student();
} // CourseCollection::delete1Student
Course
.
( CourseCollection)
Course setCode. ,
, .


.

Prj04.3.4 [];
: CourseCollection -
Course [];
, CourseCollection Course

. , get1Course() -
:
const Course& CourseCollection::get1Course( string code ) const
{
int ndx( findNdx(code) );
if ( ndx < 0 )
throw CourseCollectionXptn( "get1Course",
CourseCollectionXptn::notFound,
code.c_str() );
return ccArr[ndx];
} // CourseCollection::get1Course
ndx -
string.
[]
get1Course:
const Course& CourseCollection::operator[]( string code ) const
{
int ndx( findNdx(code) );
if ( ndx < 0 )
throw CourseCollectionXptn( "get1Course",
CourseCollectionXptn::notFound,
code.c_str() );
return ccArr[ndx];
} // CourseCollection::operator[]
:
get1C = allCourses.get1Course( "0201" );
get1C = allCourses["0201"];
: [ ] -
, .
788 Project 04

: -
[] const.
.
.
,
.
STL.

Prj04.4
CourseCollection::delete1Course() :
StudentCollection::delete1Student() StudentInCourseCollection::delete1Student-
InCourse(). , .
: -
. -
(
). :
-
.
-
-
() . ;
.

Prj04.5 Student
Student :
class Student
{
public:
// . . .
private:
enum { sNameSz = 20 };
enum { sIncr = 3 };
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
unsigned int sWH; //
size_t sNoOfCourses; //
Course::CourseKey* sCourses;
size_t sReserved;
}; // Student
sCourses ... -
.
Student , Pro-
ject 3 :
struct StudentXptn
{
enum { incomplete, negIdNum, nonPosIncr,
fileNotOpen, cannotRead, cannotWrite };
unsigned int objKey;
char funcName[100];
int errorCode;
int errIntVal;
StudentXptn( int obk, const char* mn, int ec, int ev = 0 )
789

: objKey( obk ), errorCode( ec ), errIntVal( ev )


{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // StudentXptn
, objKey
.
, :
: :
0 <= sIdNum && strlen(sSurname) < sNameSz && strlen(sFirstname) < sNameSz && sWH >= 0 &&
(k: [0..sNoOfCourses) (strlen(sCourses[k]) == Course::cCodeSz-1)) &&
(j, k: [0 .. sNoOfCourses) (j k sCourses[j] sCourses[k])) &&
(0 sNoOfCourses < sReserved) && (sReserved % sIncr == 0)
:
1) sIdNum 0
:
Student s1;
2) sIdNum 0 <= sIdNum -
1000000 -
.
3) cTitle Course sSurname sFirstname,
sNameSz . -
sNameSz-1 .
: .
Student:: Student( int aIdNum )
{
if ( aIdNum < 0 )
throw StudentXptn( 0, "Student", StudentXptn::negIdNum, aIdNum );
sIdNum = aIdNum;
sSurname[0] = '\0';
sFirstname[0] = '\0';
sWH = 0;
try { sCourses = new Course::CourseKey[ sIncr ]; }
catch( bad_alloc )
{ throw StudentXptn( sIdNum, "Student", StudentXptn::allocFailed ); }
sReserved = sIncr;
sNoOfCourses = 0;
}; // Student()
:
aIdNum
sIdNum .
sIdNum ( aIdNum.)

Prj04.5.1
: ;
. ,
()
.
, : ( ) -
.
:
~Student() { delete[] sCourses; };
:
Student::Student( const Student& rhs )
790 Project 04

{
sIdNum = rhs.sIdNum;
strcpy( sSurname, rhs.sSurname );
strcpy( sFirstname, rhs.sFirstname );
sWH = rhs.sWH;
try { sCourses = new Course::CourseKey[ rhs.sReserved ]; }
catch( bad_alloc )
{ throw StudentXptn( sIdNum, "Student", StudentXptn::allocFailed ); }
sReserved = rhs.sReserved;
for ( int k(0); k < rhs.sNoOfCourses; ++k )
sCourses[k] = rhs.sCourses[k];
sNoOfCourses = rhs.sNoOfCourses;
}; // Student( const Student& rhs )
() :
Student& Student::operator=( const Student& rhs )
{
if ( &rhs != this )
{
try { Student tmp( rhs );
swap( tmp ); }
catch( StudentXptn& x )
{ strcpy( x.funcName, "operator=" );
throw; }
}
return *this;
}; // Student( const Student& rhs )

void Student::swap( Student& rhs )


{
std::swap( sIdNum, rhs.sIdNum );

char svs[sNameSz];
strcpy( svs, sSurname ); strcpy( sSurname, rhs.sSurname );
strcpy( rhs.sSurname, svs );

strcpy( svs, sFirstname );


strcpy( sFirstname, rhs.sFirstname );
strcpy( rhs.sFirstname, svs );

std::swap( sWH, rhs.sWH );


std::swap( sNoOfCourses, rhs.sNoOfCourses );

Course::CourseKey* svck( sCourses );


sCourses = rhs.sCourses; rhs.sCourses = svck;

std::swap( sReserved, rhs.sReserved );


} // Student::swap

Prj04.5.2 get set


GE: get sReserved (
):
unsigned int getIdNum() const { return sIdNum; }
const char* getSurname() const { return sSurname; }
const char* getFirstname() const { return sFirstname; }
unsigned int getWH() const { return sWH; }
unsigned int getNoOfCourses() const { return sNoOfCourses; }
const Course::CourseKey* getCourses() const { return sCourses;}
SE: set sReserved.

void Student::setIdNum( int aIdNum )
{
791

if ( aIdNum <= 0 )
throw StudentXptn( sIdNum, "setIdNum", StudentXptn::negIdNum, aIdNum );
sIdNum = aIdNum;
} // Student::setIdNum
0, ()
.
, setSurname() setFirstname(), :
void Student::setSurname( string aSurname )
{
strncpy( sSurname, aSurname.c_str(), sNameSz-1 );
sSurname[sNameSz-1] = '\0';
} // Student::setSurname

void Student::setFirstname( string aFirstname )


{
strncpy( sFirstname, aFirstname.c_str(), sNameSz-1 );
sFirstname[sNameSz-1] = '\0';
} // Student::setSurname
( ) -
19 19
. , -, -
, !
(setCourses) sNoOf-
Courses sCourses. . -
,
insert1Course() add1Course().
set
void clearCourses() { sNoOfCourses = 0; sWH = 0; }
Project 3. ! ;
, sReserved , sNoOfCourses (== 0)
.
sIncr .
...

Prj04.5.3
Course-
Collection .
findNdx()
, , 1.
() CourseCollection:
int Student::findNdx( const string& code ) const
{
int ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = -1;
else
ndx = linSearch( sCourses, sNoOfCourses, 0, sNoOfCourses-1,
Course::CourseKey(code) );
return ndx;
} // Student::findNdx
find1Course() :
bool find1Course( const string& code ) const
{ return ( findNdx(code) >= 0 ); };
792 Project 04

, -
private.
get1Course(); ,
.
insert1Course():
void Student::insert1Course( const Course::CourseKey& aCode )
{
if ( sReserved <= sNoOfCourses+1 )
{
try { renew( sCourses, sNoOfCourses, sReserved+sIncr );
ccReserved += ccIncr; }
catch( MyTmpltLibXptn& )
{
throw StudentXptn( sIdNum, "insert1Course",
StudentXptn::allocFailed );
}
}
sCourses[sNoOfCourses] = aCode;
++sNoOfCourses;
} // Student::insert1Course

.
sWH.
(-
).

, insert1Course() CourseCollection -
add1Course() -
. .
void Student::add1Course( const Course& oneCourse )
{
if ( findNdx(oneCourse.getCode()) < 0 )
{
insert1Course( Course::CourseKey(oneCourse.getCode()) );
sWH += oneCourse.getWH();
}
} // Student::add1Course
, insert1Course() , -
Course
(getWH()).
:
void Student::delete1Course( const Course& oneCourse )
{
int ndx( findNdx(oneCourse.getCode()) );
if ( ndx >= 0 ) //
{
erase1Course( ndx );
sWH -= oneCourse.getWH();
}
} // Student::delete1Course

void Student::erase1Course( int ndx )


{
sCourses[ndx] = sCourses[sNoOfCourses-1];
--sNoOfCourses;
} // Student::erase1Course
793

Prj04.5.4
Student :
void Student::save( ostream& bout ) const
{
if ( bout.fail() )
throw StudentXptn( sIdNum, "save", StudentXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&sIdNum), sizeof(sIdNum) );
bout.write( sSurname, sizeof(sSurname) );
bout.write( sFirstname, sizeof(sFirstname) );
bout.write( reinterpret_cast<const char*>(&sWH), sizeof(sWH) );
bout.write( reinterpret_cast<const char*>(&sNoOfCourses),
sizeof(sNoOfCourses) );
for ( int k(0); k < sNoOfCourses; ++k )
bout.write( sCourses[k].s, Course::cCodeSz );
if ( bout.fail() )
throw StudentXptn( sIdNum, "save", StudentXptn::cannotWrite );
} // Student::save
for
.
load() .
void Student::load( istream& bin )
{
Student tmp;
bin.read( reinterpret_cast<char*>(&tmp.sIdNum), sizeof(sIdNum) );
if ( !bin.f() )
{
bin.read( tmp.sSurname, sizeof(sSurname) );
bin.read( tmp.sFirstname, sizeof(sFirstname) );
bin.read( reinterpret_cast<char*>(&tmp.sWH), sizeof(sWH) );
bin.read( reinterpret_cast<char*>(&tmp.sNoOfCourses),
sizeof(sNoOfCourses) );
if ( tmp.sNoOfCourses >= tmp.sReserved )
{
delete[] tmp.sCourses;
try
{
tmp.sCourses =
new Course::CourseKey[((tmp.sNoOfCourses/sIncr)+1)*sIncr];
tmp.sReserved = ((tmp.sNoOfCourses/sIncr)+1)*sIncr;
}
catch( bad_alloc )
{
throw StudentXptn( tmp.sIdNum, "load", StudentXptn::allocFailed );
}
}
for ( int k(0); k < tmp.sNoOfCourses; ++k )
bin.read( tmp.sCourses[k].s, Course::cCodeSz );
if ( bin.fail() )
throw StudentXptn( sIdNum, "load", StudentXptn::cannotRead );
swap( tmp );
}
} // Student::load
-
CourseCollection.
(tmp) *this:
, Course insert1-
Course(). ( sNoOfCourses).
-
n. , insert1Course(), .
,
tmp.sNoOfCourses. , -
794 Project 04

, .

.
save() load(), ,
, readFromText().
: readPartFromText().
: :
void Student::readPartFromText( istream& tin )
{
string line;
getline( tin, line, '\n' );
if ( !tin.eof() )
{
Student tmp;
size_t t1Pos( line.find("\t") );
if ( t1Pos >= line.length() )
throw StudentXptn( sIdNum, "readPartFromText",
StudentXptn::incomplete );
string str1( line.substr(0, t1Pos) );
int iStr1( atoi(str1.c_str()) );
try { tmp.setIdNum( iStr1 ); }
catch( StudentXptn& x )
{ strcpy( x.funcName, "readPartFromText" );
throw; }
size_t t2Pos( line.find("\t", t1Pos+1) );
if ( t2Pos >= line.length() )
throw StudentXptn( tmp.sIdNum, "readPartFromText",
StudentXptn::incomplete );
tmp.setSurname( line.substr(t1Pos+1, t2Pos-t1Pos-1) );
tmp.setFirstname( line.substr(t2Pos+1) );
swap( tmp );
} // if ( !tin.eof . . .
} // Student::readPartFromText

Prj04.5.5 Student
Student:
class Student
{ // version 2
public:
// constructors, destructor
explicit Student( int aIdNum=0 );
Student( const Student& rhs );
~Student() { delete[] sCourses; };
// copy assignement
Student& operator=( const Student& rhs );
// getters
unsigned int getIdNum() const { return sIdNum; }
const char* getSurname() const { return sSurname; }
const char* getFirstname() const { return sFirstname; }
unsigned int getWH() const { return sWH; }
unsigned int getNoOfCourses() const { return sNoOfCourses; }
const Course::CourseKey* getCourses() const
{ return sCourses; }
// setters
void setIdNum( int aIdNum );
void setSurname( string aSurname );
void setFirstname( string aFirstname );
void clearCourses() { sNoOfCourses = 0; sWH = 0; }
// 1 Course methods
bool find1Course( const string& code ) const
{ return ( findNdx(code) >= 0 ); };
void add1Course( const Course& oneCourse );
795

void delete1Course( const Course& oneCourse );


// other methods
void swap( Student& rhs );
void readPartFromText( istream& tin );
void save( ostream& bout ) const;
void load( istream& bin );
private:
enum { sNameSz = 20 };
enum { sIncr = 3 };
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
unsigned int sWH; //
unsigned int sNoOfCourses; //
//
Course::CourseKey* sCourses;
unsigned int sReserved;

unsigned int countTabs( string aLine );


int findNdx( const string& code ) const;
void insert1Course( const Course::CourseKey& aCode );
void erase1Course( int ndx );
}; // Student

bool operator!=( const Student& lhs, const Student& rhs )
{ return (lhs.getIdNum() != rhs.getIdNum()); }

bool operator==( const Student& lhs, const Student& rhs )


{ return !(lhs != rhs); }
:
struct StudentXptn
{ // version 2
enum { allocFailed, outOfRange, incomplete, negIdNum, nonPosIncr,
fileNotOpen, cannotRead, cannotWrite };
unsigned int objKey;
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
StudentXptn( int obk, const char* mn, int ec, const char* sv="" )
: objKey( obk ), errorCode( ec )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
StudentXptn( int obk, const char* mn, int ec, int ev )
: objKey( obk ), errorCode( ec ), errIntVal( ev )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // StudentXptn

Prj04.6
CourseCollection.h CourseCollection.cpp find-and-
replace Course Student. -
StudentCollection. -
Student . :
class StudentCollection // version 1
{
public:
StudentCollection();
~StudentCollection() { delete[] scArr; };
// getters
size_t getNOfStudents() const { return scNOfStudents; }
const Student* getArr() const { return scArr; }
796 Project 04

// 1 Student
bool find1Student( int aIdNum ) const
{ return ( findNdx(aIdNum) >= 0 ); };
void delete1Student( int aIdNum );
void add1Student( const Student& aStudent );
const Student& get1Student( int aIdNum ) const;
// other
void save( ofstream& bout ) const;
void load( ifstream& bin );
void swap( StudentCollection& rhs );
private:
enum { scIncr = 30 };
Student* scArr;
size_t scNOfStudents;
size_t scReserved;

StudentCollection( const StudentCollection& rhs ) { };


StudentCollection& operator=( const StudentCollection& rhs ){};
void erase1Student( int ndx );
void insert1Student( const Student& aStudent );
int findNdx( int aIdNum ) const;
}; // StudentCollection
CourseCollection ,
( ;) -
.
-
CourseCollection: delete1Student() add1Student(). :
void StudentCollection::delete1Student( int aIdNum )
{
int ndx( findNdx(aIdNum) );
if ( ndx >= 0 ) //
{
if ( scArr[ndx].getNoOfCourses() > 0 )
throw StudentCollectionXptn( "delete1Student",
StudentCollectionXptn::enrollRef,
aIdNum );
erase1Student( ndx );
}
} // StudentCollection::delete1Student
-
CourseCollection::delete1Course(), -
.
.
Student insert1-
Course() add1Course(): -
( ).
: -
-
( ).
; StudentCollection; !
.
:
CourseCollection* scPAllCourses;
:
StudentCollection::StudentCollection()
{
try
{
scReserved = scIncr;
797

scArr = new Student[ scReserved ];


scNOfStudents = 0;
}
catch( bad_alloc& )
{
throw StudentCollectionXptn( "StudentCollection",
StudentCollectionXptn::allocFailed);
}
scPAllCourses = 0;
} // StudentCollection::StudentCollection
:
CourseCollection* getPAllCourses() const { return scPAllCourses; }
void setPAllCourses( CourseCollection* pCourses )
{ scPAllCourses = pCourses; }
, :
CourseCollection allCourses;
StudentCollection allStudents;
:
allStudents.setPAllCourses( &allCourses );
add1Student():
void StudentCollection::add1Student( const Student& aStudent )
{
int ndx( findNdx(aStudent.getIdNum()) );
if ( ndx < 0 ) //
{
if ( scPAllCourses != 0 )
{
const Course::CourseKey* aStCourses( aStudent.getCourses() );
for ( int k(0); k < aStudent.getNoOfCourses(); ++k )
{
if ( !scPAllCourses->find1Course(aStCourses[k].s) )
throw StudentCollectionXptn( "add1Student",
StudentCollectionXptn::ref,
aStCourses[k].s );
}
}
insert1Student( aStudent );
}
} // StudentCollection::add1Student
:
()
(findNdx(aStudent.getIdNum()) < 0).

(scPAllCourses != 0).
for aStCourses -
() .
CourseCollection -
( Course)
( Student) . -
.
add1Course() delete1Course(). : -
sCourses
. : (
) . add1Course()
delete1Course() Student . ...
798 Project 04

Prj04.6.1 ,
save() load() CourseCollection
find-and-replace
:

(index)
struct IndexEntry
{
unsigned int sIdNum;
size_t loc;
}; // IndexEntry

(-) students.ndx.
StudentCollection; !
StudentCollection . index
StudentCollection .
index save():
void StudentCollection::save( ofstream& bout, IndexEntry* index )
{
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&scNOfStudents),
sizeof(scNOfStudents) );
for ( int k(0); k < scNOfStudents; ++k )
{
index[k].sIdNum = scArr[k].getIdNum();
index[k].loc = bout.tellp();
scArr[k].save( bout );
}
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::cannotWrite );
} // StudentCollection::save
scArr[k]
(sIdNum) (loc)
scArr[k]. , scArr index
- scArr.
index -
.
:
void StudentCollection::load( ifstream& bin )
{
StudentCollection tmp;
unsigned int n;
bin.read( reinterpret_cast<char*>(&n), sizeof(scNOfStudents) );
if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Student oneStudent;
oneStudent.load( bin );
tmp.insert1Student( oneStudent );
}
if ( bin.fail() )
throw StudentCollectionXptn( "load",
StudentCollectionXptn::cannotRead );
swapArr( tmp );
}
799

} // StudentCollection::load
swapArr();
StudentCollection:
void StudentCollection::swapArr( StudentCollection& rhs )
{
std::swap( scArr, rhs.scArr );
std::swap( scNOfStudents, rhs.scNOfStudents );
std::swap( scReserved, rhs.scReserved );
} // StudentCollection::swapArr
swap() (-
); scPAllCourses
.6

Prj04.7 StudentInCourse
StudentInCourse
Course:
class StudentInCourse
{
public:
// . . .
private:
unsigned int sicSIdNum; //
Course::CourseKey sicCCode; //
float sicMark; //
}; // StudentInCourse
, a b,
(a.sicSIdNum == b.sicSIdNum) (a.sicCCode == b.sicC-
Code). , (sicSIdNum, sicCCode) . -
( ) public :
struct SICKey
{
unsigned int sIdNum;
Course::CourseKey CCode;
explicit SICKey( int aIdNum=0, string aCCode="" )
{ sIdum = aIdNum; CCode = Course::CourseKey(aCCode); }
}; // SICKey

SICKey getKey() const
{ return SICKey( sicSIdNum, sicCCode.s ); }
!=:
bool operator!=( const StudentInCourse::SICKey& lhs,
const StudentInCourse::SICKey& rhs )
{ return ( (lhs.sIdNum != rhs.sIdNum) || (lhs.CCode != rhs.CCode) ); }
StudentInCourse:
bool operator!=( const StudentInCourse& lhs, const StudentInCourse& rhs )
{ return ( lhs.getKey() != rhs.getKey() ); }
.
: :
0 <= sicSIdNum &&
((strlen(sicCCode.s) == Course::cCodeSz-1) || (sicCCode.s) == 0)) &&
0 <= sicMark <= 10

6
800 Project 04

: ( ) :
StudentInCourse( int aIdNum=0, string aCCode="" );
:
StudentInCourse::StudentInCourse( int aIdNum, string aCCode )
{
if ( aIdNum < 0 )
throw StudentInCourseXptn( SICKey(), "StudentInCourse",
StudentInCourseXptn::negIdNum, aIdNum );
sicSIdNum = aIdNum;
if ( aCCode.length() != Course::cCodeSz-1 &&
aCCode.length() != 0 )
throw StudentInCourseXptn( SICKey(sicSIdNum), "StudentInCourse",
StudentInCourseXptn::keyLen, aCCode.c_str());
sicCCode = Course::CourseKey( aCCode );
sicMark = 0;
} // StudentInCourse::StudentInCourse
, , : -
. , ,
:
~StudentInCourse() { };
GE: get, getKey() :
unsigned int getSIdNum() const { return sicSIdNum; }
const char* getCCode() const { return sicCCode.s; }
float getMark() const { return sicMark; }
SE: set:
void StudentInCourse::setSIdNum( int aIdNum )
{
if ( aIdNum <= 0 )
throw StudentInCourseXptn( getKey(), "setSIdNum",
StudentInCourseXptn::negIdNum, aIdNum );
sicSIdNum = aIdNum;
} // StudentInCourse::setSIdNum

void StudentInCourse::setCCode( string aCCode)


{
if ( aCCode.length() != Course::cCodeSz-1 )
throw StudentInCourseXptn( getKey(), "setCCode",
StudentInCourseXptn::keyLen, aCCode.c_str());
sicCCode = Course::CourseKey( aCCode );
} // StudentInCourse::setCCode

void StudentInCourse::setMark( float aMark )


{
if ( aMark < 0 || 10 < aMark )
throw StudentInCourseXptn( getKey(), "setMark",
StudentInCourseXptn::rangeError, aMark );
sicMark = aMark;
} // StudentInCourse::setMark
setIdNumCCode() ; , , -
, StudentInCourseCollection -
setIdNumCCode().
: save() -
:
void StudentInCourse::save( ostream& bout ) const
{
if ( bout.fail() )
throw StudentInCourseXptn( getKey(), "save",
StudentInCourseXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&sicSIdNum), sizeof(sicSIdNum) );
bout.write( sicCCode.s, Course::cCodeSz ); //
801

bout.write( reinterpret_cast<const char*>(&sicMark), sizeof(sicMark) );


if ( bout.fail() )
throw StudentInCourseXptn( getKey(), "save",
StudentInCourseXptn::cannotWrite );
} // StudentInCourse::save
load():
void StudentInCourse::load( istream& bin )
{
StudentInCourse tmp;
bin.read( reinterpret_cast<char*>(&tmp.sicSIdNum), sizeof(sicSIdNum) );
if ( !bin.eof() )
{
bin.read( tmp.sicCCode.s, Course::cCodeSz ); //
bin.read( reinterpret_cast<char*>(&tmp.sicMark), sizeof(sicMark) );
if ( bin.fail() )
throw StudentInCourseXptn( getKey(), "load",
StudentInCourseXptn::cannotWrite );
*this = tmp;
}
} // StudentInCourse::load
:
class StudentInCourse
{
public:
struct SICKey
{
unsigned int sIdNum;
Course::CourseKey CCode;
explicit SICKey( int aIdNum=0, string aCCode="" )
{ sIdNum = aIdNum; CCode = Course::CourseKey(aCCode); }
}; // SICKey
explicit StudentInCourse( int aIdNum=0, string aCCode="" );
~StudentInCourse() { };
// getters
unsigned int getSIdNum() const { return sicSIdNum; }
const char* getCCode() const { return sicCCode.s; }
float getMark() const { return sicMark; }
SICKey getKey() const
{ return SICKey( sicSIdNum, sicCCode.s ); }
// setters
void setSIdNum( int aIdNum );
void setCCode( string aCode);
void setMark( float aMark );
// other
void save( ostream& bout ) const;
void load( istream& bin );
private:
unsigned int sicSIdNum; //
Course::CourseKey sicCCode; //
float sicMark; //
}; // StudentInCourse
, !=:
bool operator!=( const StudentInCourse::SICKey& lhs,
const StudentInCourse::SICKey& rhs )
{ return ( (lhs.sIdNum != rhs.sIdNum) || (lhs.CCode != rhs.CCode) ); }

bool operator!=( const StudentInCourse& lhs, const StudentInCourse& rhs )


{ return ( lhs.getKey() != rhs.getKey() ); }
:
struct StudentInCourseXptn
{
enum { negIdNum, keyLen, rangeError, unknownCCode,
fileNotOpen, cannotWrite };
StudentInCourse::SICKey objKey;
802 Project 04

char funcName[100];
int errorCode;
char errStrVal[100];
float errFltVal;
StudentInCourseXptn( const StudentInCourse::SICKey obk,
const char* mn, int ec, const char* sv="" )
: objKey( obk ), errorCode( ec )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
StudentInCourseXptn( const StudentInCourse::SICKey& obk,
const char* mn, int ec, float fv )
: objKey( obk ), errorCode( ec ), errFltVal( fv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // StudentInCourseXptn

Prj04.8 StudentInCourseCollection
CourseCollection StudentCollection
(sicSIdNum, sicCCode)
class StudentInCourseCollection
{
public:
StudentInCourseCollection();
~StudentInCourseCollection() { delete[] siccArr; };
// getters
size_t getNOfStudentInCourses() const
{ return siccNOfStudentInCourses; }
const StudentInCourse* getArr() const { return siccArr; }
// 1 StudentInCourse
bool find1StudentInCourse( int aIdNum, string code ) const
{ return ( findNdx(aIdNum, code) >= 0 ); }
const StudentInCourse& get1StudentInCourse( int aIdNum,
string code ) const;
void delete1StudentInCourse( int aIdNum, string code );
void add1StudentInCourse( const StudentInCourse& aStdnInCrs );
// other
void save( ofstream& bout ) const;
void load( ifstream& bin );
void swapArr( StudentInCourseCollection& rhs );
void display( ostream& tout ) const;
private:
enum { siccIncr = 50 };
StudentInCourse* siccArr;
size_t siccNOfStudentInCourses;
size_t siccReserved;

StudentInCourseCollection( const StudentInCourseCollection& rhs ) { };


StudentInCourseCollection& operator=(
const StudentInCourseCollection& rhs ) { };

void erase1StudentInCourse( int ndx );


void insert1StudentInCourse( const StudentInCourse& aStdnInCrs );
int findNdx( int aIdNum, string code ) const;
}; // StudentInCourseCollection

int StudentInCourseCollection::findNdx( int aIdNum, string code ) const
{
int ndx;
if ( aIdNum <= 0 || code.length() != Course::cCodeSz-1 )
ndx = -1;
else
ndx = linSearch( siccArr, siccNOfStudentInCourses,
0, siccNOfStudentInCourses-1,
StudentInCourse(aIdNum,code) );
803

return ndx;
} // StudentInCourseCollection::findNdx
:
StudentInCourse (sicSIdNum, sicCCode)
aIdNum code. -
find1StudentInCourse(), delete1StudentInCourse(), get1StudentInCourse()
delete1StudentInCourse().
linSearch()
: aIdNum > 0 && code.length() == Course::cCodeSz-1.
, delete1StudentInCourse() add1StudentInCourse().
() setIdNumCCode() Project 3.
add1StudentInCourse() setIdNumCCode()

; ! StudentCollection :
private:
// . . .
StudentCollection* siccPAllStudents;
CourseCollection* siccPAllCourses;
:
StudentInCourseCollection::StudentInCourseCollection()
{
try
{
siccReserved = siccIncr;
siccArr = new StudentInCourse[ siccReserved ];
siccNOfStudentInCourses = 0;
}
catch( bad_alloc& )
{
throw StudentInCourseCollectionXptn( "StudentInCourseCollection",
StudentInCourseCollectionXptn::allocFailed );
}
siccPAllStudents = 0;
siccPAllCourses = 0;
} // StudentInCourseCollection::StudentInCourseCollection

public:
// . . .
const StudentCollection* getPAllStudents() const
{ return siccPAllStudents; }
const CourseCollection* getPAllCourses( ) const
{ return siccPAllCourses; }
// setters
void setPAllStudents( const StudentCollection* pStudents )
{ siccPAllStudents = pStudents; }
void setPAllCourses( const CourseCollection* pCourses )
{ siccPAllCourses = pCourses; }
, :
CourseCollection allCourses;
StudentCollection allStudents;
StudentInCourseCollection allEnrollments;
:
allEnrollments.setPAllStudents( &allStudents );
allEnrollments.setPAllCourses( &allCourses );
delete1StudentInCourse() add1StudentInCourse() -
siccPAllStudents != 0 / siccPAllCourses != 0 -
: ( )
804 Project 04

[sCourses Student siccArr StudentInCourseCollection]


.
add1StudentInCourse():
-
.
:
void add1StudentInCourse( const StudentInCourse& aStdnInCrs )
{
if ( siccArr
(aStdnInCrs.getSIdNum(),aStdnInCrs.getCCode()) )
{
// . . .
}
} // StudentInCourseCollection::add1StudentInCourse
( )
:
if ( siccPAllCourses == 0 )
throw
if ( aStdnInCrs.getCCode() )
throw
if ( siccPAllStudents == 0 )
throw
if ( .. aStdnInCrs.getSIdNum() )
throw
:
( )

( )
aStdnInCrs siccArr
add1Student()
(CourseCollection) siccPAllCourses:
siccPAllCourses->add1Student( aStdnInCrs.getCCode() );
-
:
Course oneCourse( siccPAllCourses->get1Course(aStdnInCrs.getCCode()) );
add1Course
(StudentCollection) siccPAllStudents:7
siccPAllStudents->add1Course( aStdnInCrs.getSIdNum(), oneCourse );
aStdnInCrs siccArr StudentIn-
CourseCollection:
insert1StudentInCourse( aStdnInCrs );
:
void StudentInCourseCollection::add1StudentInCourse(
const StudentInCourse& aStdnInCrs )
{
if ( findNdx(aStdnInCrs.getSIdNum(), aStdnInCrs.getCCode()) < 0 )
{ //
if ( siccPAllCourses == 0 )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::noCrs );

7 oneCourse
:
pAllStudents->add1Course( aStdnInCrs.getSIdNum(),
pAllCourses->get1Course( aStdnInCrs.getCCode() );
805

if ( !(siccPAllCourses->find1Course(aStdnInCrs.getCCode())) )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::unknownCrs,
aStdnInCrs.getCCode() );
if ( siccPAllStudents == 0 )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::noStdnt );
if ( !(siccPAllStudents->find1Student(aStdnInCrs.getSIdNum())) )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::unknownStdn,
aStdnInCrs.getSIdNum() );
siccPAllCourses->add1Student( aStdnInCrs.getCCode() );
Course oneCourse( siccPAllCourses->get1Course(aStdnInCrs.getCCode()) );
siccPAllStudents->add1Course( aStdnInCrs.getSIdNum(), oneCourse );
insert1StudentInCourse( aStdnInCrs );
}
} // StudentInCourseCollection::add1StudentInCourse
delete1StudentInCourse() :
void StudentInCourseCollection::delete1StudentInCourse( int aIdNum,
string code )
{
int ndx( findNdx( aIdNum, code );
if ( ndx >= 0 ) //
{
if ( siccPAllCourses == 0 )
throw StudentInCourseCollectionXptn( "delete1StudentInCourse",
StudentInCourseCollectionXptn::noCrs );
if ( siccPAllStudents == 0 )
throw StudentInCourseCollectionXptn( "delete1StudentInCourse",
StudentInCourseCollectionXptn::noStdnt );
siccPAllCourses->delete1Student( code );
Course oneCourse( siccPAllCourses->get1Course(code) );
siccPAllStudents->delete1Course( aIdNum, oneCourse );
erase1StudentInCourse( ndx );
}
} // StudentInCourseCollection::delete1StudentInCourse
StudentInCourseCollection :
class CourseCollection;
class StudentCollection;

class StudentInCourseCollection
{ // version 1
public:
StudentInCourseCollection();
~StudentInCourseCollection() { delete[] siccArr; };
// getters
size_t getNOfStudentInCourses() const
{ return siccNOfStudentInCourses; }
const StudentInCourse* getArr() const { return siccArr; }
const StudentCollection* getPAllStudents() const
{ return siccPAllStudents; }
const CourseCollection* getPAllCourses( ) const
{ return siccPAllCourses; }
// setters
void setPAllStudents( StudentCollection* pStudents )
{ siccPAllStudents = pStudents; }
void setPAllCourses( CourseCollection* pCourses )
{ siccPAllCourses = pCourses; }
// 1 StudentInCourse
bool find1StudentInCourse( int aIdNum, string code ) const
{ return ( findNdx(aIdNum, code) >= 0 ); }
void delete1StudentInCourse( int aIdNum, string code );
void add1StudentInCourse( const StudentInCourse& aStdnInCrs );
const StudentInCourse& get1StudentInCourse( int aIdNum,
string code ) const;
806 Project 04

// other
void save( ofstream& bout ) const;
void load( ifstream& bin );
void swapArr( StudentInCourseCollection& rhs );
void display( ostream& tout ) const;
private:
enum { siccIncr = 50 };
StudentInCourse* siccArr;
size_t siccNOfStudentInCourses;
size_t siccReserved;
StudentCollection* siccPAllStudents;
CourseCollection* siccPAllCourses;

StudentInCourseCollection( const StudentInCourseCollection& rhs ) { };


StudentInCourseCollection& operator=(
const StudentInCourseCollection& rhs ) { };
void erase1StudentInCourse( int ndx );
void insert1StudentInCourse( const StudentInCourse& aStdnInCrs );
int findNdx( int aIdNum, string code ) const;
}; // StudentInCourseCollection
CourseCollection StudentCol-
lection.
StudentCollection* siccPAllStudents;
CourseCollection* siccPAllCourses;
:
struct StudentInCourseCollectionXptn
{ // version 1
enum { allocFailed, notFound, noCrs, unknownCrs, noStdnt,
unknownStdn, fileNotOpen, cannotWrite, cannotRead };
char funcName[100];
int errorCode;
char errStrVal[100];
char errIntVal;
StudentInCourse::SICKey errSICVal;
StudentInCourseCollectionXptn( const char* mn, int ec, const char* sv="" )
: errorCode( ec )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; };
StudentInCourseCollectionXptn( const char* mn, int ec, int iv )
: errorCode( ec ), errIntVal( iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; };
StudentInCourseCollectionXptn( const char* mn, int ec,
const StudentInCourse::SICKey& sk )
: errorCode( ec ), errSICVal( sk )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; };
}; // StudentInCourseCollectionXptn

Prj04.9


( Course Collection),
add1Student().
( StudentCollection),
add1Course().
( Stu-
dentInCourseCollection) add1StudentInCourse().
807


; ; !
. .
StudentInCourseCollection::add1StudentInCourse(), , -
. , -
() .
; :
(Course Collection::)add1Student(), (StudentCollection::)add1Course()
.
.

.
( private) (CourseCollection::)add1Student(), (StudentCollec-
tion::)add1Course() add1StudentInCourse()
.
:
. , ,
(!) , -
.
, -
.
;
CourseCollection StudentCollection:
friend void StudentInCourseCollection::add1StudentInCourse(
const StudentInCourse& aStdnInCrs );
friend void StudentInCourseCollection::delete1StudentInCourse( int aIdNum,
string code );
private CourseCollection add1Student delete1Student.
private StudentCollection add1Course delete1Course.

Prj04.10
Course-
Collection StudentCollection.

Prj04.10.1 CourseCollection
CourseCollection::delete1Course().
Prj04.3.1
: (cNoOfStudents
> 0); :

.
( cNoOfStudents == 0)
.
Prj04.4 ( )
:
808 Project 04

DeletedCourseCollection Deleted-
StudentInCourseCollection8
class DeletedCourse
{
private:
// . . .
public:
Course dcCourse;
time_t dcDelTime; // DateTime dcDelTime ( )
}; // DeletedCourse
class DeletedStudentInCourse
{
private:
// . . .
public:
StudentInCourse dsiccEnroll;
time_t dsiccDelTime; // DateTime dsiccDelTime
}; // DeletedStudentInCourse
CourseCollection::delete1Course() ,
CourseCollection::moveOut1Course(), :
-
( Deleted-
StudentInCourse) DeletedStudentInCourseCollection.
StudentInCourseCollection::moveOut1StudentIn-
Course().

DeletedCourse DeletedCourse-
Collection.
,
.
StudentIn-
CourseCollection::delete1StudentInCourse() .
:
StudentInCourseCollection* ccPAllEnrollments;
0 ( )
:
const StudentInCourseCollection*
CourseCollection::getPAllEnrollments() const
{ return ccPAllEnrollments; }

void CourseCollection::setPAllEnrollments(
StudentInCourseCollection* pEnrollments )
{ ccPAllEnrollments = pEnrollments; }

.
CourseCollection :
class CourseCollection
{ // version 1
friend void StudentInCourseCollection::add1StudentInCourse(
const StudentInCourse& aStdnInCrs );
friend void StudentInCourseCollection::delete1StudentInCourse( int aIdNum,
string code );
public:
CourseCollection();

8 DeletedStudentCollection.
809

~CourseCollection() { delete[] ccArr; };


// getters
size_t getNOfCourses() const { return ccNOfCourses; }
const Course* getArr() const { return ccArr; }
// const StudentInCourseCollection* getPAllEnrollments() const
// { return ccPAllEnrollments; }
// setters
// void setPAllEnrollments( StudentInCourseCollection*
// pEnrollments)
// { ccPAllEnrollments = pEnrollments; }
// 1 Course
bool find1Course( const string& code ) const
{ return ( findNdx(code) >= 0 ); };
void delete1Course( string code );
void add1Course( const Course& aCourse );
const Course& get1Course( string code ) const;
// other
void save( ofstream& bout ) const;
void load( ifstream& bin );
void swap( CourseCollection& rhs );
void display( ostream& tout ) const;
private:
enum { ccIncr = 30 };
Course* ccArr;
size_t ccNOfCourses;
size_t ccReserved;
// StudentInCourseCollection* ccPAllEnrollments;

CourseCollection( const CourseCollection& rhs ) { };


CourseCollection& operator=( const CourseCollection& rhs ) { };
void erase1Course( int ndx );
void insert1Course( const Course& aCourse );
void add1Student( string code );
void delete1Student( string code );
int findNdx( const string& code ) const;
}; // CourseCollection

.9
:
struct CourseCollectionXptn
{ // version 1
enum { allocFailed, notFound, entity, cannotDel, prereqRef,
noEnroll, enrollRef, fileNotOpen, cannotWrite,
cannotRead };
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
CourseCollectionXptn( const char* mn, int ec,
const char* sv="", int iv=0 )

9 ccPAllEnrollments; -
StudentInCourseCollection CourseCollection;
friend StudentInCourseCollection::add1Stu-
dentInCourse() StudentInCourseCollection::delete1StudentInCourse().
StudentInCourseCollection CourseCollection.
StudentCollection, :
#include "StudentInCourseCollection.h"
#include "CourseCollection.h"
#include "StudentCollection.h"
, CourseCollection ( , Student Collection)
StudentInCourseCollection add1StudentInCourse() delete1Student-
InCourse().
810 Project 04

: errorCode( ec ), errIntVal( iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; };
}; // CourseCollectionXptn
:

CourseCollection. , :
getNOfCourses(), getArr() add1Course() . , -
:
CourseCollection,
...

Prj04.10.2 StudentCollection
add1Student().
, add1Stu-
dentInCourse(), for add1Student().
if ( !scPAllCourses->find1Course(aStCourses[k].s) )
add1StudentInCourse():
void StudentCollection::add1Student( const Student& aStudent )
{
int ndx( findNdx(aStudent.getIdNum()) );
if ( ndx < 0 ) //
{
if ( scPAllEnrollments == 0 )
throw StudentCollectionXptn( "add1Student",
StudentCollectionXptn::noEnroll );
insert1Student( aStudent );
const Course::CourseKey* aStCourses( aStudent.getCourses() );
for ( int k(0); k < aStudent.getNoOfCourses(); ++k )
{
scPAllEnrollments->add1StudentInCourse(
StudentInCourse(aStudent.getIdNum(),
aStCourses[k].s) );
}
}
} // StudentCollection::add1Student
:
scPAllEnrollments
. if.

scPAllEnrollments.
insert1Student() .
, StudentInCourseCollection::add1StudentInCourse() StudentCollection
::add1Course() Student::add1Course()
.
.
StudentCollection::add1Student() CourseCol-
lection::add1Course():
Student
. Student, -
,
.
Course
ocNoOfStudents. ; Course
811

.

.
StudentCollection::delete1Student(), ,
. -
4 5 -
-
,
:
:
class DeletedStudent
{
private:
// . . .
public:
Student dsStudent;
time_t dsDelTime; // DateTime dsDelTime ( )
}; // DeletedStudent
() StudentCollection::delete1Student()
, StudentCollection::moveOut1Student(), :

( -
DeletedStudentInCourse) DeletedStudentInCourse-
Collection .

DeletedStudent DeletedStudent-
Collection.
-
.
add1Course() delete1-
Course().
StudentInCourseCollection::add1StudentInCourse() StudentInCourseCollection::delete1Student-
InCourse().
void StudentCollection::add1Course( int aIdNum, const Course& aCourse )
{
int ndx( findNdx(aIdNum) );
if ( ndx < 0 )
throw StudentCollectionXptn( "add1Course",
StudentCollectionXptn::notFound, aIdNum );
scArr[ndx].add1Course( aCourse );
} // StudentCollection::add1Course

void StudentCollection::delete1Course( int aIdNum, const Course& aCourse )


{
int ndx( findNdx(aIdNum) );
if ( ndx < 0 )
throw StudentCollectionXptn( "delete1Course",
StudentCollectionXptn::notFound, aIdNum );
scArr[ndx].delete1Course( aCourse );
} // StudentCollection::add1Course
StudentCollection:
class StudentCollection
{ // version 1
friend void StudentInCourseCollection::add1StudentInCourse(
const StudentInCourse& aStdnInCrs );
friend void StudentInCourseCollection::delete1StudentInCourse(
812 Project 04

int aIdNum, string code );


public:
StudentCollection();
~StudentCollection() { delete[] scArr; delete[] scIndex; };
// getters
size_t getNOfStudents() const { return scNOfStudents; }
const Student* getArr() const { return scArr; }
const StudentInCourseCollection* getPAllEnrollments() const
{ return scPAllEnrollments; }
// setters
void setPAllEnrollments( StudentInCourseCollection*
pEnrollments )
{ scPAllEnrollments = pEnrollments; }
// 1 Student
bool find1Student( int aIdNum ) const
{ return ( findNdx(aIdNum) >= 0 ); };
const Student& get1Student( int aIdNum ) const;
void add1Student( const Student& aStudent );
void delete1Student( int aIdNum );
// other
void save( ofstream& bout, IndexEntry* index );
void load( ifstream& bin );
void swapArr( StudentCollection& rhs );
void display( ostream& tout ) const;
private:
enum { scIncr = 30 };
Student* scArr;
size_t scNOfStudents;
size_t scReserved;
StudentInCourseCollection* scPAllEnrollments;

StudentCollection( const StudentCollection& rhs ) { };


StudentCollection& operator=( const StudentCollection& rhs ) { };
void erase1Student( int ndx );
void insert1Student( const Student& aStudent );
void add1Course( int aIdNum, const Course& aCourse );
void delete1Course( int aIdNum, const Course& aCourse );
int findNdx( int aIdNum ) const;
}; // StudentCollection
:
struct StudentCollectionXptn
{ // version 1
enum { allocFailed, notFound, noEnroll, enrollRef,
fileNotOpen, cannotWrite, cannotRead };
char funcName[100];
int errorCode;
char errStrVal[100];
char errIntVal;
StudentCollectionXptn( const char* mn, int ec,
const char* sv="", int iv=0 )
: errorCode( ec ), errIntVal( iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; };
StudentCollectionXptn( const char* mn, int ec, int iv )
: errorCode( ec ), errIntVal( iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; };
}; // StudentCollectionXptn

Prj04.11 1
-
(Prj03.2)
.

813

void loadCourses( string flNm, CourseCollection& allCourses )


{
//
ifstream bin( flNm.c_str(), ios_base::binary );
if ( bin.fail() )
throw ProgXptn( "loadCourses", ProgXptn::cannotOpen,
flNm.c_str() );
//
Course oneCourse;
loadSylCourse( bin, oneCourse );
while ( !bin.eof() )
{
oneCourse.clearStudents();
allCourses.add1Course( oneCourse );
loadSylCourse( bin, oneCourse );
} // while
bin.close();
} // loadCourses
( loadSylCourse() Project 3.)
:
allCourses.

Prj04.11.1
enrllmnt.txt:
( -
)
.
-
.

.
:
-
.
-
add1StudentInCourse() add1Student()
. -
.
unknownCrs . -
. -
, 6 (0..5) -
2, 3 5.
: 0, 1 2.
2 5.
5 (0..4) .
: 0, 1 2.
2 4.
4 (0..3) .
: 0, 1, 2 3.
3.
: () 0, 1 2.
814 Project 04


-
. . -
0, 1 3.
() add1Student().
:

. -
:
.
, add1-
StudentInCourse(), .
log.
add1StudentInCourse() .
.
,
log:
add1StudentInCourse()
StudentInCourseCollection. (find-
Ndx())
StudentInCourse. -
( 7)10 -
StudentInCourse StudentInCourseXptn keyLen.

Stu-
dentInCourseCollectionXptn unknownCrs add1StudentInCourse.
:
void readStudentData( string flNm,
StudentCollection& allStudents,
StudentInCourseCollection& allEnrollments,
CourseCollection& allCourses,
ofstream& log )
{
ifstream tin( flNm.c_str() ); //"enrllmnt.txt" );
if ( tin.fail() )
throw ProgXptn( "readStudentData", ProgXptn::cannotOpen, flNm.c_str() );
do {
readAStudent( tin, allStudents, allEnrollments, allCourses, log );
} while( !tin.eof() );
tin.close();
} // readStudentData

:
void readAStudent( istream& tin,
StudentCollection& allStudents,
StudentInCourseCollection& allEnrollments,
CourseCollection& allCourses,
ofstream& log )
{
Student aStudent;
unsigned int sIdNum;

//

10 , . Prj03-1.
815

aStudent.readPartFromText( tin );
if ( !tin.eof() )
{
sIdNum = aStudent.getIdNum();
if ( allStudents.find1Student(aStudent.getIdNum()) )
{ //
//
ignoreStudentData( tin );
log << " multiple entry for student with id num "
<< sIdNum << endl;
}
else
{
//
allStudents.add1Student( aStudent );
string str1;
getline( tin, str1, '\n' );
if ( !tin.eof() )
{
int noc( atoi(str1.c_str()) );
for ( int k(0); k < noc && !tin.eof(); ++k )
{
getline( tin, str1, '\n' );
try
{
StudentInCourse aStdnInCrs( sIdNum, str1 );
allEnrollments.add1StudentInCourse( aStdnInCrs);
}
catch( StudentInCourseXptn& x )
{
if ( x.errorCode == StudentInCourseXptn::keyLen )
log << " student with id num "
<< aStudent.getIdNum()
<< " asking course " << str1 << endl;
else
throw;
} // catch( StudentInCourseXptn...
catch( StudentInCourseCollectionXptn& x )
{
if ( x.errorCode ==
StudentInCourseCollectionXptn::unknownCrs )
log << " student with id num " << aStudent.getIdNum()
<< " asking course " << str1 << endl;
else
throw;
} // catch( StudentInCourseCollectionXptn...
} // for
} // if ( !tin.eof() )
if ( !tin.eof() ) getline( tin, str1, '\n' );//blank line
} // if ( allStudents.find1Student(aStudent.getIdNum()) )
} // if ( !tin.eof() )
} // readAStudent
catch C++ .
:

.
throw;
.

Prj04.11.2
(-
) StudentCollection:
816 Project 04

void StudentCollection::checkWH( ostream& log, int maxWH ) const


{
if ( maxWH <= 0 )
throw StudentCollectionXptn( "checkWH",
StudentCollectionXptn::negWH, maxWH );
for ( int k(0); k < scNOfStudents; ++k )
{
if ( scArr[k].getWH() > maxWH )
log << "student with id num " << scArr[k].getIdNum() << ": "
<< scArr[k].getWH() << " hours/week" << endl;
} // for
} // StudentCollection::checkWH
main, :
unsigned int maxWH( 30 ); //
// : 30 /
allStudents.checkWH( log, maxWH );

Prj04.11.3
( )
void saveCollections( CourseCollection& allCourses,
StudentCollection& allStudents,
SIndexEntry* index,
StudentInCourseCollection& allEnrollments )
{
ofstream bout( "Courses.dta", ios_base::binary );
allCourses.save( bout );
bout.close();
bout.open( "students.dta", ios_base::binary );
allStudents.save( bout, index );
bout.close();
bout.open( "students.ndx", ios_base::binary );
for ( int k(0); k < allStudents.getNOfStudents(); ++k )
bout.write( reinterpret_cast<const char*>(&index[k]),
sizeof(SIndexEntry) );
bout.close();
bout.open( "enrllmnt.dta", ios_base::binary );
allEnrollments.save( bout );
bout.close();
} // saveCollections
:
bout.write( reinterpret_cast<const char*>(index),
allStudents.getNOfStudents()*sizeof(IndexEntry) );

Prj04.11.4 ...
:
#include <string>
#include <fstream>
#include <new>
#include <iostream>

#include "MyTmpltLib.h"

using namespace std;

#include "Course.cpp"
#include "Student.cpp"
#include "StudentInCourse.cpp"
#include "StudentInCourseCollection.h"
#include "CourseCollection.h"
#include "SIndexEntry.h"
817

#include "StudentCollection.h"
#include "CourseCollection.cpp"
#include "StudentCollection.cpp"
#include "StudentInCourseCollection.cpp"

struct ProgXptn
{
enum { allocFailed, cannotOpen };
char functionName[100];
int errorCode;
char errStrVal[100];
ProgXptn( const char* fn, int ec, const char* sv="" )
: errorCode( ec )
{ strncpy( functionName, fn, 99 ); functionName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // ProgXptn

void loadCourses( string flNm, CourseCollection& allCourses );


void readStudentData( string flNm,
StudentCollection& allStudents,
StudentInCourseCollection& allEnrollments,
CourseCollection& allCourses,
ofstream& log );
void saveCollections( CourseCollection& allCourses,
StudentCollection& allStudents,
IndexEntry* index,
StudentInCourseCollection& allEnrollments );

int main()
{
try
{
CourseCollection allCourses;
StudentCollection allStudents;
StudentInCourseCollection allEnrollments;

allEnrollments.setPAllStudents( &allStudents );
allEnrollments.setPAllCourses( &allCourses );

allCourses.setPAllEnrollments( &allEnrollments );
allStudents.setPAllEnrollments( &allEnrollments );

loadCourses( "Courses.dta", allCourses );

ofstream log( "log.txt" );


if ( log.fail() )
throw ProgXptn( "main", ProgXptn::cannotOpen, "log.txt");

readStudentData( "enrllmnt.txt", allStudents, allEnrollments,


allCourses, log );

unsigned int maxWH( 30 ); //


// : 30 /
allStudents.checkWH( log, maxWH );

log.close();

SIndexEntry* index;
try
{ index = new SIndexEntry[allStudents.getNOfStudents()]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }

saveCollections( allCourses, allStudents, index, allEnrollments );

delete[] index;
} // try
818 Project 04

catch( ProgXptn& x ) { /* . . . */ }
catch( MyTmpltLibXptn& x ) { /* . . . */ }
catch( CourseXptn& x ) { /* . . . */ }
catch( StudentXptn& x )
{
switch ( x.errorCode )
{
case StudentXptn::allocFailed:
cout << "Student " << x.objKey << ": no dynamic memory in "
<< x.funcName << endl;
break;
case StudentXptn::negIdNum:
cout << "Student " << x.objKey << ": illegal id num ("
<< x.errIntVal << ") in " << x.funcName << endl;
break;
case StudentXptn::incomplete:
cout << "incomplete data for Student " << x.objKey << " in "
<< x.funcName << endl;
break;
case StudentXptn::fileNotOpen:
cout << "file " << x.errStrVal << " not open in " << x.funcName
<< endl;
break;
case StudentXptn::cannotWrite:
cout << "cannot write to file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
case StudentXptn::cannotRead:
cout << "cannot read from file " << x.errStrVal << " in "
<< x.funcName << endl;
break;
default:
cout << "unexpected StudentXptn for Student " << x.objKey
<< " from " << x.funcName << endl;
} // switch
} // catch( StudentXptn
catch( StudentInCourseXptn& x ) { /* . . . */ }
catch( CourseCollectionXptn& x ) { /* . . . */ }
catch( StudentCollectionXptn& x ) { /* . . . */ }
catch( StudentInCourseCollectionXptn& x ) { /* . . . */ }
catch( ... )
{ cout << "unexpected exceptioon" << endl; }
} // main
:
include .
delete[] index ; ,
, ! !
-
index
.
,
catch
readAStudent main.
, main
.

Prj04.12 2
:
#include <fstream>
819

#include <iostream>
#include <new>

#include "MyTmpltLib.h"

using namespace std;

#include "Course.cpp"
#include "Student.cpp"
#include "SIndexEntry.h"

struct ProgXptn
// 1

void loadIndex( string flNm, PIndexEntry& index, unsigned int& ndxSz );


void retrieve( string flNm, PIndexEntry index, int ndxSz );

int main()
{
IndexEntry* index;
unsigned int ndxSz;
try
{
loadIndex( "students.ndx", index, ndxSz );
retrieve( "students.dta", index, ndxSz );
} // try
catch( ProgXptn& x ) { /* . . . */ }
catch( MyTmpltLibXptn& x ) { /* . . . */ }
catch( StudentXptn& x ) { /* . . . */ }
catch( ... )
{ cout << "unexpected exceptioon" << endl; }
}
SIndexEntry.h :
struct SIndexEntry
{
unsigned int sIdNum;
size_t loc;
explicit IndexEntry( int aIdNum=0, int aLoc=0 )
{ sIdNum = aIdNum; loc = aLoc; }
}; // SIndexEntry

typedef SIndexEntry* PIndexEntry;

bool operator!=( const SIndexEntry& lhs, const SIndexEntry& rhs )


{ return ( lhs.sIdNum != rhs.sIdNum ); }

bool operator==( const SIndexEntry& lhs, const SIndexEntry& rhs )


{ return !(lhs != rhs); }
!= ( ==)
linSearch().
SIndexEntry sIdNum. , -
. ! (
)!
. loadIndex()
15.12.1:
void loadIndex( string flNm, PIndexEntry& index, unsigned int& ndxSz )
{
ifstream bin( flNm.c_str(), ios_base::binary );
if ( bin.fail() )
throw ProgXptn( "loadIndex", ProgXptn::cannotOpen, flNm.c_str() );

bin.seekg( 0, ios_base::end );
unsigned int flSize( bin.tellg() );
820 Project 04

ndxSz = flSize/sizeof(IndexEntry);

try { index = new IndexEntry[ndxSz+1]; }


catch( bad_alloc )
{ throw ProgXptn( "loadIndex", ProgXptn::allocFailed ); }

bin.seekg( 0 );
for ( int k(0); k < ndxSz; ++k )
bin.read( reinterpret_cast<char*>(&index[k]), sizeof(IndexEntry) );
bin.close();
} // loadIndex
:
bin.seekg( 0, ios_base::end );
unsigned int flSize( bin.tellg() );
ndxSz = flSize/sizeof(IndexEntry);
-
.
. +1
linSearch().
, for .
:
void retrieve( string flNm, PIndexEntry index, int ndxSz )
{
ifstream bin( flNm.c_str(), ios_base::binary );
if ( bin.fail() )
throw ProgXptn( "retrieve", ProgXptn::cannotOpen, flNm.c_str() );

string line;
cout << "Student Id Number: "; getline( cin, line, '\n' );
while ( line != "" )
{
int idNum( atoi(line.c_str()) );
int ndx( linSearch(index, ndxSz, 0, ndxSz-1, IndexEntry(idNum)) );
if ( ndx < 0 )
cout << "unknown Student Id Number" << endl;
else
{
Student oneStudent;
bin.seekg( index[ndx].loc );
oneStudent.load( bin );
oneStudent.display( cout );
}
cout << "Student Id Number: "; getline( cin, line, '\n' );
} // while
bin.close();
} // retrieve
retrieve() index
.

index . ndx -
:
Student oneStudent;
bin.seekg( index[ndx].loc );
oneStudent.load( bin );
15.14.3 -
. . ... -
: .
; , -
. -
821

StudentCollection CourseCollection

1..1 1..1 1..1 1..1


scPAllEnrollments ccPAllEnrollments

0..1 0..1
StudentInCourseCollection

1..1

1..*
StudentInCourse

1..* 1..*
0..* 0..*
Student StudentInCourse Course
0..* 0..*
sCourses
. Prj04-1 .

.
.

.

Prj04.13
-
. . Prj04-1 -
.
; .
.
.

(Data Base Management Systems, DBMS) .
11 (
)
. , , ,
.
Project 3 .12

.
:

.

11 .
12
Student 1 .
822 Project 04

-
: ,
. ,
.
( ).
: ,
. , -
,
.
:
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
//

unsigned int sIdNum; //
char sSemester[10]; //
unsigned int sWH; //
unsigned int sNoOfCourses; //
//
Course::CourseKey* sCourses;
,
:
CourseKey cCode; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
CourseKey cPrereq; //
:
CourseKey cCode; //
unsigned int cNoOfStudents; // .
( ,
.)
, ,


.

-
. :
( save-
Collections()) , -


.

.
, (transaction processing)
, -
823

. (-
, ..) .
824 Project 04
project

5

:
Prj05.1 ............................................................................................................................................. 825
Prj05.2 Pascal............................................................................................................ 826
Prj05.3 ............................................................................................................................ 827
Prj05.3.1 : #x.......................................................................................................................................828
Prj05.3.2 - ..............................................................................829
Prj05.3.3 - ...............................................................................830
Prj05.3.4 : x = y ............................................................................................................................832
Prj05.4 ........................................................................................................................................... 832
Prj05.4.1 SetOfUCL ...................................................................................................................835
Prj05.5 ..................................................................................................................... 836
Prj05.6 ......................................................................................................................... 838

Prj05.1
Project .
. -
.
(bitmap). 26
bits long int :
bit 0 1 'A' ,
bit 1 1 'B' ,
...
bit 25 1 'Z' ,
:
3 3 2 2 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 1 1 1
1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0 9 8 7 6 5 4 3 2 1 0

00000010000000000000000001101101
{ 'A', 'C', 'D', 'F', 'G', 'Z' }. { } -
0.
, SetOfUCL, 1
. :
(x, y , u )
: #x,
: x += u x + u,
: x ~= u x ~ u,

1 Set of Upper Case Letters

825
826 Project 05

: x = y x y,
: x = y x y,
: x \= y x \ y,
-
.
.:

: 'A' p, 'B'
p+1, 'C' p+2 ...
text, mstrpc.txt,
. :
'A' 'a' ( : ,
, ).
. ( ) -
(: '\n''\n'
).
, ,
paragltr.dta,
setOfUCL:
( ),

,

.

Prj05.2 Pascal
, -
Pascal :
x, y, z: set of T;
x, y, z T ( ).
:
+ . x + y x y
* . x * y x y
- . x - y x \ y
x = y x <> y x, y
.
u T, u in x true u x
false .
x <= y true x y
false .2 y >= x ( y
x).
Extended Pascal card: card(x)
(cardinality) x (#x).

.

2 x < y . x, y Pascal
.
827

Prj05.3
: true.
struct ( ) class:
struct SetOfUCL
{
unsigned long int bitmap;
// . . .
}; // SetOfUCL
. 3 19.5
struct :
()
. ;
class,
long int bitmap ( ) private
getBitmap setBitmap.:
class SetOfUCL
{
public:
// . . .
private:
unsigned long int bitmap;
}; // SetOfUCL
, bitmap -
(bitValue(), setBit(), clearBit() ) 17.6.
H , :
class SetOfUCL
{
public:
SetOfUCL() { bitmap = 0UL; };
~SetOfUCL() { };
private:
long int bitmap;
}; // SetOfUCL
, . -
:
SetOfUCL x;
// x == { }
x .
-
,
.
( ) -
. :
explicit SetOfUCL( char c );
setBit().
1; 'A'
0, c :
static_cast<int>(c) - static_cast<int>('A')
c ;
:
SetOfUCL::SetOfUCL( char c )
{
if ( !isupper( c ) )
throw SetOfUCLXptn( "SetOfUCL", SetOfUCLXptn::nonUCL, c );
828 Project 05

bitmap = 1;
bitmap <<= ( static_cast<int>(c) - static_cast<int>('A') );
} // SetOfUCL::SetOfUCL

SetOfUCL oneSet( 'S' );
() 'S'.
:
1. :
bitmap <<= ( c - 'A' );
.
, :
-
:
'A' p, 'B' p+1, 'C'
p+2 ...
bit 0 1 'A' .
2. setBit() :
SetOfUCL::SetOfUCL( char c )
{
if ( !isupper( c ) )
throw SetOfUCLXptn( "SetOfUCL", SetOfUCLXptn::nonUCL, c );

bitmap = 0;
setBit( bitmap, static_cast<int>(c) - static_cast<int>('A') );
} // SetOfUCL::SetOfUCL
,
setBit().
setBit()
SetOfUCLXptn; ! !
get set ; bitmap . get
() set
: x += u : x ~= u.
, ,
:
void SetOfUCL::display( ostream& tout ) const
{
unsigned long int x( 1 );

for ( int k(0); k <= 25; ++k )


{
if ( (bitmap & x) != 0 )
tout << static_cast<char>( k + static_cast<int>('A') );
x <<= 1;
} // for
tout << endl;
} // SetOfUCL::display

Prj05.3.1 : #x
x
(#x). Extended Pascal card:
x.card() == #x
829

1 -
bitmap, 1 bitmap. ,
count1:
unsigned int SetOfUCL::card() const
{ return count1( bitmap ); } // SetOfUCL::card
:
unsigned int SetOfUCL::card() const
{
unsigned long int x( 1 );
int fv( 0 ), lastb( 8*sizeof(unsigned long int)-1 );

for ( int k(0); k <= lastb; ++k )


{
if ( (bitmap & x) != 0 ) ++fv;
x <<= 1;
} // for
return fv;
} // SetOfUCL::card

Prj05.3.2 -
;
. , :
true { u x } u x
x = x { u } (x = { u }):
true { x = x { u } } u x
operator@=
operator@ ( @)
=.
Pascal operator+=. 22.6
:
SetOfUCL& SetOfUCL::operator+=( const SetOfUCL& rhs )
{
bitmap = bitmap | rhs.bitmap;
return *this;
} // SetOfUCL::operator+=
, : union
! :
SetOfUCL& SetOfUCL::setUnion( const SetOfUCL& rhs )
{
return ( *this += rhs );
} // SetOfUCL::setUnion
; x SetOfUCL

x += SetOfUCL( S );
x = x { S }.
; 22.7.1:
SetOfUCL operator+( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
SetOfUCL fv( lhs );
fv += rhs;
return fv;
} // SetOfUCL operator+
friend.
830 Project 05

x +=
S. ; , :
explicit .
+=.
( ==) -
x == S . , :
SetOfUCL& SetOfUCL::operator+=( char c )
{
if ( !isupper(c) )
throw SetOfUCLXptn( "operator+=", SetOfUCLXptn::nonUCL, c );

*this += SetOfUCL( c );
return *this;
} // SetOfUCL::operator+=
:
SetOfUCL& SetOfUCL::insert( char c )
{
return ( *this += c );
} // SetOfUCL::insert

:
SetOfUCL operator+( const SetOfUCL& lhs, char rhs )
, : +
, +=. -
+=. : , -
, -
. ,
() -
, .


SetOfUCL x( 'A' ), y( x ), z;

x += 'B'; x.insert( 'C' );


x.display( cout );
y += 'C'; y.insert( 'D' ); y += 'E';
y.display( cout );
z = x + y;
z.display( cout );
x.setUnion( y );
x.display( cout );
cout << x.card() << endl;
:
ABC
ACDE
ABCDE
ABCDE
5

Prj05.3.3 -
x \ y x y,

:
831

true { u x } u x
true { x = x \ { u } } u x
-=
\=. -
Pascal ~
~ : !
x \ y , x,
x y ( ):
SetOfUCL& SetOfUCL::operator-=( const SetOfUCL& rhs )
{
bitmap = bitmap & ( bitmap ^ rhs.bitmap );
return *this;
} // SetOfUCL::operator-=
:
SetOfUCL& SetOfUCL::setDifference( const SetOfUCL& rhs )
{
return ( *this -= rhs );
} // SetOfUCL::setDifference
:
SetOfUCL operator-( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
SetOfUCL fv( lhs );
fv -= rhs;
return fv;
} // operator-( SetOfUCL, char )
:
SetOfUCL& SetOfUCL::operator-=( char c )
{
if ( isupper(c) )
{
*this -= SetOfUCL( c );
}
return *this;
} // SetOfUCL::operator-=
c
c *this.

SetOfUCL& SetOfUCL::remove( char c )
{
return ( *this -= c );
} // SetOfUCL::remove
.


x.display( cout ); y.display( cout );
y -= x;
y.display( cout );
y -= 'D';
y.display( cout );
y -= 'Q';
y.display( cout );
z = x - y;
z.display( cout );
:
ABC
ACDE
DE
832 Project 05

E
E
ABC

Prj05.3.4 : x = y
Pascal, *= =:
SetOfUCL& SetOfUCL::operator*=( const SetOfUCL& rhs )
{
bitmap = bitmap & rhs.bitmap;
return *this;
} // SetOfUCL::operator*=
:
SetOfUCL operator*( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
SetOfUCL fv( lhs );
fv *= rhs;
return fv;
} // operator*( SetOfUCL, SetOfUCL )

Prj05.4
: -
( ). -

void readParagraph( ifstream& tin, SetOfUCL& letSet )
tin text -
letSet .
; :
"" letSet
c
while ( )
{
if ( c )
letSet
c
}
letSet; bitmap letSet.
3:
void clear() { bitmap = 0L; };
letSet :4
letSet.clear();
c :
tin.get(c);
letSet :
letSet.insert( toupper(c) );
. c : isalpha(c).

3 :
bool isEmpty() const { return ( bitmap == 0UL ); }
4 clear() . ,
letSet : letSet = SetOfUCL().
833

H . ;
'\n''\n'
.
'\n''\n' -
(peek) .
. :
char c, lastC;
lastC c:
lastC = c; tin.get(c);
, :
if ( c == '\n' )
{
eopar = ( lastC == '\n' );
}
:
bool eopar; // end of paragraph
:
!tin.eof() && !eopar
:
eopar = false; lastC = '\0';
:
void readParagraph( ifstream& tin, SetOfUCL& letSet )
{
bool eopar; // end of paragraph
char c, lastC;

letSet.clear();
eopar = false; lastC = '\0';
tin.get( c );
while ( !tin.eof() && !eopar )
{
if ( isalpha( c ) )
{
letSet.insert( toupper( c ) );
}
else if ( c == '\n' )
{
eopar = ( lastC == '\n' );
}
lastC = c; tin.get( c );
} // while
} // readParagraph
.
:
curSet
nextSet
common = curSet nextSet notInNext = curSet \ nextSet
curSet, common, notInNext

. : -
nextSet.
:
curSet = nextSet
nextSet
common = curSet nextSet notInNext = curSet \ nextSet
curSet, common, notInNext
834 Project 05

curSet = nextSet
nextSet
common = curSet nextSet notInNext = curSet \ nextSet
curSet, common, notInNext
. . .
, , curSet
. ;
( -
) .
:
curSet
while ( !tin.eof() )
{
nextSet


common = curSet nextSet notInNext = curSet \ nextSet
curSet, common, notInNext
curSet = nextSet
}
nextSet = { }
common = curSet nextSet notInNext = curSet \ nextSet
curSet, common, notInNext
. :
SetOfUCL curSet, nextSet, common, notInNext;
ifstream tin( "mstrpc.txt" );
ofstream bout( "paragltr.dta", ios::binary );
:
curSet
:
readParagraph( tin, curSet );
nextSet
:
readParagraph( tin, nextSet );
common = curSet nextSet notInNext = curSet \ nextSet
:
common = curSet * nextSet;
notInNext = curSet - nextSet;
curSet, common, notInNext ;
:
bout.write( reinterpret_cast<char*>( &curSet ),
sizeof( curSet ) );
.
:
void SetOfUCL::save( ostream& bout ) const
{
bout.write( reinterpret_cast<const char*>(&bitmap), sizeof(bitmap) );
} // SetOfUCL::save
:
curSet.save( bout );
common.save( bout ); notInNext.save( bout );
:
#include <fstream>
#include <iostream>
#include <cctype>
835

#include "SetOfUCL.cpp"

using namespace std;

void readParagraph( ifstream& tin, SetOfUCL& letSet );

int main()
{
SetOfUCL curSet, nextSet, common, notInNext;
ifstream tin( "mstrpc.txt" );
ofstream bout( "paragltr.dta", ios::binary );

readParagraph( tin, curSet );


while ( !tin.eof() )
{
readParagraph( tin, nextSet );
common = curSet * nextSet;
notInNext = curSet - nextSet;
curSet.save( bout );
common.save( bout ); notInNext.save( bout );
curSet = nextSet;
} // while
tin.close();
nextSet.clear();
common = curSet * nextSet;
notInNext = curSet - nextSet;
curSet.save( bout );
common.save( bout ); notInNext.save( bout );
bout.close();
} // main

void readParagraph( ifstream& tin, SetOfUCL& letSet )


//

Prj05.4.1 SetOfUCL
:
class SetOfUCL
{
public:
SetOfUCL() { bitmap = 0UL; };
explicit SetOfUCL( char c );
~SetOfUCL() { };
unsigned int card() const;
SetOfUCL& operator+=( const SetOfUCL& rhs );
SetOfUCL& setUnion( const SetOfUCL& rhs );
SetOfUCL& operator+=( char c );
SetOfUCL& insert( char c );
SetOfUCL& operator-=( const SetOfUCL& rhs );
SetOfUCL& setDifference( const SetOfUCL& rhs );
SetOfUCL& operator-=( char c );
SetOfUCL& remove( char c );
SetOfUCL& operator*=( const SetOfUCL& rhs );
SetOfUCL& setIntersection( const SetOfUCL& rhs );
void clear() { bitmap = 0UL; };
bool isEmpty() const { return ( bitmap == 0UL ); };
void save( ostream& bout ) const;
private:
unsigned long int bitmap;
}; // SetOfUCL

SetOfUCL operator+( const SetOfUCL& lhs, const SetOfUCL& rhs );


SetOfUCL operator+( const SetOfUCL& lhs, char rhs );
SetOfUCL operator-( const SetOfUCL& lhs, const SetOfUCL& rhs );
836 Project 05

SetOfUCL operator-( const SetOfUCL& lhs, char rhs );


SetOfUCL operator*( const SetOfUCL& lhs, const SetOfUCL& rhs );

Prj05.5

: :5
__:XPX
:
__:PXPX
:
x, y: P X (x y u:X u x u y)
. ; C++
in . -
, ..:
u isMemberOf x x hasMember u

u x x.hasMember(u).
bool -
bitValue():
bool SetOfUCL::hasMember( char c ) const
{
bool fv( false );

if ( isupper( c ) )
{
unsigned long int x( 1UL );
x <<= static_cast<int>(c) - static_cast<int>('A');
fv = ( ( bitmap & x ) != 0 );
}
return fv;
} // SetOfUCL::hasMember
c
.
, :
bool isMemberOf( char c, const SetOfUCL& rhs )
: isMemberOf( u, x ). ,
friend .6
-
. .
:
(x y) (x = x y)
:
bool SetOfUCL::isSubset( SetOfUCL rhs ) const
{ return ( bitmap == ( bitmap & rhs.bitmap ) ); } // isSubset
x, y SetOfUCL x y
x.isSubset(y).

5 ( ) X P X
X.
6 , , , :
bool isMemberOf( char c, const SetOfUCL& rhs ) { return rhs.hasMember( c ); }
837

Pascal <= . -
:
bool operator<=( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
return lhs.isSubset( rhs );
} // operator<=( SetOfUCL...
x.isSubset(y) x <= y.
Pascal >= , -
isSubset():
bool operator>=( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
return rhs.isSubset( lhs );
} // operator<=( SetOfUCL...
== -
:
bool operator==( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
return ( lhs.bitmap == rhs.bitmap );
} // operator==( const SetOfUCL

bool operator!=( const SetOfUCL& lhs, const SetOfUCL& rhs )


{
return ( !(lhs==rhs) );
} // operator==
friend.7
(proper sub-
set) :
bool SetOfUCL::isProperSubset( const SetOfUCL& rhs ) const
{
return ( this->isSubset(rhs) && (bitmap != rhs.bitmap) );
} // isProperSubset
:
bool operator<( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
return lhs.isProperSubset( rhs );
} // SetOfUCL::operator<
:
: x < y x >= y ! x
y x < y x
y. < !
, SetOfUCL.h :
#ifndef _SETOFUCL_H
#define _SETOFUCL_H

#include <string>
#include <fstream>

using namespace std;

class SetOfUCL
{
friend bool operator==( const SetOfUCL& lhs, const SetOfUCL& rhs );
public:
SetOfUCL() { bitmap = 0UL; };

7 return ( lhs.isSubset(rhs) && rhs.isSubset(lhs) )


friend; , ...
838 Project 05

explicit SetOfUCL( char c );


~SetOfUCL() { };
unsigned int card() const;
SetOfUCL& operator+=( const SetOfUCL& rhs );
SetOfUCL& setUnion( const SetOfUCL& rhs );
SetOfUCL& operator+=( char c );
SetOfUCL& insert( char c );
SetOfUCL& operator-=( const SetOfUCL& rhs );
SetOfUCL& setDifference( const SetOfUCL& rhs );
SetOfUCL& operator-=( char c );
SetOfUCL& remove( char c );
SetOfUCL& operator*=( const SetOfUCL& rhs );
SetOfUCL& setIntersection( const SetOfUCL& rhs );
void clear() { bitmap = 0UL; };
bool isEmpty() const { return ( bitmap == 0UL ); };
void save( ostream& bout ) const;

bool hasMember( char c ) const;


bool isSubset( SetOfUCL rhs ) const;
bool isProperSubset( const SetOfUCL& rhs ) const;

void display( ostream& tout ) const;


private:
unsigned long int bitmap;
}; // SetOfUCL

SetOfUCL operator+( const SetOfUCL& lhs, const SetOfUCL& rhs );


SetOfUCL operator+( const SetOfUCL& lhs, char rhs );
SetOfUCL operator-( const SetOfUCL& lhs, const SetOfUCL& rhs );
SetOfUCL operator-( const SetOfUCL& lhs, char rhs );
SetOfUCL operator*( const SetOfUCL& lhs, const SetOfUCL& rhs );

bool operator<=( const SetOfUCL& lhs, const SetOfUCL& rhs );


bool operator<( const SetOfUCL& lhs, const SetOfUCL& rhs );
bool operator!=( const SetOfUCL& lhs, const SetOfUCL& rhs );

struct SetOfUCLXptn
{
enum { nonUCL };
char funcName[100];
int errorCode;
char errCharVal;
SetOfUCLXptn( const char* mn, int ec, char c=0 )
: errorCode( ec ), errCharVal( c )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // SetOfUCLXptn

Prj05.6

.
() += -= -
( )
. + (
-). , .
22.7.1 += +
-= - : -
. :
SetOfUCL operator-( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
SetOfUCL fv( lhs );
fv -= rhs;
839

return fv;
} // operator-( SetOfUCL, SetOfUCL )
operator-() fv

.
-
notInNext notInNext = curSet - nextSet
operator-() , fv
.
; fv -
.
.
SetOfUCL& SetOfUCL::setDifference( const SetOfUCL& rhs )
{
return ( *this -= rhs );
} // SetOfUCL::setDifference
setDifference()
operator-(). :
SetOfUCL setDifference( const SetOfUCL& lhs, const SetOfUCL& rhs )
{
SetOfUCL fv( lhs );
fv.setDifference( rhs );
return fv;
} // setDifference( SetOfUCL, SetOfUCL )
840 Project 05

23

:
-
.
:
.
:


is_a
(protected)
(virtual)


-- RTTI
:
23.1 ............................................................................................................. 842
23.1.1 ........................................................................................................................................843
23.2 ........................................................................................................ 844
23.3 ................................................................................................................................... 846
23.3.1 ....................................................................................................................................848
23.3.2 ................................................................................................................................848
23.4 ... ............................................................................................................................. 849
23.5 ........................................................................................................................... 849
23.5.1 .....................................................................................................................................852
23.6 ............................................................................................................................ 853
23.7 ................................................................................................ 853
23.8 private protected ............................................................................................................... 854
23.8.1 * protected: ....................................................................................................................855
23.9 ..................................................................................................................................... 857
23.10 * ................................................................................................... 859
23.10.1 virtual ............................................................................................................................860
23.10.2 ... .................................................................................................................................................861
23.11 ......................................................................................................................... 861
23.12 ................................................................................................................................ 862
23.12.1 (;) .....................................................................................................863
23.12.2 * ...........................................................................................................................864
23.13 - RTTI ............................................................................................................... 866
23.13.1 ......................................................................................................................................868
23.14 is_a has_a ................................................................................................................................. 869

841
842 23

23.15 private, protected public ...................................................................................... 872


23.16 ................................................................................................................................ 874
23.17 ................................................................................................................................. 875
23.18 ............................................................................................................................. 876
23.19 .................................................................................................................................................... 878
23.20 ........................................................................................................................................ 879
- ............................................................................................................................................. 879
A .............................................................................................................................................................................879
.............................................................................................................................................................................880

:
-
: -
(inheritance) .

C++ (, ,
C++ .)

23.1
.
. Date
, DateTime, :
class DateTime
{
public:
// . . .
private:
unsigned int dtYear;
unsigned char dtMonth;
unsigned char dtDay;
unsigned char dtHour; // hour (0 .. 23)
unsigned char dtMin; // minutes (0 .. 59)
unsigned char dtSec; // seconds (0 .. 59)
}; // DateTime
dtYear, dtMonth, dtDay;
Date, ! -
:
class DateTime: public Date
{
public:
DateTime( int yp = 1, int mp = 1, int dp = 1,
int hp = 0, int minp = 0, int sp = 0 );
// . . .
private:
unsigned char dtHour; // hour (0 .. 23)
unsigned char dtMin; // minutes (0 .. 59)
unsigned char dtSec; // seconds (0 .. 59)
}; // DateTime
, ;
:
DateTime dt( 2007, 11, 26, 19, 30, 31 );
cout << dt.getDay() << '.' << dt.getMonth() << '.' << dt.getYear() << endl;
cout << dt << endl;
dt += 3; cout << dt << endl;
dt.forward( 3 ); cout << dt << endl;
++dt; cout << dt << endl;
cout << (dt < Date(2008)) << endl;
843

:
26.11.2007
26.11.2007
26.11.2007
26.11.2007
27.11.2007
1
dt DateTime -
Date! :
DateTime (inherits) -
Date.
, DateTime
.
.
DateTime Date -
. , :
IDateTime: (dYear > 0) && (0 < dMonth <= 12) && (0 < dDay <= lastDay(dYear, dMonth))
&& (0 < dtHour < 24) && (0 < dtMin < 60) && (0 < dtSec < 60)

IDateTime: IDate && (0 < dtHour < 24) && (0 < dtMin < 60) && (0 < dtSec < 60)
, IDate &&:
,
.
Liskov (Liskov & Wing, 1993).
; ; : DateTime -
(is derived) Date (inheritance)
. () Date
(base class)
(superclass)
(parent)
DateTime
(derived)
(subclass)
- (child class).

23.1.1
:
.
. , -
:
,
,
,
,
, -
, ,
(implicit). , ,
844 23

dYear dtHour
Date dMonth dtMin
dDay dtSec
getYear
getMonth operator+=
getHour
getDay operator++
getMin
forward
getSec
setHour
setMin
setSec
DateTime

. 23-1 DateTime -
Date.

.
.
:
.
, -
.
, :
.
,
.
.

23.2
. 23-1: DateTime. -
Date.
; :
DateTime Date;
DateTime Date -
.
:
D
B D .
:
D
B D .
:
,
B, D , -
D.
(substitutability) -
Liskov (Liskov Substitution Principle - LSP).1

1 .
845

, : Date
Date d;
DateTime dt;
Date* pD;
DateTime* pDt;
: DateTime
d = dt; // d
// Date dt . 23-2 -
pD = new DateTime;
:2 DateTime is_a Date.
dt = d;
pDt = new Date;
d = dt d Date dt
(slicing) . ...
:
B D, D -
B ( B D). D
B D is_a B . 23-2.
. D
(refers to) B.
:
D is_a B D a_kind_of B is_a -
. is_a
.

. -
:
this ,
DateTime*.
static_cast<Date*>(this) this
Date*. Date*.
*(static_cast<Date*>(this)) Date.

dt = d -
=. , .
, :
DateTime& DateTime::operator=( const Date& rhs )
{
*(static_cast<Date*>(this)) = rhs:
dtHour = 12; dtMin = 0; dtSec = 0;
} // DateTime::operator=
.

.
. ,
static_cast<Date>(dt)
Date dt.
d = dt, , d = static_cast<Date>(dt).

2 .
846 23

23.3
, ,
. -
21.3 3:
.
, .
.

:
0: #include <iostream>
1: using namespace std;
2:
3: class A
4: {
5: int ma;
6: public:
7: A( int ap = 0 )
8: { ma = ap; cout << "A object created" << endl; }
9: }; // A
10:
11: class B
12: {
13: int mb;
14: public:
15: B( int bp = 0 )
16: { mb = bp; cout << "B object created" << endl; }
17: }; // B
18:
19: class C
20: {
21: int mc;
22: public:
23: C( int cp = 0 )
24: { mc = cp; cout << "C object created" << endl; }
25: }; // C
26:
27: class D: public B
28: {
29: A da;
30: C dc;
31: public:
32: D() { cout << "D object created" << endl; }
33: }; // D
34:
35: int main()
36: {
37: D d;
38: }
D (. 27-33) B (. 11-17) ,
(. 29) A (. 3-9), (. 30) C (. 19-25).
, d (. 37 main)
B, B
d.
da dc A C.
, D.
:

3 . ...
847

B object created
A object created
C object created
D object created

DateTime :
DateTime( int yp = 1, int mp = 1, int dp = 1,
int hp = 0, int minp = 0, int sp = 0 );
, , -
, Date, dtHour, dtMin, dtSec
(
):
{
if ( hp < 0 || 23 < hp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::hourRange, hp );
if ( minp < 0 || 59 < minp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::minRange, minp );
if ( sp < 0 || 59 < sp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::secRange, sp );
dtHour = hp; dtMin = minp; dtSec = sp;
}; // DateTime::DateTime
, ; -

dYear = yp; dMonth = mp; dDay = dp;
4:
Error E2247 dateTime01.cpp 128: 'Date::dYear' is not accessible in function
DateTime::DateTime(int,int,int,int,int,int)
Error E2247 dateTime01.cpp 128: 'Date::dMonth' is not accessible in function
DateTime::DateTime(int,int,int,int,int,int)
Error E2247 dateTime01.cpp 128: 'Date::dDay' is not accessible in function
DateTime::DateTime(int,int,int,int,int,int)
: DateTime dYear, dMonth, dDay -
Date! private: Date
.
, :
DateTime::DateTime( int yp, int mp, int dp,
int hp, int minp, int sp )
: Date( yp, mp, dp )
{
if ( hp < 0 || 23 < hp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::hourRange, hp );
if ( minp < 0 || 59 < minp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::minRange, minp );
if ( sp < 0 || 59 < sp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::secRange, sp );
dtHour = hp; dtMin = minp; dtSec = sp;
}; // DateTime::DateTime
; Date yp, mp, dp
. :

4 Borland C++ v.5.5


848 23


Date.
Date .
.
-
.

23.3.1

:
DateTime::DateTime( int yp, int mp, int dp,
int hp, int minp, int sp )
{
if ( hp < 0 || 23 < hp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::hourRange, hp );
if ( minp < 0 || 59 < minp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::minRange, minp );
if ( sp < 0 || 59 < sp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::secRange, sp );
*(static_cast<Date*>(this)) = Date( yp, mp, dp );
dtHour = hp; dtMin = minp; dtSec = sp;
}; // DateTime::DateTime
, .
.

23.3.2
DateTime
.
. ,
.
:
DateTime dt( 2007, 11, 16, 19, 30, 31 );

Date d( dt );
cout << d << endl;
:
16.11.2007
:
. , d
Date dt.
, DateTime:
DateTime::DateTime( const DateTime& rhs )
: Date( rhs )
{
dtHour = rhs.dtHour; dtMin = rhs.dtMin; dtSec = rhs.dtSec;
}; // DateTime::DateTime
849

Date(rhs) Date -
Date rhs. -
.5

21.7, swap. .

23.4 ...

:
.
.
() -
.
, 23.3 -
:
~A() { cout << "destroying A object" << endl; }
~B() { cout << "destroying B object" << endl; }
. . .
:
destroying D object ( )
destroying C object ( )
destroying A object
destroying B object ( )
...

23.5

.
get set :
unsigned int getHour() const { return dtHour; };
unsigned int getMin() const { return dtMin; };
unsigned int getSec() const { return dtSec; };
void setHour( int hp );
void setMin( int minp );
void setSec( int sp );
:
void DateTime::setHour( int hp )
{
if ( hp < 0 || 23 < hp )
throw DateTimeXptn( "setHour",
DateTimeXptn::hourRange, hp );
dtHour = hp;
} // DateTime::setHour

void DateTime::setMin( int minp )


{
if ( minp < 0 || 59 < minp )

5 . :
DateTime::DateTime( const DateTime& rhs )
: Date( rhs ), dtHour( rhs.dtHour ), dtMin( rhs.dtMin ), dtSec( rhs.dtSec ) { }
850 23

throw DateTimeXptn( "setMin",


DateTimeXptn::minRange, minp );
dtMin = minp;
} // DateTime::setMin

void DateTime::setSec( int sp )


{
if ( sp < 0 || 59 < sp )
throw DateTimeXptn( "setSec",
DateTimeXptn::minRange, sp );
dtSec = sp;
} // DateTime::setSec
forward() +=
. ; :6
DateTime& DateTime::forward( long int ds )
{
tm currD = { dtSec, dtMin, dtHour, getDay(),
getMonth()-1, getYear()-1900, 0, 0, 0 };
time_t currT( mktime(&currD) );
if ( ds < 0 )
{
if ( currT < (-ds) ) // currT + ds < 0
throw DateTimeXptn( "operator+=",
DateTimeXptn::outOfLimits,
ds, *this );
}
else // ds >= 0
{
if ( ds > LONG_MAX - currT ) // currT + ds > ULONG_MAX
throw DateTimeXptn( "operator+=",
DateTimeXptn::outOfLimits,
ds, *this );
}
currT += ds;
currD = *localtime( &currT );
*(static_cast<Date*>(this)) = Date( currD.tm_year+1900,
currD.tm_mon+1,
currD.tm_mday );
dtHour = currD.tm_hour;
dtMin = currD.tm_min;
dtSec = currD.tm_sec;
return *this;
} // Date::forward
:
= (Date).
:
Date& forward( long int dd )
DateTime& forward( long int ds )
.
:
DateTime dt( 2007, 11, 16, 19, 30, 31 );
Date d( dt );
cout << d << endl;
cout << dt.getDay() << '.' << dt.getMonth() << '.'
<< dt.getYear() << ' ' << dt.getHour() << ':'
<< dt.getMin() << ':' << dt.getSec() << endl;
d.forward( 10 );
dt.forward( 10 );
cout << d << endl;
cout << dt.getDay() << '.' << dt.getMonth() << '.'

6 22.5.1.4.
851

<< dt.getYear() << ' ' << dt.getHour() << ':'


<< dt.getMin() << ':' << dt.getSec() << endl;
:
16.11.2007
16.11.2007 19:30:31
26.11.2007
16.11.2007 19:30:41
:
DateTime& operator+=( long int ds ) { return forward( ds ); }
forward() :
d += 10;
dt += 10;
.
, ( ) -
(10) d Date dt DateTime -
10 10 sec. ()
. , -
(overrides)
.

.
, DateTime
forward() Date; , . :
dt.Date::operator+=( 10 );

dt.Date::forward( 10 );
dt :
26.11.2007 19:30:41
. -
.
:
this->Date::
Date (DateTime).
*(static_cast<Date*>(this)) = Date( currD.tm_year+1900,
currD.tm_mon+1,
currD.tm_mday );
:
this->Date::operator=( Date(currD.tm_year+1900, currD.tm_mon+1,
currD.tm_mday) );
this ( )
.
: ++dt dt -
. .
1 sec; -
1 sec forward(). ;
private DateTime:
DateTime& operator++() { }
852 23

++dt
Date
: DateTime& op- -dYear: unsigned int
erator++() is private. -dMonth: unsigned char
, -dDay: unsigned char
++ Date : +getYear(): unsigned int
+getMonth(): unsigned int
dt.Date::operator++();
+getDay(): unsigned int
: +operator+=(dd: int): Date
++ ++dt +forward(dd: int): Date
1 sec , +operator++(): Date
-lastDay( y: int, m: int ): unsigned int
22.2, inline
-leapYear( y: int ): bool
forward:
DateTime& operator++()
{ return forward( 1 ); }
Date DateTime
(22.5.1.6) . -dtHour: unsigned char
. 23-3 -dtMin: unsigned char
-dtSec: unsigned char
.
+getHour(): unsigned int
+getMin(): unsigned int
+getSec(): unsigned int
23.5.1 +setHour( hp: int )
+setMin( minp: int )

+setSec( sp: int )
- +operator+=( ds: int ): DateTime
, , - +forward( ds: int ): DateTime
. -operator++( ): DateTime

, swap(). . 23-3 DateTime


swap() swap() - Date. -
. : dYear,
void DateTime::swap( DateTime& rhs ) dMonth, dDay, getYear, getMonth,
{ getDay. oper-
this->Date::swap( rhs ); ator+=, forward, operator++ (
std::swap( dtHour, rhs.dtHour );
).
std::swap( dtMin, rhs.dtMin );
std::swap( dtSec, rhs.dtSec );
} // DateTime::swap
this->Date::swap(rhs) (, : Date::swap(rhs))
Date rhs.7
:
DateTime& DateTime::operator=( const DateTime& rhs )
{
if ( &rhs != this )
{
DateTime tmp( rhs );
swap( tmp );
}
return *this;
} // DateTime::operator=

7 swap() Date! :
void Date::swap( Date& rhs )
{
std::swap( dYear, rhs.dYear );
std::swap( dMonth, rhs.dMonth );
std::swap( dDay, rhs.dDay );
} // Date::swap
853

23.6
,
.
.
== DateTime :
bool operator==( const DateTime& lhs, const DateTime& rhs )
{
return ( static_cast<Date>(lhs) == static_cast<Date>(rhs) &&
lhs.getHour() == rhs.getHour() &&
lhs.getMin() == rhs.getMin() &&
lhs.getSec() == rhs.getSec() );
} // operator==( const DateTime
<<:
ostream& operator<<( ostream& tout, const DateTime& rhs )
{
return tout << static_cast<Date>( rhs ) << ' '
<< rhs.getHour() << ':' << rhs.getMin() << ':'
<< rhs.getSec();
} // operator<<( ostream& tout, const DateTime

23.7
:

.
, :
struct DateTimeXptn : public DateXptn
{
enum { hourRange = 50, minRange, secRange };
DateTime errDateTimeVal;
DateTimeXptn( const char* mn, int ec,
int ev1 = 0, int ev2 = 0, int ev3 = 0 )
: DateXptn( mn, ec, ev1, ev2, ev3 ) { }
DateTimeXptn( const char* mn, int ec, int ev1, const DateTime& edt )
: DateXptn( mn, ec, ev1, edt )
{ errDateTimeVal = edt; }
}; // DateTimeXptn
:
hourRange = 50:
DateXptn (0 .. DateXptn::cannotWrite) DateTimeXptn (50..
DateTimeXptn::secRange).
-
:
catch( DateTimeXptn& x )
{ . . . }
catch( DateXptn& x )
{ . . . }
catch catch(DateXptn& x)
catch(DateTimeXptn& x), Date-
TimeXptn DateXptn.
: Date-
TimeXptn DateTime Date
(errDateVal).
854 23

, Date edt, . -
edt errDateTimeVal.

23.8 private protected


23.3 DateTime dYear, dMonth, dDay
Date! private: Date.
DateTime.
, :
-
(.. swap()) set.

get.
, , -
. , private -

.
C++ ,
protected.
, protected
.
:
: , protected

. .
Date :
class Date
{
// . . .
public:
// . . .
protected:
unsigned int dYear;
unsigned char dMonth;
unsigned char dDay;

static unsigned int lastDay( int y, int m );


private:
static bool leapYear( int y );
}; // Date
DateTime ,
:
if ( yp <= 0 ) throw . . .
dYear = yp;
if ( mp <= 0 || 12 < mp ) throw . . .
dMonth = mp;
if ( dp <= 0 || lastDay(dYear, dMonth) < dp )
throw DateXptn( "Date", DateXptn::dayErr, yp, mp, dp );
dDay = dp;

: Date( yp, mp, dp )

*(static_cast<Date*>(this)) = Date( yp, mp, dp );


855

: .
,
set Date. ,
Date .
forword() :
dYear = currD.tm_year+1900;
dMonth = currD.tm_mon+1;
dDay = currD.tm_mday;

*(static_cast<Date*>(this)) = Date( currD.tm_year+1900,
currD.tm_mon+1,
currD.tm_mday );

.
Date
20.8.1,
#dYear: unsigned int
UML, , protected #dMonth: unsigned char
#. . 23-4 #dDay: unsigned char
Date, . +getYear(): unsigned int
- +getMonth(): unsigned int
+getDay(): unsigned int
private pro-
+operator+=(dd: int): Date
tected - +forward(dd: int): Date
. +operator++(): Date
, , private #lastDay( y: int, m: int ): unsigned int
-leapYear( y: int ): bool
protected -
. - . 23-4 Date -
: dYear, dMonth, dDay
lastDay

protected.
private protected -

.
, ,
/ .
, protected,
-

.

23.8.1 * protected:
- : ,
protected
, protected
.
:
class B
{
public:
B( int bp=0 ) { mb = bp; }
void display( ostream& tout ) const { tout << mb; }
protected:
int mb;
}; // B
856 23

class D2: public B


{
public:
D2( int bp=2, int d2p=0 ): B(bp) { md2 = d2p; }
void display( ostream& tout ) const
{ B::display( tout ); tout << ' ' << md2; }
private:
int md2;
}; // D2
D2 :
void xchangeB( B& b );
mb b.
B b;
D2 d2a( 2, 11 );
:
d2a.xchangeB( b );
d2a.display( cout ); cout << endl;
b.display( cout ); cout << endl;
:
0 11
2
:
void xchangeB( B& b ) { std::swap( b.mb, mb ); }
8 : Error E2247 testDerived.cpp 31: 'B::mb'
is not accessible in function D2::xchangeB(B &).
;
(B) protected: int mb.
(D1), mb
b B.
B::mb -
D2::xchangeB(B &).
:
void xchangeB( D1& b ) { std::swap( b.mb, mb ); }
.
D2 d2a( 2, 11 ), d2b( 3, 13 );

d2a.xchangeB( d2b );
d2a.display( cout ); cout << endl;
d2b.display( cout ); cout << endl;
:
3 11
2 13
d2a.xchangeB( b ).

class DD2: public D2
{
public:
DD2( int bp=1, int d2p=0, int dd2p=0 )
: D2(bp, d2p) { mdd2 = dd2p; }
void display( ostream& tout ) const
{ D2::display( tout ); tout << ' ' << mdd2; }

8 Borland BC++, v.5.5.


857

private: B
int mdd2;
}; // DD2
:
DD2 dd2( 5, 17, 23 ); D1 D2

d2a.xchangeB( dd2 );
. DD2

. 23-5 D2 -
class D1: public B
{ protected
public: B -
D1( int bp=1, int d1p=0 ) D2 DD2
: B(bp) { md1 = d1p; } B D1.
void display( ostream& tout ) const
{ B::display( tout ); tout << ' ' << md1; }
private:
int md1;
}; // D1
xchangeB()
void xchangeB( D1& b ) { std::swap( b.mb, mb ); }
: b.mb!
(. 23-5):
() B protected,
D, ( ) B f D, f
protected B
D D.

23.9
23.5 :

. ; :
Date* pind[2];
:
pind[0] = new Date( 2002, 2, 2 );
pind[1] = new DateTime( 2003, 3, 3, 3, 33, 33 );
; !
B, D , -
D . :
pind[0]->forward( 10 );
pind[1]->forward( 10 );
cout << pind[0]->getDay() << endl;
cout << pind[1]->getDay() << endl;
++(*pind[0]);
++(*pind[1]);
cout << pind[0]->getDay() << endl;
cout << pind[1]->getDay() << endl;
:
12
13
13
14
858 23

; forward() ++ -
.
pind Date ...
Date.
: , ! -
, . :
DateTime dt( 2003, 3, 3, 3, 33, 33 );
:
void plus10( Date& d )
{
d.forward( 10 );
} // plus10

cout << dt << endl;
plus10( dt );
cout << dt << endl;
:
3.3.2003 3:33:33
13.3.2003 3:33:33
, forward() Date DateTime. ; ,


-
( const ), .

.
; :

virtual ().
class Date
{
// . . .
public:
virtual const Date& operator+=( long int dd );
virtual const Date& forward( long int dd );
virtual Date& operator++();
// . . .
}; // Date
:
12
3
13
3
:
3.3.2003 3:33:33
3.3.2003 3:33:43
;
virtual ()
(). -
virtual operator+=(), forward(), operator++() Date
DateTime.
859

:


.
virtual ;
: virtual
virtual .9
virtual .
;...

23.10 *
,
.
23.3 ( )
class B
{
public:
B( int bp=0 ) { mb = bp; }
virtual void display( ostream& tout ) const { tout << mb; }
virtual int f() const
{ cout << "B::f()" << endl; return mb+1; }
protected:
int mb;
}; // B

class D1: public B


{
public:
D1( int bp=1, int d1p=0 ): B(bp) { md1 = d1p; }
virtual void display( ostream& tout ) const
{ B::display( tout ); tout << ' ' << md1; }
virtual void g( int& aV, int& aDV ) const
{ cout << "void D1::f()" << endl;
aV = mb; aDV = md1; }
private:
int md1;
}; // D1
: :
B bo;
D1 d1o;
:
cout << "sizeof_bo: " << sizeof(bo) << endl;
cout << "sizeof_d1o: " << sizeof(d1o) << endl;
:10
sizeof_bo: 8
sizeof_d1o: 12
B int
D1 .
int 4 . 4 .
-, vfptr,
( -

9 Once virtual, always virtual!


10 g++ (Dev-C++).
860 23

)
/ (virtual method / function table) vtable.
:
vtable B B::f B::display.
vtable D1 B::f ( B), D1::display
D1::g.
B, bo, vfptr
vtable
B.
D1.

vfptr
.

23.10.1 virtual
virtual
; , .

, plus10Local(),
Date DateTime plus10() 10
sec
plus10Local().
-
:
void plus10Local( Date d )
{
d.forward( 10 );
// . . .
} // plus10Local
: plus10Local(dt) -
Date dt d. dt; !
Date dt. virtual
...

, -
.

. 11
:
, :
const Date& d. d.forward(10) const.
d ,
plus10Local. , ;
...

11 OBJ33 (CERT 2009) : (Do not slice


polymorphic objects).
861

23.10.2 ...
virtual
. . -
, virtual . (-
) .
.
virtual ; -
.
,
.. get set;
-
: (-
) (late deferred binding) . Java C#
() ().
Java virtual
.
C# C++: , , virtual -
.

23.11
23.3,
23.4. :
B* pd( new D );
delete pd;
:
B object created
A object created
C object created
D object created
destroying B object
, destroying B object,

, *pd. ;
, .
; :
virtual.
, :
virtual ~B() { cout << "destroying B object" << endl; }
:
B object created
A object created
C object created
D object created
destroying D object
destroying C object
destroying A object
destroying B object
21.5
~K() {} .
862 23

.
:
virtual ~K() { };


C++ , std::exception,

. :
struct exception
{
exception() throw() { }
virtual ~exception() throw();
virtual const char* what() const throw();
}; // exception
, virtual.
, :
struct DateXptn : public exception
{
// . . .
virtual ~DateXptn() throw() { };
}; // DateXptn

struct DateTimeXptn : public DateXptn


{
// . . .
virtual ~DateTimeXptn() throw() { };
}; // DateTimeXptn

#include <exception>.

23.12

, -
virtual.
, (polymorphism)
( ) A B.
: -
-
, .
C++ -
(subclass subtype). :

(.. d.forward(10) d += 10)
(.. d Date
10 DateTime 10 sec).
; ()
() () (..: const Date& forward(long
int dd)). (;)
(..: const DateTime& forward( long int dd)).
863

12
.

virtual.
-
: (;) .
(;). , -
. -
.
( ).
.
; , -
( ) . -
.
, (.. Date* Date&) -
(.. DateTime* DateTime&)
.13
, forward() +=
Date DateTime:
const Date& Date::forward( long int dd )
const DateTime& DateTime::forward( long int ds )

const Date& Date::operator+=( long int dd )


const DateTime& DateTime::operator+=( long int ds )
virtual .

(run-time).
:
, virtual , -

. 23.11
:
virtual ~exception() throw();
(DateXptn) :
virtual ~DateTimeXptn() throw() { };
throw() .

23.12.1 (;)
++. -
, :
Date Date::operator++( int )
DateTime DateTime::operator++( int )

.

12 .
. .
13 (covariance).
864 23

-
.
virtual .
, , -
(compile time) -
(run-time). -
! ,
(CERT 2009):14
virtual.

23.12.2 *
(overloading) -
(overriding) . -
, .
23.3 , B:
class B
{
public:
B( int bp=0 ) { mb = bp; }
virtual int f() const
{ cout << "B::f()" << endl; return mb+1; }
protected:
int mb;
}; // B
D1:
class D1: public B
{
public:
D1( int bp=1, int d1p=0 ): B(bp) { md1 = d1p; }
virtual int f() const
{ cout << "D1::f()" << endl; return mb+md1; }
private:
int md1;
}; // D1
f() D1 D1 f() B.
main
D1 d( 1, 2 );
cout << d.f() << endl;
B b( d );
cout << b.f() << endl;
:
D1::f()
3
B::f()
2
D1 :
class D1: public B
{
public:
D1( int bp=1, int d1p=0 ): B(bp) { md1 = d1p; }
virtual void f( int& aV, int& aDV ) const
{ cout << "void D1::f()" << endl;
aV = mb; aDV = md1; }

14 OBJ02 : Do not hide inherited non-virtual member functions.


865

private:
int md1;
}; // D1
main :
D1 d( 1, 2 );
cout << d.f() << endl;
int a1, a2;
d.f( a1, a2 );
cout << a1 << " " << a2 << endl;
:
virtual int f() const;
:
virtual void f( int& aV, int& aDV ) const;
; , . , -
, f() B, , virtual
, , !
, :
cout << d.f() << endl;
(Error E2193 tO.cpp 63: Too few parameters in call to 'D1::f(int &,int &)
const' in function main()15) , , : -
f() D1.
.
:
cout << d.B::f() << endl;
:
B::f()
2
void D1::f()
1 2
D1 f() .
class D1: public B
{
public:
D1( int bp=1, int d1p=0 ): B(bp) { md1 = d1p; }
virtual int f() const
{ cout << "D1::f()" << endl; return mb+md1; }
virtual void f( int& aV, int& aDV ) const
{ cout << "void D1::f()" << endl;
aV = mb; aDV = md1; }
private:
int md1;
}; // D1
:
virtual int f() const f()
. , virtual ( f() B) !
virtual void f( int& aV, int& aDV ) const .
virtual
D1 ( DD1).

D1 d( 1, 2 );
cout << d.f() << endl;
int a1, a2;

15 Borland BC++, v.5.5.


866 23

d.f( a1, a2 );
cout << a1 << " " << a2 << endl;
, :
D1::f()
3
void D1::f()
1 2
:
!... :
(virtual) .
:
, , :
B* pD( new D1(1,2) );
cout << pD->f() << endl;
int a1, a2;
pD->f( a1, a2 );
cout << a1 << " " << a2 << endl;
B pD->f(a1,
a2)!
.

23.13 - RTTI

. 23.9, :
Date* pind[2];
// . . .
pind[1] = new DateTime( 2003, 3, 3, 3, 33, 33 );

pind[1]->forward( 10 );

cout << pind[1]->getDay() << endl;


virtual pind[1]->getDay() 3.
43. -
forward() . :
cout << pind[1]->getSec() << endl;
: class Date has no member named
getSec. ! protected , virtual ,
; (-) :
protected .
virtual .
; getSec() (virtual) -
.

. ;
(dynamic casting):
cout << dynamic_cast<DateTime*>(pind[1])->getSec() << endl;
dynamic_cast< >(-) (-)
.
0 (NULL).
867

pind[1] Date-
Time DateTime* pind[1].
pind[1]
DateTime ( 0) -
getSec(). -
(convertible) . -
:
DateTime* temp( dynamic_cast<DateTime*>(pind[1]) );
if ( temp != 0 )
cout << temp->getSec() << endl;
, :
( -
);
-
: -
( ).

:
Date* pd = new DateTime( 2004, 4, 4, 4, 44, 44 );
if ( dynamic_cast<Date*>(pd) == 0 ) cout << "OXI" << endl;
else cout << "NAI" << endl;
if ( dynamic_cast<DateTime*>(pd) == 0 ) cout << "OXI"<<endl;
else cout << "NAI"<<endl;
Date* pd0 = new Date( 2005, 5, 5 );
if ( dynamic_cast<Date*>(pd0) == 0 ) cout << "OXI" << endl;
else cout << "NAI" << endl;
if ( dynamic_cast<DateTime*>(pd0) == 0 ) cout << "OXI"<<endl;
else cout << "NAI"<<endl;
:
NAI
NAI
NAI
OXI
pd, ' Date,
DateTime. ,
, dynamic_cast<DateTime*>(pd)
DateTime*.
pd,
Date DateTime pd.
: pd0 Date.

dynamic_cast<DateTime*>(pd0) 0.
:
:
DateTime* pdt( new DateTime(2004, 4, 4, 4, 44, 44) );
dynamic_cast<Date*>(pdt) != 0 C++ :
pdt Date; NAI
if ( dynamic_cast<Date*>(pdt) == 0 ) cout << "OXI" << endl;
else cout << "NAI" << endl;
23.2 DateTime
Date*
*(dynamic_cast<Date*>(this))
868 23

, (Run
Time Type Identification, RTTI) typeid. -
, 2.8.1: :
typeid( ).name()
.
(#include) typeinfo. :
cout << typeid(*pd).name() << endl;
cout << typeid(*pd0).name() << endl;
:
DateTime
Date
typeid type_info,
== !=. , :
if ( typeid(*pd) == typeid(Date) ) cout << "NAI" << endl;
else cout << "OXI" << endl;
if ( typeid(*pd) == typeid(DateTime) ) cout << "NAI" << endl;
else cout << "OXI" << endl;
if ( typeid(*pd0) == typeid(Date) ) cout << "NAI" << endl;
else cout << "OXI" << endl;
if ( typeid(*pd0) == typeid(DateTime) ) cout << "NAI" << endl;
else cout << "OXI" << endl;
:
OXI
NAI
NAI
OXI

23.13.1
:
DateTime dt( 2014, 3, 3, 3, 33, 33 );
cout << "dt = " << dt << endl;
Date& rd( dt );
cout << "rd = " << rd << endl;
Date -
DateTime Date& rd(dt).
:
dt = 3.3.2014 3:33:33
rd = 3.3.2014
, ! . ! ,
. 13.4
dt rd .
rd << Date. , :
DateTime* pRd( reinterpret_cast<DateTime*>(&rd) );
cout << "*pRd = " << *pRd << endl;
:
*pRd = 3.3.2014 3:33:33
;
, :
void aFunc( Date& aDate )

DateTime EDT
Date ED.
869

-
-
:
void aFunc( Date& aDate )
{
// . . .
try
{
DateTime& aDT( dynamic_cast<DateTime&>(aDate) );
// EDT aDT
}
catch( bad_cast& )
{
// ED aDate
}
// . . .
}
aDT -
aDate DateTime.
dynamic_cast (std::)
bad_cast. #include <typeinfo>
bad_cast.
try/catch
if-else!

23.14 is_a has_a


, ,
.
: -
. -
. , :
class OfferedCourse : public Course
{
public:
// . . .
private:
unsigned int ocNoOfStudents; // .
}; // OfferedCourse
:
class OfferedCourse
{
public:
// . . .
private:
Course ocC;
unsigned int ocNoOfStudents; // .
}; // OfferedCourse

has_a (OfferedCourse has_a Course).
; Project 6
Project 4. -

.
. :
class B
870 23

{
public:
B( int newMb=0 )
: mb( newMb ) { };
virtual ~B() { };
void f() { cout << "this is base f" << endl; };
virtual void display( ostream& tout )
{ tout << "base display: mb = " << mb; };
virtual void swap( B& other )
{ std::swap( mb, other.mb ); }
private:
int mb;
}; // B

class D1 : public B
{
public:
D1( int newMb=0, int newMd=0 )
: B( newMb ), md( newMd ) { };
virtual ~D1() { };
virtual void display( ostream& tout )
{ B::display( tout );
tout << " derived display: md = " << md; };
virtual void swap( D1& other )
{ B::swap( other );
std::swap( md, other.md ); }
private:
int md;
}; // D1
:
D1 x( 3, 5 ), u( 19, 17 );
x.f();
cout << "x: "; x.display( cout ); cout << endl;
cout << "u: "; u.display( cout ); cout << endl;
x.B::display( cout ); cout << endl;
x.swap( u );
cout << "after swap" << endl;
cout << "x: "; x.display( cout ); cout << endl;
cout << "u: "; u.display( cout ); cout << endl;
:
this is base f
x: base display: mb = 3 derived display: md = 5
u: base display: mb = 19 derived display: md = 17
base display: mb = 3
after swap
x: base display: mb = 19 derived display: md = 17
u: base display: mb = 3 derived display: md = 5

:
class D2
{
public:
D2( int newMb=0, int newMd=0 )
: md( newMd ) { bo = B(newMb); };
~D2() { };
void display( ostream& tout )
{ bo.display( tout );
tout << " derived display: md = " << md; };
void f() { bo.f(); };
void bdisplay( ostream& tout ) { bo.display( tout ); };
void swap( D2& other )
{ bo.swap( other.bo );
std::swap( md, other.md ); }
private:
871

B bo;
int md;
}; // D2
, D2 f()
bdisplay() B. -
:
D2 y( 3, 5 ), t( 19, 17 );
y.f();
cout << "y: "; y.display( cout ); cout << endl;
cout << "t: "; t.display( cout ); cout << endl;
y.bdisplay( cout ); cout << endl;
y.swap( t );
cout << "after swap" << endl;
cout << "y: "; y.display( cout ); cout << endl;
cout << "t: "; t.display( cout ); cout << endl;
:
, , B bo;
public :
class D3
{
public:
D3( int newMb=0, int newMd=0 )
: md( newMd ) { bo = B(newMb); };
void display( ostream& tout )
{ bo.display( tout );
tout << " derived display: md = " << md; };
void swap( D3& other )
{ bo.swap( other.bo );
std::swap( md, other.md ); }
B bo;
private:
int md;
}; // D3
:
D3 z( 3, 5 ), v( 19, 17 );
z.bo.f();
cout << "z: "; z.display( cout ); cout << endl;
cout << "v: "; v.display( cout ); cout << endl;
z.bo.display( cout ); cout << endl;
z.swap( v );
cout << "after swap" << endl;
cout << "z: "; z.display( cout ); cout << endl;
cout << "v: "; v.display( cout ); cout << endl;
.
: -
B* p(new D1) B* p(new D2).
new D1 -

( )
typeid. CourseCollection (
StudentCollection) Project 6; ccArr
Course*
OfferedCourse. ;
void* ; , , .
-
. ;
is_a ,
,
872 23

. Computer -
HardDisk -
. Computer is_a HardDisk Computer
HardDisk (-
public) . Computer has_a HardDisk.
has_a .
is_a has_a
:

OfferedCourse , ocSemester,
. , -

OfferedCourse -
Course.
OfferedCourse Course
OfferedCourse .
(association) -- (many-to-one)
N : 1 is_a has_a.

,
.

23.15 private, protected public


,
private, protected public.
private )
) .
protected ) )
) )
.
public .

:
class D: private B ) B public
protected D
D ) D D
D* B* ( D& B&).
class D: protected B B public protected
a) D
D ) D.
D* B* ( D& B&) ) D
D ) D.
class D: public B ) B public protected
)
D* B* D& B&.
:
873

class D: public B , -
, B
D.

23.2.
private
has_a . -
:
class D4 : private B
{
public:
D4( int newMb=0, int newMd=0 )
: B( newMb ), md( newMd ) { };
virtual ~D4() { };
virtual void display( ostream& tout )
{ B::display( tout );
tout << " derived display: md = " << md; };
void f() { B::f(); };
void bdisplay( ostream& tout ) { B::display( tout ); };
void swap( D4& other )
{ B::swap( other );
std::swap( md, other.md ); }
private:
int md;
}; // D4
:
D4 v( 3, 5 ), w( 19, 17 );
v.f();
cout << "v: "; v.display( cout ); cout << endl;
cout << "w: "; w.display( cout ); cout << endl;
v.bdisplay( cout ); cout << endl;
v.swap( w );
cout << "after swap" << endl;
cout << "v: "; v.display( cout ); cout << endl;
cout << "w: "; w.display( cout ); cout << endl;
:
this is base f
v: base display: mb = 3 derived display: md = 5
w: base display: mb = 19 derived display: md = 17
base display: mb = 3
after swap
v: base display: mb = 19 derived display: md = 17
w: base display: mb = 3 derived display: md = 5
:
: B public protected -
D. -
D4::f(), D4::bdisplay() D4::swap().
, main(); ! v.f();
: 'B::f()' is not accessible in function main().
v.B::display(cout);. , -
D4::f() D4::bdisplay(), D2.
: D D
D* B* ( D& B&).
D4::swap() D1::swap(). B::swap(other);
D4& (other) B& B::swap().
. , ,
int f1( B& ap )
874 23

{
//...
:
cout << f1( v );
Cannot initialize 'B &' with 'D4' in function main()
.
, :
B* bp( new D4 );
class D: private B
B D.
D is_implemented_in_terms_of B D has_a B.
class D: protected B.
D D
protected.

23.16
:
.
:
, - . :
/
:
1. 0.03 / kWh,
2. 0.06 /kWh

3.
0.06 /kWh A kWh 0.1 /kWh -
A. A .
, , (
).
.
.
, ,
Industrial. ;
. ;
, .
( SmallMediumEnt).
. -
.
( HomeCons)
A .
, ( ) Industrial.
SmallMediumEnt .
HomeCons SmallMediumEnt.
().
.
:
Industrial SmallMediumEnt HomeCons
875

, -

; ! :



-
.
,
.
. 23-6 .
,
class ElecConsumer
{
public:
ElecConsumer( int consCodeP );
unsigned long int getConsCode() const { return ecConsCode; }
void setConsCode( int consCodeP );
virtual double charge( double consumption ) const = 0;
protected:
unsigned long int ecConsCode;
}; // ElecConsumer
: charge -
= 0. charge -
(true virtual method).
(ab-
stract) . , , , -
. , , , -
(concrete) .

, ( ElecConsumer)
. -
.
.
.
, ElecConsumer -
. ,
Industrial SmallMediumEnt HomeCons
:
ElecConsumer Industrial
ElecConsumer SmallMediumEnt
ElecConsumer HomeCons
: is_a ,
is_a -
is_a .

23.17
, 3.1.2 10.3
:
-
.
876 23

ElecConsumer
# mConsCode

+ getConsCode(): unsigned long int


+ setConsCode( consCodeP: long int )
+ charge( consumption: double )

Industrial SmallMediumEnt
- mFixed - mFixed
+ charge( consumption: double )
+ charge( consumption: double )
+ getFixed(): double + charge( consumption: double )
+ setFixed( fixedP: double ) + getFixed(): double
+ setFixed( fixedP: double )
+ getConsLimit(): double
+ setConsLimit( cLimitP: double )

. 23-6 , Industrial, SmallMediumEnt, HomeCons,


ElecConsumer.
.
, .
.

23.18
:
class MyTime
{
friend ostream& operator<<( ostream& tout, const MyTime& rhs );
public:
MyTime( int hp = 0, int minp = 0, int sp = 0 );
unsigned int getHour() const { return mtHour; };
unsigned int getMin() const { return mtMin; };
unsigned int getSec() const { return mtSec; };
void setHour( int hp );
void setMin( int minp );
void setSec( int sp );
MyTime& operator++();
protected:
unsigned int mtHour; // hour (0 .. 23)
unsigned int mtMin; // minutes (0 .. 59)
unsigned int mtSec; // seconds (0 .. 59)
}; // MyTime
Date.
DateTime:
class DateTime : public Date, public MyTime
{
friend ostream& operator<<( ostream& tout, const DateTime& rhs );
public:
DateTime( int yp = 1, int mp = 1, int dp = 1,
int hp = 0, int minp = 0, int sp = 0 )
: Date( yp, mp, dp ), MyTime( hp, minp, sp ) { };
}; // DateTime

ostream& operator<<( ostream& tout, const DateTime& rhs )


{
return ( tout << rhs.dDay << '.' << rhs.dMonth << '.' << rhs.dYear << ' '
<< rhs.mtHour << ':' << rhs.mtMin << ':' << rhs.mtSec );
} // operator<< DateTime
877

DateTime : Date Date MyTime

MyTime.
. 23-7.
DateTime

. 23-7 DateTime -
, ..:
Date
class X : public A, private B, public C { /* ... */ }; MyTime.
:
DateTime dt( 2007, 11, 26, 19, 30, 31 );
dt ! ;
++ Date MyTime ; -
(ambiguity) :
dt.Date::operator++();
cout << dt << endl;
dt.MyTime::operator++();
cout << dt << endl;
:
27.11.2007 19:30:31
27.11.2007 19:30:32
, dt.Date::operator++(), 26 27 ,
dt.MyTime::operator++(), 31 32.
:
class B1 : public L { /* ... */ };
class B2 : public L { /* ... */ };
class D : public B1, public B2 { /* ... */ };
D L,
B2 B3. ; ! L, Employee,
B1, Manager, B2, Engineer, D, TechnManager -
.23-8.
C++ : B2::L B3::L.
: ; -
, . 23-8,
.
. 23-9. (virtual) :
class B1 : virtual public L { /* ... */ };
class B2 : virtual public L { /* ... */ };
class D : public B1, public B2 { /* ... */ };

Employee Employee Employee

Manager Engineer Manager Engineer

TechnManager TechnManager

. 23-8 TechnManager - . 23-9 virtual


Employee - TechnManager
. Employee .
878 23

23.19
19.1.3, -
public.
(interface part) .
Java16 :
. -
, Java Tutorials17
interface Bicycle
{
void changeCadence(int newValue);
void changeGear(int newValue);
void speedUp(int increment);
void applyBrakes(int decrement);
}
.
ACME :
class ACMEBicycle implements Bicycle
{
int cadence = 0;
int speed = 0;
int gear = 1;
// . . .
void speedUp(int increment)
{ speed = speed + increment; }
// . . .
}
C++
. :
class Bicycle
{
public:
virtual void changeCadence( int newValue ) = 0;
virtual void changeGear( int newValue ) = 0;
virtual void speedUp( int increment ) = 0;
virtual void applyBrakes( int decrement ) = 0;
};

class ACMEBicycle : public Bicycle


{
public:
ACMEBicycle()
{ cadence = 0; speed = 0; gear = 1; }

virtual void changeCadence( int newValue )


{ cadence = newValue; }

virtual void changeGear( int newValue )


{ gear = newValue; }

virtual void speedUp( int increment )


{ speed = speed + increment; }

virtual void applyBrakes( int decrement )


{ speed = speed - decrement; }

void printStates()
{ cout << "cadence:" << cadence << " speed:" << speed

16 C#.
17 http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
879

<< " gear:" << gear << endl; }


private:
int cadence;
int speed;
int gear;
}; // ACMEBicycle

23.20
B D :
class D : public B
{ // . . .
D B :
B
D ( ) :
D -
B.
/ -.
D - B.
,
.
.

.
virtual.
-
. -
get set.
( ) protected private.
,
. typeid
.

A
23-1 :
#include <iostream>
class A class C : public A
{ {
public: public:
A( char c = 'A' ) : x( c ) C( char c = 'C' ) : z( c )
{ cout << "A=" << x; } { cout << "C=" << z; }
~A() { cout << "~A"; } ~C()
A& operator=( const A& a ) { cout << "~C"; }
{ C& operator=( const C& c )
x = a.x; {
cout << "A=" << x; A::operator=(c);
} z = c.z;
private: cout << "C=" << z;
char x; }
}; // class A private:
880 23

char z;
class B : public A }; // class C
{
public: int main()
B( char c = 'B' ) : y( c ) {
{ cout << "B=" << y; } cout << "Prints";
~B() cout << endl << "1:";
{ cout << "~B"; } A* b = new B;
B& operator=( const B& b ) A* c = new C;
{ cout << endl << "2:";
A::operator=( b ); A bb = *b;
y = b.y; A cc = *c;
cout << "B=" << y; cout << endl << "3:";
} bb = cc;
private: } // main
char y;
}; // class B


23-2 :
class Order class Auto
{ {
public: public:
. . . . . .
private: private:
unsigned int orderNum; std::string manuf;
Good* goods; std::string model;
int gCount; char country[3];
std::string customer; Date purchDate;
Date oDate; std::string regNumber;
}; // Order }; // Auto
Date :
struct Good
{
unsigned int code;
std::string unit;
double quantity;
double price;
}; // Good
) (Order) : goods, gCount
, . struct Good,
, (code), (unit)
(quantity) . (price) . oDate
()
(orderNum).
) (Auto) : (manuf),
(model), (country, ),
(purchDate), (regNumber).18
, ,
( ) , /
.
.

18 ,
. ,
.
881


.
.
Auto
text ( cout).
Order print -
text ( cout). .
23-3 :
class Invoice
{
public:
. . .
private:
unsigned int invoiceNum;
unsigned int orderNum;
Good* goods;
int gCount;
std::string customer;
Date oDate;
Date iDate;
double total;
}; // Order
.
(invoiceNum).
( iDate).
, , (price).
, (total).
Order, Invoice print
text ( cout).
.
Invoice Order.
.
Order -
.
23-4 :
class A class B: public A
{ {
public: public:
. . . . . .
protected: private:
double* g; double r;
unsigned int nElmn; }; // B
std::string c;
}; // A
( nElmn g.)
,
) :
int main()
{
double q[3] = { 3.0, 1.5, -1.1 };
A a1;
// a1.nElmn==0 && a1.g==0 && c==
A a2( 3, q, an object );
// a2.nElmn==3 && a2.g[0]==3.0 && a2.g[1]==1.5 && a2.g[2]==-1.1 &&
// a2.c==an object
A a3( a2 );
// a3.nElmn==3 && a3.g[0]==3.0 && a3.g[1]==1.5 && a3.g[2]==-1.1 &&
882 23

// a3.c==an object

a3.setG( 1, 5.5 );
// a3.nElmn==3 && a3.g[0]==3.0 && a3.g[1]==5.5 && a3.g[2]==-1.1 &&
// a3.c==an object &&
// a2.g[1]==1.5 && q[1]==1.5

B b1( a3, 7.35 );


// b1.nElmn==3 && b1.g[0]==3.0 && b1.g[1]==5.5 && b1.g[2]==-1.1 &&
// b1.c==an object && b1.r==7.35
. . .
-
.
) , :
A* z[2] = { &a2, &b1 };
fstream tout( abc.dta, ios_base::out|ios_base::binary );
:
z[0]->write( tout );
z[1]->write( tout );
abc.dta, -
(binary), a2, b1 :
3, 3.0, 1.5, -1.1, an object, 3, 3.0, 5.5, -1.1, an object, 7.35
23-5 :
class LongBitMap
{
public:
typedef unsigned long int ULong;
LongBitMap() { mBm = new ULong[1]; mBm[0] = 0;
mNoOfBits = 0; mArrSize = 1; }
LongBitMap( LongBitMap& other );
~LongBitMap() { delete [] ULong; }
long getNoOfBits() const { return mNoOfBits; }
LongBitMap& operator=( LongBitMap& other );
LongBitMap& operator&=( LongBitMap& other );
LongBitMap& operator|=( LongBitMap& other );
LongBitMap& operator^=( LongBitMap& other );
void lSetBit( int pos );
void lClearBit( int pos );
ULong lCount1() const;
int lBitValue( int pos ) const;
private:
ULong* mBm; //
ULong mNoOfBits; // bits
ULong mArrSize; // ( ULong) mBm
}; // class LongBitMap
. ,
unsigned long int. mBm[0]
bits 0 31, mBm[1] bits 32 63, mBm[2] bits 64 95 ...
mNoOfBits bits . mArrSize
mBm.
.
:
.
and (operator&=). mNoOfBits other.mNoOfBits
bits 0 ().
xor (operator^=). mNoOfBits other.mNoOfBits
bits 0 ().
883

lSetBit. 1 bit pos. pos > mNoOfBits1 -


( renew) pos.
lBitValue. bit pos. pos > mNoOfBits1
.
-
.
884 23
project

6


:
Prj06.1 ............................................................................................................................................. 885
Prj06.2 .................................................................................................................................................. 887
Prj06.3 Course OfferedCourse .................................................................................................... 887
Prj06.3.1 Course OfferedCourse ..........................................................................................890
Prj06.3.2 ........................................................................................................................890
Prj06.4 CourseCollection ...................................................................................................................... 892
Prj06.5 Student EnrolledStudent ................................................................................................ 899
Prj06.6 StudentCollection ..................................................................................................................... 905
Prj06.7 StudentInCourse StudentInCourseCollection .................................................................................. 909
Prj06.8 1 ( ) ................................................................................................ 910
Prj06.9 2 ( ) ........................................................................................................ 912
Prj06.10 ........................................................................................................... 914

Prj06.1
Prj04.12 :
,
. ,
, .
:
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
//

unsigned int sIdNum; //
char sSemester[10]; //
unsigned int sWH; //
unsigned int sNoOfCourses; //
//
Course::CourseKey* sCourses;
,
:
CourseKey cCode; //
char cTitle[cTitleSz]; //

885
886 Project 06

unsigned int cFSem; //


bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
CourseKey cPrereq; //
:
unsigned int cNoOfStudents; // .
( ,
.)
Project 4
:

:
class Student
{
public:
// . . .
private:
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
}; // Student

class EnrolledStudent : public Student


{
public:
// . . .
private:
char esSemester[10]; //
unsigned int esWH; //
unsigned int esNoOfCourses; //
//
Course::CourseKey* esCourses;
}; // EnrolledStudent

class Course
{
public:
// . . .
private:
CourseKey cCode; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
CourseKey cPrereq; //
}; // Course

class OfferedCourse : public Course


{
public:
// . . .
private:
unsigned int ocNoOfStudents; // .
}; // OfferedCourse
887

a :
Course
OfferedCourse.
, -
EnrolledStudent -
Student.
:
; ! -
EnrolledStudent Student.
, OfferedCourse -
Course. -
!
EnrolledStudent OfferedCourse
Student Course ( sIdNum cCode .) -
23.14.
.

Prj06.2
Course OfferedCourse.
:

:
: struct Course ;
.
private; protected;
.
Student EnrolledStudent.
CourseCollection.
; :
() : Course -

OfferedCourse.
.
() , ccArr, Course* Course.
ccArr[k] () Course,
.

*ccArr[k] OfferedCourse.
. -
.
StudentCollection.

Prj06.3 Course OfferedCourse


OfferedCourse ocNoOfStudents. , -
clearStudents(), add1Student(), delete1Student() -
. Course ( -
OfferedCourse.)
888 Project 06

save(), load() display()


Course OfferedCourse. virtual Course
OfferedCourse.
, .
.
Course :

cNoOfStudents = 0;
:
virtual ~Course() { };
OfferedCourse.
23.3:
OfferedCourse::OfferedCourse( string aCode, string aTitle )
: Course( aCode, aTitle ), ocNoOfStudents( 0 ) { }
,
.
:
virtual ~OfferedCourse() { };
. Course :
virtual void save( ostream& bout ) const;
virtual void load( istream& bin );
virtual void display( ostream& tout ) const;
:
save(0 :
bout.write( reinterpret_cast<const char*>(&cNoOfStudents),
sizeof(cNoOfStudents) );
load() :
bin.read( reinterpret_cast<char*>(&tmp.cNoOfStudents),
sizeof(cNoOfStudents) ); // . .
display() : << '\t' << cNoOfStudents
OfferedCourse , virtual -
. :
void OfferedCourse::save( ostream& bout ) const
{
if ( bout.fail() )
throw CourseXptn( CourseKey(getCode()), "save",
CourseXptn::fileNotOpen );
this->Course::save( bout );
bout.write( reinterpret_cast<const char*>(&ocNoOfStudents),
sizeof(ocNoOfStudents) ); // . .
if ( bout.fail() )
throw CourseXptn( CourseKey(getCode()), "save",
CourseXptn::cannotWrite );
} // OfferedCourse::save
, this->Course::save(bout) -
Course ocNoOfStudents.
void OfferedCourse::load( istream& bin )
{
OfferedCourse tmp;
tmp.Course::load( bin );
if ( !bin.eof() )
{
bin.read( reinterpret_cast<char*>(&tmp.ocNoOfStudents),
sizeof(ocNoOfStudents) );// . .
889

if ( bin.fail() )
throw CourseXptn( CourseKey(getCode()), "load",
CourseXptn::cannotRead);
} // if ( !bin.eof() ). . .
*this = tmp;
} // OfferedCourse::load
, tmp.Course::load(bin)
Course tmp. tmp.ocNoOfStudents.
void OfferedCourse::display( ostream& tout ) const
{
this->Course::display( tout );
tout << ocNoOfStudents << endl;
if ( tout.fail() )
throw CourseXptn( CourseKey(getCode()), "display",
CourseXptn::cannotWrite );
} // OfferedCourse::display
:
CourseXptn

. OfferedCourseXptn.
cCode CourseKey(getCode()).
(private) . -
protected; .
ocNoOfStudents : o inline
void clearStudents() { ocNoOfStudents = 0; }
void add1Student() { ++ocNoOfStudents; }
:
void OfferedCourse::delete1Student()
{
if ( ocNoOfStudents <= 0 )
throw OfferedCourseXptn( CourseKey(getCode()),"delete1Student",
OfferedCourseXptn::noStudent );
--ocNoOfStudents;
} // OfferedCourse::delete1Student
, ,
(
.)
(23.7),
. :
struct OfferedCourseXptn : public CourseXptn
{
enum { noStudent=20 };
OfferedCourseXptn( const Course::CourseKey& obk, const char* mn, int ec,
const char* sv="" )
: CourseXptn( obk, mn, 0, sv ) { errorCode = ec; }
}; // OfferedCourseXptn
, ,
noStudent. =20; Of-
feredCourseXptn::noStudent 0 OfferedCourseXptn::keyLen
(!)

.
890 Project 06

Prj06.3.1.1 Course OfferedCourse


:

*ccArr[k] OfferedCourse. ;
:
OfferedCourse* pOneCourse( new OfferedCourse );
pOneCourse
*ccArr[ndx], ocNoOfStudents :
delete ccArr[ndx];
ccArr[ndx] = pOneCourse;
;
-
Course OfferedCourse 0 ocNoOfStu-
dents. :
OfferedCourse* pOneCourse( new OfferedCourse(*ccArr[ndx]) );
:
*pOneCourse = *ccArr[ndx];
-
. :
OfferedCourse( const Course& oneCourse );
, :
OfferedCourse::OfferedCourse( const Course& oneCourse )
: Course( oneCourse ), ocNoOfStudents( 0 ) { }
:
1. -
; ! Offered-
Course( const Course& oneCourse )
*pOneCourse = *ccArr[ndx].
2.
Course( const OfferedCourse& oneOfrdCourse );
;
() Course.

Prj06.3.1.2
Course :1
class Course
{
public:
enum { cCodeSz = 8 };
struct CourseKey
{
char s[cCodeSz];
explicit CourseKey( string aKey="" )
{ strncpy( s, aKey.c_str(), cCodeSz-1 );
s[cCodeSz-1] = '\0'; }
}; // CourseKey
explicit Course( string aCode="", string aTitle="" );
virtual ~Course() { };
// getters

1 SylCourse Project 2
( .)
891

const char* getCode() const { return cCode.s; }


const char* getTitle() const { return cTitle; }
unsigned int getFSem() const { return cFSem; }
bool getCompuls() const { return cCompuls; }
char getSector() const { return cSector; }
const char* geCateg() const { return cCateg; }
unsigned int getWH() const { return cWH; }
unsigned int getUnits() const { return cUnits; }
const char* getPrereq() const { return cPrereq.s; }
// setters
void setCode( string aCode );
void setTitle( string aTitle );
void setFSem( int aFSem );
void setCompuls( bool aCompuls ) { cCompuls = aCompuls; };
void setSector( char aSector );
void setCateg( string aCateg );
void setWH( int aWH );
void setUnits( int aUnits );
void setPrereq( const string& prCode );
// other
virtual void save( ostream& bout ) const;
virtual void load( istream& bin );
virtual void display( ostream& tout ) const;
private:
CourseKey cCode; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
CourseKey cPrereq; //
}; // Course

typedef Course* PCourse;


!= == CourseKey Course .
:
struct CourseXptn
{
enum { keyLen, rangeError, noSuchSector, noSuchCateg, autoRef,
fileNotOpen, cannotWrite, cannotRead };
Course::CourseKey objKey;
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
CourseXptn( const Course::CourseKey& obk, const char* mn,
int ec, const char* sv="" )
: objKey( obk ), errorCode( ec )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
CourseXptn( const Course::CourseKey& obk, const char* mn,
int ec, int iv )
: objKey( obk ), errorCode( ec ), errIntVal( iv )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // CourseXptn
:
noStudent.
:
class OfferedCourse : public Course
{
public:
explicit OfferedCourse( string aCode="", string aTitle="" );
892 Project 06

OfferedCourse( const Course& oneCourse );


virtual ~OfferedCourse() { };
// getters
unsigned int getNoOfStudents() const { return ocNoOfStudents; }
// setters
void clearStudents() { ocNoOfStudents = 0; }
void add1Student() { ++ocNoOfStudents; }
void delete1Student();
// other
virtual void save( ostream& bout ) const;
virtual void load( istream& bin );
virtual void display( ostream& tout ) const;
private:
unsigned int ocNoOfStudents; // .
}; // OfferedCourse

typedef OfferedCourse* POfferedCourse;



OfferedCourse: Course.
, -

Course
OfferedCourse ! ;
2 :
. !
:
struct OfferedCourseXptn : public CourseXptn
{
enum { noStudent=20 };
OfferedCourseXptn( const Course::CourseKey& obk, const char* mn, int ec,
const char* sv="" )
: CourseXptn( obk, mn, 0, sv ) { errorCode = ec; }
}; // OfferedCourseXptn

Prj06.4 CourseCollection
CourseCollection

Course* ccArr;
:
PCourse* ccArr;
, , --
findNdx(), .
linSearch() MyTmpltLib. linSearch()

. findNdx() StudentCollection.
;
findNdx()
linSearch().

.
linSearch() linSearchP
.

2 ...
893

( ) .
:
template< typename T >
int linSearchP( T** v[], int n,
int from, int upto, const T& x )
{
if ( v == 0 && n > 0 )
throw MyTmpltLibXptn( "linSearchP",
MyTmpltLibXptn::noArray );
int fv( -1 );
if ( v != 0 && (0 <= from && from <= upto && upto < n) )
{
T save( *v[upto+1] ); // *v[upto+1]
*v[upto+1] = x; //
int k( from );
while ( *v[k] != x ) ++k;
if ( k <= upto ) fv = k;
else fv = -1;
*v[upto+1] = save; //
// (from <= fv <= upto && v[fv] == x) ||
// (fv == -1 && (j:from..upto v[j] != x))
}
return fv;
} // linSearchP
, != *v[k].
: *v[upto+1]. -
*v[n] (
).
,
int CourseCollection::findNdx( const string& code ) const
{
int ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = -1;
else
ndx = linSearchP( ccArr, ccNOfCourses,
0, ccNOfCourses-1, Course(code) );
return ndx;
} // CourseCollection::findNdx
, , ,
.

:
CourseCollection::CourseCollection()
{
try
{
ccReserved = ccIncr;
ccArr = new PCourse[ ccReserved ];
ccNOfCourses = 0;
ccPAllEnrollments = 0; // NULL
ccArr[ccNOfCourses] = new Course;
for ( int k(ccNOfCourses+1); k < ccReserved; ++k )
ccArr[k] = 0;
}
catch( bad_alloc& )
{
throw CourseCollectionXptn( "CourseCollection",
CourseCollectionXptn::allocFailed);
}
} // CourseCollection::CourseCollection
894 Project 06

ccArr[ccNOfCourses] = new Course ( -


). H for
0.
:
CourseCollection::~CourseCollection()
{
for ( int k(0); k <= ccNOfCourses; ++k )
delete ccArr[k];
delete[] ccArr;
} // CourseCollection::~CourseCollection
(private) erase1-
Course() insert1Course().
void CourseCollection::erase1Course( int ndx )
{
delete ccArr[ndx];
ccArr[ndx] = ccArr[ccNOfCourses-1];
ccArr[ccNOfCourses-1] = ccArr[ccNOfCourses];
ccArr[ccNOfCourses] = 0;
--ccNOfCourses;
} // CourseCollection::erase1Course
ccArr[ndx] = ccArr[ccNOfCourses-1] :
*ccArr[ndx].
.
ccArr[ccNOfCourses-1] = ccArr[ccNOfCourses].
insert1Course() :
void CourseCollection::insert1Course( const Course& aCourse );
Course
OfferedCourse.
ccArr[ccNOfCourses] = new Course( aCourse );

ccArr[ccNOfCourses] = new OfferedCourse( aCourse );
;
(23.13.1).
: add1-
Course().
: :
void CourseCollection::insert1Course( const Course* pCourse )
-
pCourse. : -
. insert1Course() private -
(CourseCollection::) add1Course() (CourseCollection::)load().

add1Course().
.
void CourseCollection::insert1Course( Course* pCourse )
{
if ( ccReserved <= ccNOfCourses+1 )
{
try
{
renew( ccArr, ccNOfCourses+1, ccReserved+ccIncr );
ccArr[ccNOfCourses+1] = ccArr[ccNOfCourses]; //
for ( int k(ccNOfCourses+2); k < ccReserved+ccIncr; ++k )
ccArr[k] = 0;
895

ccReserved += ccIncr;
}
catch( ... )
{ throw CourseCollectionXptn( "insert1Course",
CourseCollectionXptn::allocFailed ); }
}
ccArr[ccNOfCourses+1] = ccArr[ccNOfCourses];
ccArr[ccNOfCourses] = pCourse;
++ccNOfCourses;
} // CourseCollection::insert1Course
:
(ccNOfCourses+1)
(ccArr[ccNOfCourses+1] = ccArr[ccNOfCourses]).
0.
(ccArr[ccNOfCourses] = pCourse).
( ) :
. (catch(...))
allocFailed!
(public) delete1Course() :
void CourseCollection::delete1Course( string code )
{
int ndx( findNdx(code) );
if ( ndx >= 0 ) //
{
*ccArr[ccNOfCourses] = Course();
ccArr[ccNOfCourses]->setPrereq( code ); //
int k(0);
while ( strcmp(ccArr[k]->getPrereq(), code.c_str()) != 0 )
++k;
if ( k < ccNOfCourses )
throw CourseCollectionXptn( "delete1Course",
CourseCollectionXptn::prereqRef,
code.c_str() );
OfferedCourse* pOneCourse( dynamic_cast<OfferedCourse*>(ccArr[ndx]) );
if ( pOneCourse != 0 )
{
int enrStdnt( pOneCourse->getNoOfStudents() );
if ( enrStdnt > 0 ) //
throw CourseCollectionXptn( "delete1Course",
CourseCollectionXptn::enrollRef,
code.c_str(), enrStdnt );
}
erase1Course( ndx );
}
} // CourseCollection::delete1Course
. -> :
*ccArr[ndx] OfferedCourse.
(pOneCourse == 0) erase1Course(ndx).
(pOneCourse != 0)
pOneCourse->getNoOfStudents() > 0
erase1Course(ndx) .
add1Course() :
void CourseCollection::add1Course( const Course& aCourse )
const Course* pCourse
; public
.
896 Project 06

, -
.
void CourseCollection::add1Course( const Course& aCourse )
{
if ( strlen(aCourse.getCode()) != Course::cCodeSz-1 )
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::entity );
int ndx( findNdx(aCourse.getCode()) );
if ( ndx < 0 ) //
{
if ( strcmp(aCourse.getPrereq(), "") != 0 ) //
{
int ndx( findNdx(aCourse.getPrereq()) );
if ( ndx < 0 ) //
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::prereqRef,
aCourse.getPrereq() );
}
//
try
{
try
{
const OfferedCourse&
oneCourse( dynamic_cast<const OfferedCourse&>(aCourse) );
insert1Course( new OfferedCourse(oneCourse) );
}
catch( bad_cast )
{ insert1Course( new Course(aCourse) ); }
}
catch( bad_alloc )
{ throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::allocFailed ); }
}
} // CourseCollection::add1Course
:

const OfferedCourse&
oneCourse( dynamic_cast<const OfferedCourse&>(aCourse) );
aCourse OfferedCourse
oneCourse. , Course, -
bad_cast. try/catch , ,
ifelse. -
.
, new try/catch
.
, clearStudents() -
OfferedCourse.

.
void CourseCollection::add1Student( string code )
{
int ndx( findNdx(code) );
if ( ndx < 0 )
throw CourseCollectionXptn( "add1Student",
CourseCollectionXptn::notFound,
code.c_str() );
OfferedCourse* pOneCourse( dynamic_cast<OfferedCourse*>(ccArr[ndx]) );
if ( pOneCourse == 0 )
{
try { pOneCourse = new OfferedCourse( *ccArr[ndx] ); }
897

catch( bad_alloc& )
{
throw CourseCollectionXptn( "add1Student",
CourseCollectionXptn::allocFailed,
code.c_str() );
}
delete ccArr[ndx];
ccArr[ndx] = pOneCourse;
}
pOneCourse->add1Student();
} // CourseCollection::add1Student
ccArr[ndx]->add1Student():
Course add1Student(). , -
, pOneCourse, ccArr[ndx].
*ccArr[ndx] Course .
Prj06.3.1. ,
pOneCourse->add1Student() pOneCourse -
( OfferedCourse) ccArr[ndx].
void CourseCollection::delete1Student( string code )
{
int ndx( findNdx(code) );
if ( ndx < 0 )
throw CourseCollectionXptn( "delete1Student",
CourseCollectionXptn::notFound,
code.c_str() );
OfferedCourse* pOneCourse( dynamic_cast<OfferedCourse*>(ccArr[ndx]) );
pOneCourse->delete1Student();
// . . .
if ( pOneCourse->getNoOfStudents() == 0 )
{
Course* tmp( new Course(*pOneCourse) );
delete pOneCourse;
ccArr[ndx] = tmp;
}
} // CourseCollection::delete1Student
;

ccArr[ndx] OfferedCourse Course.
;
. !
.
.

OfferedCourse ocNoOfStudents == 0 Course.

save() load(). --
: Course OfferedCourse.
; ! , ,
. :
struct CIndexEntry
{
Course::CourseKey cCode;
size_t loc;
short int inhLvl;
}; // IndexEntry
: () cCode loc
Course inhLvl 0 OfferedCourse 1.
898 Project 06


!=:
struct CIndexEntry
{
Course::CourseKey cCode;
size_t loc;
short int inhLvl;
explicit CIndexEntry( Course::CourseKey aCode=Course::CourseKey(""),
int aLoc=0, short int aInhL=0 )
: cCode( aCode ), loc( aLoc ), inhLvl( aInhL ) { }
}; // CIndexEntry

bool operator!=( const CIndexEntry& lhs, const CIndexEntry& rhs )


{ return ( lhs.cCode != rhs.cCode ); }

bool operator==( const CIndexEntry& lhs, const CIndexEntry& rhs )


{ return !(lhs != rhs); }
:
void CourseCollection::save( ofstream& bout, CIndexEntry* crsIndex ) const
{
if ( bout.fail() )
throw CourseCollectionXptn( "save",
CourseCollectionXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&ccNOfCourses),
sizeof(ccNOfCourses) );
for ( int k(0); k < ccNOfCourses; ++k )
{
crsIndex[k].cCode = Course::CourseKey(ccArr[k]->getCode());
crsIndex[k].loc = bout.tellp();
OfferedCourse* pOneCourse( dynamic_cast<OfferedCourse*>(ccArr[k]) );
if ( pOneCourse == 0 ) // Course
{ crsIndex[k].inhLvl = 0;
ccArr[k]->save( bout ); }
else // OfferedCourse
{ crsIndex[k].inhLvl = 1;
pOneCourse->save( bout ); }
}
if ( bout.fail() )
throw CourseCollectionXptn( "save",
CourseCollectionXptn::cannotWrite );
} // CourseCollection::save

save().
:
void CourseCollection::load( ifstream& bin, const CIndexEntry* crsIndex )
{
unsigned int n;
bin.read( reinterpret_cast<char*>(&n), sizeof(n) );
if ( !bin.eof() )
{
CourseCollection tmp;
try
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Course* pOneCourse;
if ( crsIndex[k].inhLvl == 0 ) // Course
pOneCourse = new Course;
else // OfferedCourse
pOneCourse = new OfferedCourse;
pOneCourse->load( bin );
tmp.insert1Course( pOneCourse );
}
}
899

catch( bad_alloc& )
{
throw CourseCollectionXptn( "load",
CourseCollectionXptn::allocFailed );
}
if ( bin.fail() )
throw CourseCollectionXptn( "load",
CourseCollectionXptn::cannotRead );
swap( tmp );
}
} // CourseCollection::load

Prj06.5 Student EnrolledStudent


Student ( EnrolledStudent) -
(sNoOfCourses, sCourses, sReserved) sWH
( ).
, , : getNoOf-
Courses(), getCourses(), clearCourses(), find1Course(), add1Course(), delete1Course(), findNdx(), insert-
1Course(), erase1Course() getWH().
, . :
Student::Student( int aIdNum )
{
if ( aIdNum < 0 )
throw StudentXptn( 0, "Student", StudentXptn::negIdNum, aIdNum );
sIdNum = aIdNum;
sSurname[0] = '\0';
sFirstname[0] = '\0';
}; // Student()
. ,
. ()
:
virtual ~Student() { };

:
virtual void swap( Student& rhs );
virtual void save( ostream& bout ) const;
virtual void load( istream& bin );
virtual void display( ostream& tout );
:
void Student::swap( Student& rhs )
{
std::swap( sIdNum, rhs.sIdNum );

char svs[sNameSz];
strcpy( svs, sSurname ); strcpy( sSurname, rhs.sSurname );
strcpy( rhs.sSurname, svs );

strcpy( svs, sFirstname );


strcpy( sFirstname, rhs.sFirstname );
strcpy( rhs.sFirstname, svs );
} // Student::swap

void Student::save( ostream& bout ) const


{
if ( bout.fail() )
throw StudentXptn( sIdNum, "save", StudentXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&sIdNum), sizeof(sIdNum) );
bout.write( sSurname, sizeof(sSurname) );
900 Project 06

bout.write( sFirstname, sizeof(sFirstname) );


if ( bout.fail() )
throw StudentXptn( sIdNum, "save", StudentXptn::cannotWrite );
} // Student::save

void Student::load( istream& bin )


{
Student tmp;
bin.read( reinterpret_cast<char*>(&tmp.sIdNum), sizeof(sIdNum) );
if ( !bin.eof() )
{
bin.read( tmp.sSurname, sizeof(sSurname) );
bin.read( tmp.sFirstname, sizeof(sFirstname) );
if ( bin.fail() )
throw StudentXptn( sIdNum, "load", StudentXptn::cannotRead );
swap( tmp );
}
} // Student::load

void Student::display( ostream& tout )


{
tout << sIdNum << '\t' << sSurname << '\t' << sFirstname << endl
} // Student::display
, () Student :
class Student
{
public:
// constructors, destructor
explicit Student( int aIdNum=0 );
virtual ~Student() { };
// getters
unsigned int getIdNum() const { return sIdNum; }
const char* getSurname() const { return sSurname; }
const char* getFirstname() const { return sFirstname; }
// setters
void setIdNum( int aIdNum );
void setSurname( string aSurname );
void setFirstname( string aFirstname );
// other methods
void readPartFromText( istream& tin );
virtual void swap( Student& rhs );
virtual void save( ostream& bout ) const;
virtual void load( istream& bin );
virtual void display( ostream& tout );
private:
enum { sNameSz = 20 };
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];

unsigned int countTabs( string aLine );


}; // Student

typedef Student* PStudent;


!= == .
:
struct StudentXptn
{
enum { negIdNum, incomplete, fileNotOpen, cannotRead, cannotWrite };
unsigned int objKey;
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
StudentXptn( int obk, const char* mn, int ec, const char* sv="" )
901

: objKey( obk ), errorCode( ec )


{ strncpy( funcName, mn, 99 ); funcName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
StudentXptn( int obk, const char* mn, int ec, int ev )
: objKey( obk ), errorCode( ec ), errIntVal( ev )
{ strncpy( funcName, mn, 99 ); funcName[99] = '\0'; }
}; // StudentXptn

EnrolledStudent. :
explicit EnrolledStudent( int aIdNum=0 );
:
EnrolledStudent::EnrolledStudent( int aIdNum )
: Student( aIdNum ), esWH( 0 )
{
try { esCourses = new Course::CourseKey[ esIncr ]; }
catch( bad_alloc )
{ throw StudentXptn( getIdNum(), "EnrolledStudent",
EnrolledStudentXptn::allocFailed ); }
esReserved = esIncr;
esNoOfCourses = 0;
} // EnrolledStudent::EnrolledStudent
, -
. :
EnrolledStudent( const EnrolledStudent& rhs );
:
EnrolledStudent::EnrolledStudent( const EnrolledStudent& rhs )
: Student( rhs ), esWH( rhs.esWH )
{
try { esCourses = new Course::CourseKey[ rhs.esReserved ]; }
catch( bad_alloc )
{ throw EnrolledStudentXptn( getIdNum(), "Student",
EnrolledStudentXptn::allocFailed ); }
esReserved = rhs.esReserved;
for ( int k(0); k < rhs.esNoOfCourses; ++k )
esCourses[k] = rhs.esCourses[k];
esNoOfCourses = rhs.esNoOfCourses;
}; // EnrolledStudent::EnrolledStudent
swap()
:
virtual void swap( EnrolledStudent& rhs );
:
void EnrolledStudent::swap( EnrolledStudent& rhs )
{
Student::swap( rhs );

std::swap( esWH, rhs.esWH );


std::swap( esNoOfCourses, rhs.esNoOfCourses );

Course::CourseKey* svck( esCourses );


esCourses = rhs.esCourses; rhs.esCourses = svck;

std::swap( esReserved, rhs.esReserved );


} // EnrolledStudent::swap
, swap() . , Student
::swap(rhs) this->Student:: swap(rhs) -
Student *this rhs.
:
EnrolledStudent& operator=( const EnrolledStudent& rhs );
902 Project 06

:
EnrolledStudent& EnrolledStudent::operator=( const EnrolledStudent& rhs )
{
if ( &rhs != this )
{
try { EnrolledStudent tmp( rhs );
swap( tmp ); }
catch( EnrolledStudentXptn& x )
{ strcpy( x.funcName, "operator=" );
throw; }
}
return *this;
}; // Student( const Student& rhs )
, :
// getters
unsigned int getWH() const { return esWH; }
unsigned int getNoOfCourses() const { return esNoOfCourses; }
const Course::CourseKey* getCourses() const { return esCourses; }
// setters
void clearCourses() { esNoOfCourses = 0; esWH = 0; }
:
bool find1Course( const string& code ) const
{ return ( findNdx(code) >= 0 ); }
void add1Course( const Course& oneCourse );
void delete1Course( const Course& oneCourse );
(public) add1Course() delete1Course() ()
. sWH esWH.
(private) findNdx(), insert1Course() erase1-
Course(): sIncr, sCourses, sNoOfCourses, sReserved esIncr, esCourses, esNoOfCourses,
esReserved . insert1Course()
: EnrolledStudentXptn StudentXptn.
void EnrolledStudent::insert1Course( const Course::CourseKey& aCode )
{
if ( esReserved <= esNoOfCourses+1 )
{
try { renew( esCourses, esNoOfCourses, esReserved+esIncr );
esReserved += esIncr; }
catch( MyTmpltLibXptn& )
{
throw EnrolledStudentXptn( getIdNum(), "insert1Course",
EnrolledStudentXptn::allocFailed );
}
}
esCourses[esNoOfCourses] = aCode;
++esNoOfCourses;
} // Student::insert1Course
, swap(), :
void EnrolledStudent::save( ostream& bout ) const
{
Student::save( bout );

bout.write( reinterpret_cast<const char*>(&esWH), sizeof(esWH) );


bout.write( reinterpret_cast<const char*>(&esNoOfCourses),
sizeof(esNoOfCourses) );
for ( int k(0); k < esNoOfCourses; ++k )
bout.write( esCourses[k].s, Course::cCodeSz );

if ( bout.fail() )
throw StudentXptn( getIdNum(), "save",
StudentXptn::cannotWrite );
} // EnrolledStudent::save
903

void EnrolledStudent::load( istream& bin )


{
EnrolledStudent tmp;

tmp.Student::load( bin );
if ( !bin.eof() )
{
bin.read( reinterpret_cast<char*>(&tmp.esNoOfCourses),
sizeof(esNoOfCourses) );
if ( tmp.esNoOfCourses >= tmp.esReserved )
{
delete[] tmp.esCourses;
try
{
tmp.esCourses = new Course::CourseKey[
((tmp.esNoOfCourses/esIncr)+1)*esIncr ];
tmp.esReserved = ((tmp.esNoOfCourses/esIncr)+1)*esIncr;
}
catch( bad_alloc )
{
throw EnrolledStudentXptn( tmp.getIdNum(), "load",
EnrolledStudentXptn::allocFailed );
}
}
for ( int k(0); k < tmp.esNoOfCourses; ++k )
bin.read( tmp.esCourses[k].s, Course::cCodeSz );
if ( bin.fail() )
throw StudentXptn( tmp.getIdNum(), "load", StudentXptn::cannotRead );
swap( tmp );
}
} // EnrolledStudent::load

void EnrolledStudent::display( ostream& tout )


{
Student::display( tout );
tout << esWH << '\n' << esNoOfCourses << endl;
for ( int k(0); k < esNoOfCourses; ++k )
tout << esCourses[k].s << endl;
} // EnrolledStudent::display
( Student::save(bout), tmp.Student:: load(bin),
Student::display(tout)) .
,
protected. sIdNum

getIdNum() inline,
!
, : -
,
EnrolledStudent
Student. :
enrllmnt.txt Student,
scArr[k] readPartFromText() *scArr[k]. -
.
. -
:
EnrolledStudent* pOneStudent;
// . . .
try { pOneStudent = new EnrolledStudent( *scArr[ndx] ); }
catch( bad_alloc& )
{ throw . . . }
904 Project 06

delete scArr[ndx];
scArr[ndx] = pOneStudent;
new EnrolledStudent(*scArr[k]) -
:
EnrolledStudent::EnrolledStudent( const Student& rhs )
: Student( rhs ), esWH( 0 )
{
try { esCourses = new Course::CourseKey[ esIncr ]; }
catch( bad_alloc )
{ throw EnrolledStudentXptn( getIdNum(), "EnrolledStudent",
EnrolledStudentXptn::allocFailed ); }
esReserved = esIncr;
esNoOfCourses = 0;
} // EnrolledStudent::EnrolledStudent
-
, OfferedCourse, Enrol-
ledStudent = Student
Student EnrolledStudent

EnrolledStudent = EnrolledStudent( Student )



class EnrolledStudent : public Student
{
public:
// constructors, destructor
explicit EnrolledStudent( int aIdNum=0 );
EnrolledStudent( const EnrolledStudent& rhs );
EnrolledStudent( const Student& rhs );
virtual ~EnrolledStudent() { delete[] esCourses; };
// copy assignement
EnrolledStudent& operator=( const EnrolledStudent& rhs );
// getters
unsigned int getWH() const { return esWH; }
unsigned int getNoOfCourses() const { return esNoOfCourses; }
const Course::CourseKey* getCourses() const
{ return esCourses; }
// setters
void clearCourses() { esNoOfCourses = 0; esWH = 0; }
// 1 Course methods
bool find1Course( const string& code ) const
{ return ( findNdx(code) >= 0 ); }
void add1Course( const Course& oneCourse );
void delete1Course( const Course& oneCourse );
// other methods
virtual void swap( EnrolledStudent& rhs );
virtual void save( ostream& bout ) const;
virtual void load( istream& bin );
virtual void display( ostream& tout );
private:
enum { esIncr = 3 };
unsigned int esWH;
unsigned int esNoOfCourses;
Course::CourseKey* esCourses;
unsigned int esReserved;

int findNdx( const string& code ) const;


void insert1Course( const Course::CourseKey& aCode );
void erase1Course( int ndx );
}; // EnrolledStudent

typedef EnrolledStudent* PEnrolledStudent;


905

!= == -
.
:
struct EnrolledStudentXptn : public StudentXptn
{
enum { allocFailed=20 };
unsigned int objKey;
char funcName[100];
int errorCode;
char errStrVal[100];
int errIntVal;
EnrolledStudentXptn( int obk, const char* mn, int ec, const char* sv="" )
: StudentXptn( obk, mn, 0, sv ) { errorCode = ec; }
EnrolledStudentXptn( int obk, const char* mn, int ec, int ev )
: StudentXptn( obk, mn, 0, ev ) { errorCode = ec; }
}; // EnrolledStudentXptn

Prj06.6 StudentCollection
StudentCollection

Student* scArr;
:
PStudent* scArr;
findNdx()
CourseCollection:
int StudentCollection::findNdx( int aIdNum ) const
{
int ndx;
if ( aIdNum <= 0 )
ndx = -1;
else
ndx = linSearchP( scArr, scNOfStudents, 0, scNOfStudents-1,
Student(aIdNum) );
return ndx;
} // StudentCollection::findNdx

CourseCollection:
StudentCollection::StudentCollection()
{
try
{
scReserved = scIncr;
scArr = new PStudent[ scReserved ];
scNOfStudents = 0;
scPAllEnrollments = 0;
scArr[scNOfStudents] = new Student;
for ( int k(scNOfStudents+1); k < scReserved; ++k )
scArr[k] = 0;
}
catch( bad_alloc& )
{
throw StudentCollectionXptn( "StudentCollection",
StudentCollectionXptn::allocFailed);
}
} // StudentCollection::StudentCollection

StudentCollection::~StudentCollection()
{
for ( int k(0); k <= scNOfStudents; ++k )
906 Project 06

delete scArr[k];
delete[] scArr;
} // StudentCollection::~StudentCollection
erase1Course() insert1Course() CourseCollection,
, erase1Student() insert1Student() :
void StudentCollection::erase1Student( int ndx )
{
delete scArr[ndx];
scArr[ndx] = scArr[scNOfStudents-1];
scArr[scNOfStudents-1] = scArr[scNOfStudents];
scArr[scNOfStudents] = 0;
--scNOfStudents;
} // StudentCollection::erase1Student

void StudentCollection::insert1Student( Student* pStudent )


{
if ( scReserved <= scNOfStudents+1 )
{
try
{
renew( scArr, scNOfStudents+1, scReserved+scIncr );
scArr[scNOfStudents+1] = scArr[scNOfStudents]; //
for ( int k(scNOfStudents+2); k < scReserved+scIncr; ++k )
scArr[k] = 0;
scReserved += scIncr;
}
catch( MyTmpltLibXptn& )
{ throw StudentCollectionXptn( "insert1Student",
StudentCollectionXptn::allocFailed ); }
}
scArr[scNOfStudents+1] = scArr[scNOfStudents];
scArr[scNOfStudents] = pStudent;
++scNOfStudents;
} // StudentCollection::insert1Student
CourseCollection::insert1Course
Student* pStudent
: add1Student() insert1Student().
void StudentCollection::add1Student( const Student& aStudent )
{
int ndx( findNdx(aStudent.getIdNum()) );
if ( ndx < 0 ) //
{
if ( scPAllEnrollments == 0 )
throw StudentCollectionXptn( "add1Student",
StudentCollectionXptn::noEnroll );
try
{
try
{
const EnrolledStudent&
oneStudent( dynamic_cast<const EnrolledStudent&>(aStudent) );
insert1Student( new EnrolledStudent(oneStudent) );
const Course::CourseKey* aStCourses( aStudent.getCourses() );
for ( int k(0); k < aStudent.getNoOfCourses(); ++k )
{
scPAllEnrollments->add1StudentInCourse(
StudentInCourse(aStudent.getIdNum(),
aStCourses[k].s) );
}
}
catch( bad_cast )
{ insert1Student( new Student(aStudent) ); }
}
catch( bad_alloc )
907

{ throw StudentCollectionXptn( "add1Student",


StudentCollectionXptn::allocFailed ); }
}
} // StudentCollection::add1Student
StudentCollection::delete1Student(),
CourseCollection::delete1Course():
Student
EnrolledStudent getNoOfCourses() == 0.
void StudentCollection::delete1Student( int aIdNum )
{
int ndx( findNdx(aIdNum) );
if ( ndx >= 0 ) //
{
EnrolledStudent* pOneStudent(
dynamic_cast<EnrolledStudent*>(scArr[ndx]) );
if ( pOneStudent != 0 ) // EnrolledStudent
{
if ( pOneStudent.getNoOfCourses() > 0 )
throw StudentCollectionXptn( "delete1Student",
StudentCollectionXptn::enrollRef,
aIdNum );
}
erase1Student( ndx );
}
} // StudentCollection::delete1Student
EnrolledStudent -
scArr[ndx]
pOneStudent.
StudentCollection::add1Course() StudentCollection
::delete1Course() CourseCollection::add1Student() CourseCollection::
delete1Student().
Prj06.5 EnrolledStudent
Student
add1Course():
void StudentCollection::add1Course( int aIdNum, const Course& aCourse )
{
int ndx( findNdx(aIdNum) );
if ( ndx < 0 )
throw StudentCollectionXptn( "add1Course",
StudentCollectionXptn::notFound, aIdNum );
EnrolledStudent* pOneStudent( dynamic_cast<EnrolledStudent*>(scArr[ndx]) );
if ( pOneStudent == 0 )
{
try { pOneStudent = new EnrolledStudent( *scArr[ndx] ); }
catch( bad_alloc& )
{
throw StudentCollectionXptn( "add1Course",
StudentCollectionXptn::allocFailed );
}
delete scArr[ndx];
scArr[ndx] = pOneStudent;
}
pOneStudent->add1Course( aCourse );
} // StudentCollection::add1Course
, CourseCollection::add1Student() -
.
Student
EnrolledStudent
.
908 Project 06

void StudentCollection::delete1Course( int aIdNum, const Course& aCourse )


{
int ndx( findNdx(aIdNum) );
if ( ndx < 0 )
throw StudentCollectionXptn( "delete1Course",
StudentCollectionXptn::notFound, aIdNum );
EnrolledStudent* pOneStudent( dynamic_cast<EnrolledStudent*>(scArr[ndx]) );
if ( pOneStudent != 0 )
{
pOneStudent->delete1Course( aCourse );
// . . .
if ( pOneStudent->getNoOfCourses() == 0 )
{
Student* tmp( new Student(*pOneStudent) );
delete pOneStudent;
scArr[ndx] = tmp;
}
}
} // StudentCollection::delete1Course
CourseCollection::delete1Student() -
. . .
CourseCollection::save() CourseCollection::load() -
StudentCollection::save() StudentCollection::load() , -
:
struct SIndexEntry
{
unsigned int sIdNum;
size_t loc;
short int inhLvl;
explicit SIndexEntry( int aIdNum=0, int aLoc=0, short int aInhL=0 )
: sIdNum( aIdNum ), loc( aLoc ), inhLvl( aInhL ) { }
}; // SIndexEntry

typedef SIndexEntry* PSIndexEntry;

bool operator!=( const SIndexEntry& lhs, const SIndexEntry& rhs )


{ return ( lhs.sIdNum != rhs.sIdNum ); }

bool operator==( const SIndexEntry& lhs, const SIndexEntry& rhs )


{ return !(lhs != rhs); }
SIndexEntry CIndexEntry .
void StudentCollection::save( ofstream& bout, SIndexEntry* stdntIndex ) const
{
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&scNOfStudents),
sizeof(scNOfStudents) );
for ( int k(0); k < scNOfStudents; ++k )
{
stdntIndex[k].sIdNum = scArr[k]->getIdNum();
stdntIndex[k].loc = bout.tellp();
EnrolledStudent*
pOneStudent( dynamic_cast<EnrolledStudent*>(scArr[k]) );
if ( pOneStudent == 0 ) // Student
{ stdntIndex[k].inhLvl = 0;
scArr[k]->save( bout ); }
else // EnrolledStudent
{ stdntIndex[k].inhLvl = 1;
pOneStudent->save( bout ); }
}
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::cannotWrite );
909

} // StudentCollection::save

void StudentCollection::load( ifstream& bin, const SIndexEntry* stdntIndex )


{
unsigned int n;
bin.read( reinterpret_cast<char*>(&n), sizeof(n) );
if ( !bin.eof() )
{
StudentCollection tmp;
try
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Student* pOneStudent;
if ( stdntIndex[k].inhLvl == 0 ) // Student
pOneStudent = new Student;
else // EnrolledStudent
pOneStudent = new EnrolledStudent;
pOneStudent->load( bin );
tmp.insert1Student( pOneStudent );
}
}
catch( bad_alloc& )
{
throw StudentCollectionXptn( "load",
StudentCollectionXptn::allocFailed );
}
if ( bin.fail() )
throw StudentCollectionXptn( "load",
StudentCollectionXptn::cannotRead );
swapArr( tmp );
}
} // StudentCollection::load
, checkWH() :
*scArr[k] EnrolledStudent.
void StudentCollection::checkWH( ostream& log, int maxWH ) const
{
if ( maxWH <= 0 )
throw StudentCollectionXptn( "checkWH",
StudentCollectionXptn::negWH, maxWH );
for ( int k(0); k < scNOfStudents; ++k )
{
EnrolledStudent*
pOneStudent( dynamic_cast<EnrolledStudent*>(scArr[k]) );
if ( pOneStudent != 0 )
{
if ( pOneStudent->getWH() > maxWH )
log << "student with id num " << pOneStudent->getIdNum()
<< ": " << pOneStudent->getWH() << " hours/week"
<< endl;
}
} // for
} // StudentCollection::checkWH

Prj06.7 StudentInCourse StudentInCourseCollection


StudentInCourse
OfferedCourse EnrolledStudent. . Prj06-1.
StudentInCourseCollection !
910 Project 06

Prj06.8 1 ( )
Project 4: readStudentData()
. , allStudents allCourses .
loadCourses() : one-
Course.clearStudents(); Course
clearStudents().
.
main() :
CIndexEntry* cIndex;
SIndexEntry* sIndex;
try
{ cIndex = new CIndexEntry[allCourses.getNOfCourses()]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
try
{ sIndex = new SIndexEntry[allStudents.getNOfStudents()]; }
catch( bad_alloc )
{ delete[] cIndex;
throw ProgXptn( "main", ProgXptn::allocFailed ); }
saveCollections()
saveCollections( allCourses, cIndex, allStudents, sIndex,
allEnrollments );
:
void saveCollections( CourseCollection& allCourses,
CIndexEntry* cIndex,
StudentCollection& allStudents,
SIndexEntry* sIndex,
StudentInCourseCollection& allEnrollments )
{
ofstream bout( "Courses.dta", ios_base::binary );
allCourses.save( bout, cIndex );
bout.close();
bout.open( "courses.ndx", ios_base::binary );
// bout.write( reinterpret_cast<const char*>(cIndex),
// allCourses.getNOfCourses()*sizeof(CIndexEntry) );
for ( int k(0); k < allCourses.getNOfCourses(); ++k )
bout.write( reinterpret_cast<const char*>(&cIndex[k]),
sizeof(CIndexEntry) );
bout.close();
bout.open( "students.dta", ios_base::binary );
allStudents.save( bout, sIndex );
bout.close();
bout.open( "students.ndx", ios_base::binary );
// bout.write( reinterpret_cast<const char*>(sIndex),
// allStudents.getNOfStudents()*sizeof(SIndexEntry) );
for ( int k(0); k < allStudents.getNOfStudents(); ++k )
bout.write( reinterpret_cast<const char*>(&sIndex[k]),

Student Course

StudentInCourse

0..* 0..*
EnrolledStudent StudentInCourse OfferedCourse
0..* 0..*
esCourses
. Prj06-1 StudentInCourse Enrolled-
Student ( ) OfferedCourse
( ).
Student Course .
911

sizeof(SIndexEntry) );
bout.close();
bout.open( "enrllmnt.dta", ios_base::binary );
allEnrollments.save( bout );
bout.close();
} // saveCollections
:
#include <string>
#include <fstream>
#include <new>
#include <iostream>

#include "MyTmpltLib.h"

using namespace std;

#include "Course.cpp"
#include "OfferedCourse.cpp"
#include "Student.cpp"
#include "EnrolledStudent.cpp"
#include "StudentInCourse.cpp"
#include "StudentInCourseCollection.h"
#include "CIndexEntry.h"
#include "CourseCollection.h"
#include "SIndexEntry.h"
#include "StudentCollection.h"
#include "CourseCollection.cpp"
#include "StudentCollection.cpp"
#include "StudentInCourseCollection.cpp"

struct ProgXptn
{
enum { allocFailed, cannotOpen };
char functionName[100];
int errorCode;
char errStrVal[100];
ProgXptn( const char* fn, int ec, const char* sv="" )
: errorCode( ec )
{ strncpy( functionName, fn, 99 ); functionName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // ProgXptn

void loadCourses( string flNm, CourseCollection& allCourses );


void readStudentData( string flNm,
StudentCollection& allStudents,
StudentInCourseCollection& allEnrollments,
CourseCollection& allCourses,
ofstream& log );
void saveCollections( CourseCollection& allCourses,
CIndexEntry* cIndex,
StudentCollection& allStudents,
SIndexEntry* sIndex,
StudentInCourseCollection& allEnrollments );

int main()
{
OfferedCourse oc;
try
{
CourseCollection allCourses;
StudentCollection allStudents;
StudentInCourseCollection allEnrollments;

allEnrollments.setPAllStudents( &allStudents );
allEnrollments.setPAllCourses( &allCourses );
912 Project 06

allCourses.setPAllEnrollments( &allEnrollments );
allStudents.setPAllEnrollments( &allEnrollments );

loadCourses( "gCourses.dta", allCourses );

ofstream log( "log.txt" );


if ( log.fail() )
throw ProgXptn( "main", ProgXptn::cannotOpen, "log.txt" );

readStudentData( "enrllmnt.txt", allStudents, allEnrollments,


allCourses, log );

unsigned int maxWH( 30 ); //


// : 30 /
allStudents.checkWH( log, maxWH );

log.close();

CIndexEntry* cIndex;
SIndexEntry* sIndex;
try
{ cIndex = new CIndexEntry[allCourses.getNOfCourses()]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
try
{ sIndex = new SIndexEntry[allStudents.getNOfStudents()]; }
catch( bad_alloc )
{ delete[] cIndex;
throw ProgXptn( "main", ProgXptn::allocFailed ); }

saveCollections( allCourses, cIndex, allStudents, sIndex,


allEnrollments );

delete[] sIndex;
delete[] cIndex;
} // try
catch( ProgXptn& x ) { /* . . . */ }
catch( MyTmpltLibXptn& x ) { /* . . . */ }
catch( OfferedCourseXptn& x ) { /* . . . */ }
catch( CourseXptn& x ) { /* . . . */ }
catch( EnrolledStudentXptn& x ) { /* . . . */ }
catch( StudentXptn& x ) { /* . . . */ }
catch( StudentInCourseXptn& x ) { /* . . . */ }
catch( CourseCollectionXptn& x ) { /* . . . */ }
catch( StudentCollectionXptn& x ) { /* . . . */ }
catch( StudentInCourseCollectionXptn& x ) { /* . . . */ }
catch( ... )
{ cout << "unexpected exceptioon" << endl; }
} // main

Prj06.9 2 ( )
, main(),
IndexEntry* index;

SIndexEntry* sIndex;
:
void loadIndex( string flNm,
PSIndexEntry& sIndex, unsigned int& ndxSz );
void retrieve( string flNm, PSIndexEntry sIndex, int ndxSz );
loadIndex()
retrieve():
913

void retrieve( string flNm, PSIndexEntry sIndex, int ndxSz )


{
ifstream bin( flNm.c_str(), ios_base::binary );
if ( bin.fail() )
throw ProgXptn( "retrieve", ProgXptn::cannotOpen,
flNm.c_str() );
string line;
cout << "Student Id Number: "; getline( cin, line, '\n' );
while ( line != "" )
{
int idNum( atoi(line.c_str()) );
int ndx( linSearch(sIndex, ndxSz, 0, ndxSz-1,
SIndexEntry(idNum)) );
if ( ndx < 0 )
cout << "unknown Student Id Number" << endl;
else // ndx >= 0
{
Student* pOneStudent;
try {
if ( sIndex[ndx].inhLvl == 0 )
pOneStudent = new Student;
else // == 1
pOneStudent = new EnrolledStudent;
}
catch( bad_alloc& )
{
bin.close();
throw ProgXptn( "retrieve", ProgXptn::allocFailed );
}
bin.seekg( sIndex[ndx].loc );
pOneStudent->load( bin );
pOneStudent->display( cout );
delete pOneStudent; pOneStudent = 0;
}
cout << "Student Id Number: "; getline( cin, line, '\n' );
} // while
bin.close();
} // retrieve

inhLvl:
linSearch() idNum sIndex ndx
.
sIndex[ndx].loc .
: load()
; sIndex[ndx].inhLvl 0
Student , 1, EnrolledStudent.
; ,
Student* pOneStudent Student
. , EnrolledStudent:
if ( sIndex[ndx].inhLvl == 0 )
pOneStudent = new Student;
else // == 1
pOneStudent = new EnrolledStudent;
:
pOneStudent->load( bin );
pOneStudent->display( cout );
Student ( EnrolledStu-
dent) :
virtual void load( istream& bin );
virtual void display( ostream& tout );
914 Project 06

, delete pOneStudent,

virtual ~Student() { };
( virtual ~EnrolledStudent() { delete[] esCourses; }.)
main() :
#include <fstream>
#include <iostream>
#include <new>

#include "MyTmpltLib.h"

using namespace std;

#include "Course.cpp"
#include "Student.cpp"
#include "EnrolledStudent.cpp"
#include "SIndexEntry.h"

struct ProgXptn
{
enum { allocFailed, cannotOpen };
char functionName[100];
int errorCode;
char errStrVal[100];
ProgXptn( const char* fn, int ec, const char* sv="" )
: errorCode( ec )
{ strncpy( functionName, fn, 99 ); functionName[99] = '\0';
strncpy( errStrVal, sv, 99 ); errStrVal[99] = '\0'; }
}; // ProgXptn

void loadIndex( string flNm,


PSIndexEntry& sIndex, unsigned int& ndxSz );
void retrieve( string flNm, PSIndexEntry sIndex, int ndxSz );

int main()
{
SIndexEntry* sIndex;
unsigned int ndxSz;
try
{
loadIndex( "students.ndx", sIndex, ndxSz );
retrieve( "students.dta", sIndex, ndxSz );
} // try
catch( ProgXptn& x ) { /* . . . */ }
catch( MyTmpltLibXptn& x ) { /* . . . */ }
catch( EnrolledStudentXptn& x ) { /* . . . */ }
catch( StudentXptn& x ) { /* . . . */ }
catch( ... )
{ cout << "unexpected exceptioon" << endl; }
} // main

Prj06.10
Enrol-
ledStudent OfferedCourse Student
Course ( sIdNum cCode .)
23.14.
, :
: Course OfferedCourse (Prj06.3) Student
EnrolledStudent (Prj06.5).
915

-
. OfferedCourse
(Prj06.3).
-

OfferedCourse( const Course& oneCourse ); // (Prj06.3)
EnrolledStudent( const Student& rhs ); // (Prj06.5)
, ,
OfferedCourse = Course
EnrolledStudent = Student
.

. ; :
PCourse* ccArr; // (Prj06.4)
PStudent* scArr; // (Prj06.6)

ccArr[k] scArr[k].
.3
-
-
.

3 .
916 Project 06

24
-
:
C++ ( C)
.
:
C++.
-
.
:
.
;
( ) -
( ).
(
C++ ).
.
:
assert()

exit()

try


:
24.1 C .................................................................................................................................. 919
24.1.1 assert() .........................................................................................................................................919
24.1.2 ..............................................................................................................920
24.1.2.1 std::exit() return ...................................................................................................... 921
24.1.3 ; errno .......................................................................................................................................922
24.2 ..................................................................................... 924
24.3 ...................................................................................... 927
24.4 ............................................................................................... 928
24.4.1 std::set_terminate() .................................................................................................928
24.4.2 std::terminate() ............................................................................................................930
24.4.3 * .................................................................................933
24.4.4 * std::uncaught_exception() .................................................................................934
24.5 try .......................................................................................................................... 935
24.6 C++ ................................................................................................................. 936
24.6.1 logic_error .....................................................................................................938

917
918 24

24.6.1.1 domain_error............................................................................................................................... 938


24.6.1.2 invalid_argument ........................................................................................................................ 939
24.6.1.3 length_error................................................................................................................................. 940
24.6.1.4 out_of_range ............................................................................................................................... 940
24.6.2 runtime_error ................................................................................................941
24.6.2.1 range_error.................................................................................................................................. 941
24.6.2.2 overflow_error underflow_error ...................................................................................... 941
24.6.3 ; ...........................................................................................................943
24.7 ............................................................................... 943
24.8 ........................................................................................................... 944
24.8.1 ........................................................................................................945
24.9 ........................................................................................................... 948
24.10 ....................................................................................................................................................... 949

:
-
. -
:

,
,
(-
),
.
, -
. 4.3, , :
cout << " m: "; cin >> h;

assert( h >= 0 );

// (g == 9.81) && (0 h DBL_MAX)


// tP, vP
- assert() false,
.
. 1 5.5 :
cout << " m: "; cin >> h;
if ( h >= 0 )
{ // (g == 9.81) && (0 h DBL_MAX)
//
}
else
// false
cout << " " << endl;
h ( h < 0)
.
, 7.7
// factorial -- a!
unsigned long int factorial( int a )
{
if ( a < 0 )
{
cout << " factorial " << a << endl;
exit( EXIT_FAILURE );
}
unsigned long int fv( 1 );
for ( int k(1); k <= a; ++k ) fv *= k;
return fv;
} // factorial
- 919

( .)
, factorial() (-
), .
:
( )
exit().

:
, . , -
(2.7 3.8)
h 0 2h / g .
. ;
-
.
.
, -
,
.
C++
. ,
C, -
.
:
C
.

24.1 C
C assert() -
. 1
exit() .

24.1.1 assert()
() assert() :
void assert( bool test )
, true . false

abort().

#include <cassert>.

1 C ( ISO/IEC TR 24731-1-2007) -
(constraints) -
. assert() .
920 24

24.1.2
exit(): 7.7 (. 1)
. :
void exit( int status )
#include <cstdlib>.
:
atexit(),
.
.
,
.
, .
status 0 EXIT_SUCCESS
(successful termination). status 1 EXIT_FAILURE
(unsuccessful termination).2
abort(): assert()
abort(). abort() - -
. :
void abort( )
#include <cstdlib>.
-
. -
.
_Exit(): ( cstdlib) ():
void _Exit( int status );

exit(). abort().
atexit(): exit()
atexit().
atexit() ( cstdlib) ():
int atexit( void (*func)() );
, atexit() void
( void f()).
0
- . C++ -
32 .
:
#include <iostream>
#include <cstdlib>
using namespace std;

void bye()
{ cout << "Bye bye!" << endl; }

void thatsAll()
{ cout << "That is all!!" << endl; }

2 cstdlib :
#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1
- 921

int main()
{
if ( atexit(&bye) != 0 )
cout << "bye registration failed" << endl;
if ( atexit(&thatsAll) != 0 )
cout << "thatsAll registration failed" << endl;

exit(0);
}
:
That is all!!
Bye bye!
:
1. bye() thatsAll()
thatsAll() bye().
2. 14.3, & :
if ( atexit(bye) != 0 ) . . .
if ( atexit(thatsAll) != 0 ) . . .
! using namespace std
std:: .

24.1.2.1 std::exit() return


exit() return main;
return n
main
exit( n ).
exit( n ) ,
.
:
#include <iostream>
#include <cstdlib>
using namespace std;

struct B
{
B( int k ) : bM( k ) { };
~B()
{ cout << "destruction of a B object: " << bM << endl; }
private:
int bM;
}; //

B b1( 3 );

int main()
{
B b2( 7 );

return 0;
}
:
destruction of a B object: 7
destruction of a B object: 3
return 0 exit( 0 ) :
destruction of a B object: 3
922 24

b1
b2 .3
,
! -
; :
( 16.14)
!

24.1.3 ; errno
C (..:
) -
errno. :
#include <iostream>
#include <cmath>
#include <cerrno>
#include <string>
using namespace std;
int main()
{
const double g( 9.81 ); // m/sec2,
double h, // m,
tP, // sec,
vP; // m/sec,

// h
cout << " m: "; cin >> h;
// tP
errno = 0;
tP = sqrt( (2/g)*h );
if ( errno != EDOM )
{ // (g == 9.81) && (0 h DBL_MAX) && (tP (2h/g))
vP = -g*tP;
// (tP (2h/g)) && (vP -(2hg))
// tP, vP
cout << " = " << h << " m" << endl;
cout << " = " << tP << " sec" << endl;
cout << " = "
<< vP << " m/sec" << endl;
}
else // errno == EDOM
cout << strerror( errno )
<< ": " << endl;
}
:
m: 80
= 80 m
= 4.03855 sec
= -39.6182 m/sec
m: -10
Domain error:
errno;
4
int errno;

3 , static B b2( 7 ) .
4 C -
-l.
- 923

errno 0. -
errno .
, math,
errno EDOM ( cerrno).
( -
) errno ERANGE.
; errno 0
h tP=sqrt((2/g)*h). errno
errno != EDOM. -
,
!
strerror() errno .
EDOM Domain error.
,
13.8.
double d;
char* p;

errno = 0;
d = strtod( "7.1e+318", &p );
if ( (d == HUGE_VAL) && errno == ERANGE )
cout << "TRUE" << endl;
errno = 0;
d = strtod( "-7.1e+318", &p );
if ( (d == -HUGE_VAL) && errno == ERANGE )
cout << "TRUE" << endl;
:
TRUE
TRUE
, 7.110+318 double
HUGE_VAL errno ERANGE.
C99 : ,
HUGE_VAL ERANGE errno.
13.8
(d == HUGE_VAL || d == -HUGE_VAL) && errno == ERANGE
, o C
( HUGE_VAL),
( INT_MAX).
errno.
, errno :
errno = 0.
errno.
:

. : sqrt()
.5
errno. ,
strtod() C99 : (underflow),

5 NaN.
924 24

errno ERANGE
.6
,
.
;
errno.
C99
C .

24.2
C -
.

.
, exit() abort() -
.
sqrt() -
exit() abort() . -
if


.

, out errno.
, ,

. , :
bisection(), 14.3,
, errCode.
.
|f(x)| < nMax ( |b a|/2 <
). -
, nMax, -
. bisection()
: nMax |f(x)| < ; ;
.
13-10 , trinomial(),
.
, :
7 = 0 (: 1) 0 = 0 (: INT_MAX)
.
0 1 2 . , -
-
-
. ,
.

6 gcc (Dev-C++) ERANGE errno.


- 925

:
.
C:
errno ( myErrNo.)
,
.

.
- 14.9.1
:
comb(), factorial() natProduct()
,
.
, -
.7
natProduct(). :
0<mn
.

, (
) void,
// natProduct -- m*(m+1)*...*(n-1)*n
void natProduct( int m, int n,
unsigned long int& fv, int& err )
{
if ( m <= 0 || n < m )
err = 1;
else // 0 < m <= n
{
fv = m;
for ( int k = m+1; k <= n; ++k ) fv *= k;
err = 0;
}
} // natProduct
:
long int natProduct( int m, int n )
{
long int fv;

if ( m <= 0 || n < m )
fv = -1;
else // 0 < m <= n
{
fv = m;
for ( int k = m+1; k <= n; ++k ) fv *= k;
}
return fv;
} // natProduct
factorial(); :
void factorial( int a,
unsigned long int& fv, int& err )
{
if ( a == 0 ) { fv = 1; err = 0; }

7
main .
926 24

else natProduct( 1, a, fv, err );


} // factorial
:
long int factorial( int a )
{
return ( (a == 0) ? 1 : natProduct(1, a) );
} // factorial
long int -
-1 .
comb():
// comb -- m n
void comb( int m, int n,
unsigned long int& fv, int& err )
{
unsigned long int v1, v2;

if ( n < m-n )
{
factorial( n, v1, err );
if ( err == 0 )
{
natProduct( m-n+1, m, v2, err );
if ( err == 0 ) fv = v2/v1;
}
}
else
{
factorial( m-n, v1, err );
if ( err == 0 )
{
natProduct( n+1, m, v2, err );
if ( err == 0 ) fv = v2/v1;
}
}
} // comb
! !
-
-1 ( !)
main :
int main()
{
int m, n;
unsigned long int s;
int err;

cout << " m, n <= 50, m >= n: ";


cin >> m >> n;
comb( m, n, s, err );
if ( err == 0 )
cout << " "
<< m << " " << n << " = " << s << endl;
else
cout << " " << endl;
} // main
,
.

14.9.1:
- 927

1. .
( )
.
2. .
, -- err.
3. .
comb().
-
C++ ( ):
.

.
.

24.3

14.9.1. Java Tutorial:8
.
(exception) -
.
-
, (throw) (raise) :
"throw", ;
..:
throw -1; throw n; throw x;
.
:


.
v() 14.9 throw x;.
; 14.9.1,
v() v().
x; , (
catch )!
: throw
catch
( throw;). catch
.
, -1 natProd-
uct(), , StudentXptn(Student, StudentXptn::no-
Memory), (
).
,
:

8 http://docs.oracle.com/javase/tutorial/essential/exceptions/definition.html
928 24


.
, ,
. -
-

(std::)uncaught_exception().

(std::)terminate() ( (std::)abort()) -
. C++ (std::)set_terminate() -
terminate() .
:
unsigned long int natProduct( int m, int n ) throw( char* )
{
if ( m <= 0 || n < m )
{
throw -1;
}
// . . .
} // natProduct
throw -1.
(std::)
unexpected(), terminate().
terminate(), C++
(std::)set_unexpected() (std::)unexpected() .

24.4
C++9 . -
: ,
.
,
.

24.4.1 std::set_terminate()
: (std::)terminate() (
(std::)abort()) . C++
(std::)set_terminate() terminate()
.
terminate(), , :
void terminate()
{
terminate_handler pDth( &dth );
// . . .
(*pDth)();
}

void dth()
{
// . . .

9 C++03. C++11
- 929

abort();
}

typedef void (*terminate_handler)();


, terminate_handler void
( atexit()).
, terminate() abort() , dth().
set_terminate() terminate()
pDth.
#include <exception>. exception
:
terminate_handler set_terminate(terminate_handler f) throw();
:
void myTerminateHandler()
{
logFl << ", ," << endl
<< ", ." << endl;
abort();
} // myTerminateHandler
:
terminate_handler oldTH;
oldTH = set_terminate( &myTerminateHandler );
;
pDth terminate() &myTerminateHandler,
.
oldTH pDth,
.
set_terminate().10
(
) :
set_terminate( &myTerminateHandler );
:
#include <fstream>
#include <exception>
#include <cstdlib>

using namespace std;

ofstream logFl( "log.txt" );

void myTerminateHandler()
//

int main()
{
set_terminate( &myTerminateHandler );
throw -1;
}
; -
-
, logFl, ( ) .

10 : set_terminate() -
(pDth) terminate()
930 24

-
:

return , -
abort().
abort() .

24.4.2 std::terminate()
: ,
(std::)terminate() ( (std::)abort())
. set_terminate():
main throw -1 catch
.
terminate() .

#include <exception>:
#include <iostream>
#include <exception>
#include <cstdlib>

using namespace std;

void myTerminateHandler()
{
cout << ", ," << endl
<< ", ." << endl;
abort();
} // myTerminateHandler

int main()
{
set_terminate( &myTerminateHandler );
terminate();
}
:11
, ,
, .

Abnormal program termination


exception :
void terminate();
terminate()
.
(
catch ). std::terminate() :12
,
catch,
. :
struct Xptn
{

11 Borland C++ v.5.5.


12
- 931

int c;
Xptn( int ac=0 ) { c = ac; }
Xptn( const Xptn& rhs ) { throw -1; }
}; // Xptn

int main()
{
Xptn x;
set_terminate( &myTerminateHandler );
try {
throw x;
}
catch( Xptn& )
{ cout << "in catch( Xptn& )" << endl; }
catch( int& )
{ cout << "in catch( int& )" << endl; }
}
:13
, ,
, .

This application has requested the Runtime to terminate it in an unusual way.


throw x . -
24.3 .
(throw -1) terminate().
, main
catch. Xptn
myTerminateHandler() :
void f1()
{ throw Xptn(-1); }

void f2()
{ f1(); }

int main()
{
set_terminate( &myTerminateHandler );
try {
f2();
}
catch( int& )
{ cout << "in catch( int& )" << endl; }
}

. ; main f2() f1()
Xptn(-1). f2()
main. catch(int&)
catch(Xptn&) catch(...) terminate().

. :
struct C
{
int ic;
C( int ac=0 ) { ic = ac; }
~C() { throw 0; }
};

13 gcc.
932 24

void f()
{ C lc( 7 );
throw -1; }

int main()
{
set_terminate( &myTerminateHandler );
try {
f();
}
catch( int& )
{ cout << "int exception" << endl; }
}
throw -1 C
lc. terminate()
.
-
. :
struct C
{
int ic;
C( int ac=0 ) { ic = ac; throw -1; }
};

C gc;
gc . throw -1
terminate().14 :
void f()
{
static C c( 7 );
}

int main()
{
set_terminate( &myTerminateHandler );
f();
}
, c, terminate()
.
atexit()
. bye() 24.1.2:
void bye()
{ cout << "Bye bye!" << endl;
throw -1; }

int main()
{
set_terminate( &myTerminateHandler );
if ( atexit(&bye) != 0 )
cout << "bye registration failed" << endl;
exit( 0 );
}
:
Bye bye!

14 main set_terminate( &myTer-


minateHandler ).
- 933

, ,
, .

Abnormal program termination


throw; ( -
) , ..:
int main()
{
set_terminate( &myTerminateHandler );
throw;
}
unexpected(), .

:
.
throw -
. , .
,
.
:

.

24.4.3 *
(std::)unexpected() -
.
(std::)set_unexpected() unexpected().

.
C++11 throw() (
). :
throw() -
unexpected() set_unexpected().

(std::)bad_exception.
:
#include <iostream>
#include <exception>
#include <cstdlib>

using namespace std;

void myTerminateHandler()
{
cout << ", ," << endl
<< ", ." << endl;
abort();
} // myTerminateHandler

unsigned long int natProduct( int m, int n ) throw( char* )


{
throw -1;
} // natProduct
934 24

int main()
{
set_terminate( &myTerminateHandler );
try {
cout << natProduct( 3, 1 ) << endl;
}
catch( char* )
{ cout << "catching char*" << endl; }
catch( int& )
{ cout << "catching int" << endl; }
}
:
, ,
, .

This application has requested the Runtime to terminate it in an unusual way.


; natProduct() -1 (int)
. unexpected() terminate().
:
:
void myUnexpected()
{
cout << "unexpected; \' ..." << endl;
throw;
}
natProduct():
unsigned long int natProduct( int m, int n ) throw( char*, bad_exception )
{
throw -1;
} // natProduct
, main:
int main()
{
set_terminate( &myTerminateHandler );
set_unexpected( &myUnexpected ); // <<<<<<<<<<<<<<
try {
cout << natProduct( 3, 1 ) << endl;
}
catch( char* )
{ cout << "catching char*" << endl; }
catch( int& )
{ cout << "catching int" << endl; }
catch( bad_exception& ) // <<<<<<<<<<<<<<
{ cout << "catching bad_exception" << endl; }
}
:
unexpected; ' ...
catching bad_exception
(std::)bad_exception
myUnexpected(), terminate()!

24.4.4 * std::uncaught_exception()
, exception, :
bool uncaught_exception() throw();
true , ,
.
- 935

. myUnexpected()
: , -
, , throw; (-
) terminate(). myUnexpected() :
void myUnexpected()
{
cout << "unexpected; \' ..." << endl;
if ( uncaught_exception() )
throw;
}
; -
true
, .
;
. ;
! (
). ; :
if ( uncaught_exception() )
{ E1 }
else
{ E2 }
: E1
E2 ( ).

.

24.5 try
23.3 DateTime :
DateTime::DateTime( int yp, int mp, int dp,
int hp, int minp, int sp )
: Date( yp, mp, dp )
{
// . . .
}; // DateTime::DateTime
Date
Date : -
Date DateTime.
; DateXptn
Date DateTimeXptn.
:
DateTime::DateTime( int yp, int mp, int dp, int hp, int minp, int sp )
try : Date( yp, mp, dp )
{
if ( hp < 0 || 23 < hp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::hourRange, hp );
if ( minp < 0 || 59 < minp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::minRange, minp );
if ( sp < 0 || 59 < sp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::secRange, sp );
dtHour = hp; dtMin = minp; dtSec = sp;
}
catch( DateTimeXptn& x )
936 24

{ throw; }
catch( DateXptn& x )
{
throw DateTimeXptn( "DateTime", x.errorCode,
x.errVal1, x.errVal2, x.errVal3 );
} // DateTime::DateTime
;
try -
try (functional try-block). catch
.
try, {.
catch
(throw;).
catch

DateTimeXptn.
catch throw. ; !
try catch
throw.
throw;.
, :
( -
). !
try -
. -
, try
!
try
main.
: throw catch.

void f( . . . )
{
void f( . . . )
try
try {
{
// . . .
// . . .
}
}
catch( . . . )
catch( . . . )
{
{
// . . .
// . . .
}
}
}

24.6 C++
C++
. ,
, exception, :
class exception
{
public:
exception() throw();
exception( const exception& ) throw();
exception& operator=( const exception& ) throw();
- 937

exception

bad_alloc bad_exception logic_error runtime_error

bad_cast bad_typeid ios_base::failure

. 24-1 exception -
. logic_error runtime_error -
.

virtual ~exception() throw();


virtual const char* what() const throw();
};
, :
,
,
,
(virtual)
(virtual), what(), .
throw(): ! 16.6.1
, , char funcName[100]
string funcName
.
: , []
std::terminate()
throw.
what(); -.
Borland C++ v.5.5 :
no named exception thrown
-
.15 exception .
. 24-1.
(std::)bad_alloc. :
class bad_alloc : public exception
{
public:
bad_alloc() throw();
bad_alloc( const bad_alloc& ) throw();
bad_alloc& operator=( const bad_alloc& ) throw();
virtual bad_alloc() throw();
virtual const char* what() const throw();
};
, . , what()
(BC++ v.5.5):
bad alloc exception thrown
C++ new.
, ios_base::
failure.

15 exception C++ .
938 24

(std::)bad_cast 23.13.1 Prj06.4.


typeinfo.
24.4.3 (std::) bad_exception. exception.
(std::)bad_typeid typeid ( )
0. #include <typeinfo>. -
, :
Student* p( 0 );
try {
cout << typeid(*p).name() << endl;
// . . .
}
catch ( bad_typeid& x )
{
cout << "bad_typeid caught" << endl;
cout << x.what() << endl;
}
(g++):
bad_typeid caught
St10bad_typeid
(std::)ios_base::failure
.16 -
:
explicit failure( const string& msg );
( msg) what().

24.6.1 logic_error
logic_error stdexcept:
class logic_error : public exception
{
public:
explicit logic_error( const string& what_arg );
};
,
ios_base::failure.
, logic_error -

,
.

24.6.1.1 domain_error
:
class domain_error : public logic_error
{
public:
explicit domain_error( const string& what_arg );
};

(domain of definition) . factorial()
:

16 C++11 system_error , ,
runtime_error.
- 939

logic_error runtime_error

domain_error length_error range_error underflow_error

invalid_argument out_of_range overflow_error

. 24-2 logic_error - . 24-3 runtime_error


. .

unsigned long int factorial( int a )


{
if ( a < 0 )
{
ostringstream ssout;
ssout << " factorial " << a;
throw domain_error( ssout.str() );
}
unsigned long int fv( 1 );
for ( int k(1); k <= a; ++k ) fv *= k;
return fv;
} // factorial
-
ostringstream (10.12).
:
#include <iostream>
#include <stdexcept> // domain_error
#include <sstream> // ostringstream

using namespace std;

unsigned long int factorial( int a )


//

int main ()
{
try
{
cout << factorial( 7 ) << endl;
cout << factorial( -7 ) << endl;
}
catch ( domain_error& x )
{
cout << "domain error: " << x.what() << endl;
}
}
:
5040
domain error: factorial -7

24.6.1.2 invalid_argument
stdexcept :
class invalid_argument : public logic_error
{
public:
explicit invalid_argument( const string& what_arg );
};
940 24


domain_error. in-
valid_argument.

24.6.1.3 length_error
stdexcept :
class length_error : public logic_error
{
public:
explicit length_error( const string& what_arg );
};
size_error. (,
) (
). , :
string s1;
:
try {
s1.reserve( s1.max_size()+1 );
}
catch( exception& x )
{
cout << typeid( x ).name() << endl
<< x.what() << endl;
}
(BC++ v.5.5):17
std::length_error
invalid string size parameter in function: basic_string::reserve(size_t)
size: -14 is greater than maximum size: -15

24.6.1.4 out_of_range
stdexcept :
class out_of_range : public logic_error
{
public:
explicit out_of_range( const string& what_arg );
};
:
s1( "test text" );
:
try {
cout << s1.at(17) << endl;
}
catch( exception& x )
{
cout << typeid( x ).name() << endl
<< x.what() << endl;
}
(BC++ v.5.5):
std::out_of_range
position beyond end of string in function: basic_string::at(size_t)
index: 17 is greater than max_index: 9
, , -
domain_error.

17 -14 -15; ; . 17!


- 941

24.6.2 runtime_error
runtime_error stdexcept:
class runtime_error : public exception
{
public:
explicit runtime_error( const string& what_arg );
};
, exception
logic_error.
logic_error; logic_error ( )
(-) (-) (-)
(-). runtime_error ,
.

24.6.2.1 range_error
range_error runtime_error:
class range_error : public runtime_error
{
public:
explicit range_error( const string& what_arg );
};
.
-
. ,
f R,
f: D R
fC float double
long double:
fC: DC float ( double long double) (C)
R
, . (C) -
.
addInt() 17.3
.
Z :
. int -
int. range_error
IntOvrflXptn.

24.6.2.2 overflow_error underflow_error


addInt() overflow_error
runtime_error:18
class overflow_error : public runtime_error
{
public:
explicit overflow_error( const string& what_arg );
};
-
17.9 , -

18 , range error
.
942 24

0 () . , -
!19
class underflow_error : public runtime_error
{
public:
explicit underflow_error( const string& what_arg );
};
.
multDbl()
addInt() double
:
double multDbl( double x, double y )
{
double fv;

if ( fabs(x) >= 1 )
{
if ( fabs(y) < 1 ) fv = x * y;
else if ( fabs(y) <= DBL_MAX / fabs(x) ) fv = x * y;
else
{
ostringstream ssout;
ssout << " multDbl "
<< x << ", " << y;
throw overflow_error( ssout.str() );
}
}
else // |x| < 1
{
if ( fabs(y) >= 1 ) fv = x * y;
else if ( fabs(x) >= DBL_MIN / fabs(y) ) fv = x * y;
else
{
ostringstream ssout;
ssout << " multDbl "
<< x << ", " << y;
throw underflow_error( ssout.str() );
}
}
return fv;
} // multDbl
:
try
{
cout << multDbl( DBL_MAX, DBL_MAX ) << endl;
}
catch( exception& x )
{
cout << typeid(x).name() << endl << x.what() << endl;
}
(g++, Dev-C++):
St14overflow_error
multDbl 1.79769e+308, 1.79769e+308
:20
cout << multDbl( DBL_MIN, DBL_MIN ) << endl;

19 17.15
!
20 cout << DBL_MIN*DBL_MIN << endl 0.
- 943

(g++, Dev-C++):
St15underflow_error
multDbl 2.22507e-308, 2.22507e-308

24.6.3 ;
, C++
:
, exception.
.
-
what().

.

24.7
Boost
(Abrahams 2010). -
. :
std::exception.
:
catch(exception& x) typeid(x).name() -
. , -
std::exception catch(exception& x)
catch(...).

.
, ,
;!
virtual!
std::string
.
24.4.2.
what() () .
.
what().
, -

.
(public)
. what()
() .
.
, ,
944 24

. ,
, delete 0 .21

24.8
-
C++:
. : D
B D
B.
.
.
;
std::exception.
! , Project 6 :
struct CourseXptn : public exception { /* . . . */ };
struct CourseCollectionXptn : public exception { /* . . . */ };
struct StudentXptn : public exception { /* . . . */ };
struct StudentCollectionXptn : public exception { /* . . . */ };
struct StudentInCourseXptn : public exception { /* . . . */ };
struct StudentInCourseCollectionXptn : public exception { /* . . . */ };
struct MyTmpltLibXptn : public exception { /* . . . */ };
struct ProgXptn : public exception { /* . . . */ };
,
.. CourseXptn:
virtual ~CourseXptn() throw() { };
OfferedCourseXptn
CourseXptn:
virtual ~OfferedCourseXptn() throw() { };
, main(), catch(...) :
catch( exception& x )
{
cout << "unexpected exception " << typeid(x).name() << endl;
}

-
.
-
. what() .


.
,
.
, -
.
, .

21
.
- 945

.
. 19.4 :
, -
-
. ...
. . -
,
.

: , myFunc, myFunc -
37 !
, Project 6,
, 19.4
.

24.8.1

21.6.1. , operator= BString -
, :
try { BString tmp( rhs );
swap( tmp ); }
catch( BStringXptn& x )
{ strcpy( x.funcName, "operator=" );
throw; }
: BStringXptn, funcName -
. , operator=.

operator=. :
catch( BStringXptn& x )
{ strcat( x.funcName, "|operator=" );
throw; }
, x.funcName "BString|operator=". BStringXptn
:
void displayFuncName( ostream& tout )
{
tout << "thrown in ";
for ( int k(0); funcName[k] != '\0'; ++k )
if ( funcName[k] != '|' ) tout << funcName[k];
else tout << endl << " called by ";
tout << endl;
} // displayFuncName

// . . .
case BStringXptn::noMemory:
cout << "out of memory "; x.displayFuncName( cout );
break;
// . . .
:
out of memory thrown in BString
called by operator=
BStringXptn
void appendFuncName( const char* fn )
{ strcat( funcName, "|" );
946 24

strcat( funcName, fn ); } // appendFuncName


:
BString& BString::operator=( const BString& rhs )
{
if ( &rhs != this )
{
try { BString tmp( rhs );
swap( tmp ); }
catch( BStringXptn& x )
{ x.appendFuncName( "operator=" );
throw; }
}
return *this;
} // BString::operator=
BStringXptn :
struct BStringXptn : public exception
{
static const int fnLength = 100;
enum { noMemory, outOfRange };
char funcName[ fnLength ];
int errorCode;
int errorValue;
BStringXptn( const char* fn, int ec, int ev = 0 )
{ strncpy( funcName, fn, fnLength-1 );
funcName[fnLength-1] = '\0';
errorCode = ec; errorValue = ev; }
virtual ~BStringXptn() { };

void appendFuncName( const char* fn )


{ strcat( funcName, "|" );
strcat( funcName, fn ); } // appendFuncName

void displayFuncName( ostream& tout )


{
tout << "thrown in ";
for ( int k(0); funcName[k] != '\0'; ++k )
if ( funcName[k] != '|' ) tout << funcName[k];
else tout << endl << " called by ";
tout << endl;
} // displayFuncName
}; // BStringXptn
: -
100 fnLength :
static const int fnLength = 100;
funcName -
-
.. appendFuncName("load") appendFuncName(
"Course::load") 100 .

DateTime 24.5.
:
struct DateXptn : public exception
{
static const int fnLength = 100;
enum { yearErr, monthErr, dayErr, outOfLimits,
fileNotOpen, cannotRead, cannotWrite };
char funcName[ fnLength ];
int errorCode;
int errVal1;
int errVal2;
int errVal3;
- 947

Date errDateVal;
DateXptn( const char* fn, int ec,
int ev1 = 0, int ev2 = 0, int ev3 = 0 )
: errorCode(ec), errVal1(ev1), errVal2(ev2), errVal3(ev3)
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0'; }
DateXptn( const char* fn, int ec, int ev1, const Date& ed )
: errorCode(ec), errVal1(ev1), errDateVal(ed)
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0'; }
virtual ~DateXptn() throw() { };

void appendFuncName( const char* fn )


// BStringXptn

void displayFuncName( ostream& tout )


// BStringXptn
}; // DateXptn
DateTime:
DateTime::DateTime( int yp, int mp, int dp, int hp, int minp, int sp )
try : Date( yp, mp, dp )
{
if ( hp < 0 || 23 < hp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::hourRange, hp );
if ( minp < 0 || 59 < minp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::minRange, minp );
if ( sp < 0 || 59 < sp )
throw DateTimeXptn( "DateTime",
DateTimeXptn::secRange, sp );
dtHour = hp; dtMin = minp; dtSec = sp;
}
catch( DateTimeXptn& x )
{ throw; }
catch( DateXptn& x )
{
x.appendFuncName( "DateTime" );
throw;
} // DateTime::DateTime

day error ( 44 ) thrown in Date
called by DateTime

DateTime.
. -

; !
.
-
.
.
.


.

.
:
.
948 24

24.9
21.6 21.6.1 BString::operator=()
(exception safety) (strong guar-
antee). , ()
: a = b
.
a.

BString::swap() . BString::swap()
- (no-throw guarantee).
20.7.2.3
void Route::erase1RouteStop( int ndx )
{
for ( int k(ndx); k <= rNoOfStops; ++k )
rAllStops[k] = rAllStops[k+1];
--rNoOfStops;
} // Route::erase1RouteStop
ndx . -
rAllStops[k] = rAllStops[k+1] erase1RouteStop()
bad_alloc rAllStops[k], RouteStop, string
sName.
k k0. -
string :

rAllStops[k0] . :
k0 == ndx -
.
k0 > ndx, for rAllStops[k0-1]
rAllStops[k0]. , rAllStops[ndx],

k0-1 k0 . -
:
( k: 1..rNoOfStops-1 (rAllStops[k+1].sDist > rAllStops[k].sDist)
: rAllStops ,
rReserved rNoOfStops
.
Route::clearRouteStops().
Route::erase1RouteStop() (basic
guarantee).22
( -
) (Abrahams 2001):
: -
. (
) .
, -
. -

22 (minimal)
.
- 949

..
.
:

( ) -
.
.
-:
( ) .
-
. . -
; , , Route::erase1-
RouteStop -
. ; !
.
:

RouteStop* tmp( new RouteStop[rReserved] );


rAllStops[ndx]:
rAllStops
tmp.
, , .
: . -
; ;
! -
(
).
() -
; .
: , -
STL, -
RouteStop , , set<RouteStop>
-
.

-
.
- try/catch.
RAII . STL,
, .
, , () swap().
PIMPL (22.10).

24.10
C -


950 24

errno.
(abort(), exit(),
_Exit()) (atexit()).
assert()
. , , -
.
C++
terminate()
( abort()) .

-
unexpected(), terminate().
set_terminate() set_unexpected() terminate()
unexpected() .

throw().
( )
( ) exception.
-
. RAII swap() -
.



() .

25

:
-
C++: .
:

,
.
:









:
25.1 BString ............................................................................................... 952
25.2 ........................................................................................................ 955
25.3 ............................................................................................. 956
25.3.1 : pair..............................................................................................................................956
25.4 ................................................................................................................................. 958
25.5 .................................................................................................................. 959
25.5.1 ...................................................................................................961
25.6 ............................................................................................................... 964
25.6.1 ..............................................................................................964
25.6.2 ...........................................................................................964
25.6.3 .................................................................................965
25.7 ................................................................................................................................ 966
25.7.1 ...............................................................................................................................970
25.7.1.1 ......................................................................................................................................... 974
25.7.2 ........................................................................................................................................975
25.7.3 , ........................................................................................975
25.7.4 ..................................................................................................................................................976
25.8 ............................................................................................................................................. 977
25.8.1 std::auto_ptr .....................................................................................................................................................983
25.8.2 ... ..............................................................................................................................................985
25.9 ......................................................................................................... 985

951
952 25

25.10 ........................................................................................................................................ 988


................................................................................................................................................................... 988

:
, C++
,
1 (class templates) -
C++ .

C:
Java (generic types).
C# (generic classes).
(std::)string, ,
basic_string. (!)
:
BString BStringT.
.

25.1 BString
BString. ,
,
, char,
, unsigned char wchar_t. C++ ,
, .
, ,
:
0: class BString
1: { // I: (0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
2: friend bool operator==( const BString& lhs,
3: const BString& rhs );
4: public:
5: BString();
6: BString( const char* rhs, int n=0 );
7: BString( const BString& rhs );
8: ~BString() { delete[] bsData; };
9: BString& operator=( const BString& rhs );
10: BString& assign( const BString& rhs )
11: { return (*this = rhs); }
12: const char* c_str() const
13: { bsData[bsLen] = '\0'; return bsData; }
14: size_type length() const { return bsLen; }
15: bool empty() const { return ( bsLen == 0 ); }
16: char& at( int k ) const;
17: char& operator[]( int pos ) const { return bsData[pos]; }
18: BString& operator+=( const BString& rhs );
19: BString& append( const BString& rhs )
20: { return (*this += rhs); }
21: void swap( BString& rhs );
22: int compare( const BString& rhs ) const;
23: private:
24: static const unsigned int bsIncr = 16;
25: char* bsData;
26: size_type bsLen;
27: size_type bsReserved;

1 (parametric) .
953

28:
29: static size_type cStrLen( const char* cs );
30: static int stringCmpr( const char* lhs, const char* rhs,
31: int n );
32: }; // BString
:
BString::BString()
{
try { bsData = new char[bsIncr]; }
catch( bad_alloc )
{ throw BStringXptn( "BString", BStringXptn::allocFailed ); }
bsReserved = bsIncr;
bsLen = 0;
} // BString::BString
inline
.
operator==() :
ostream& operator<<( ostream& tout, const BString& rhs )
{
for ( int k(0); k < rhs.length(); ++k ) tout << rhs[k];
return tout;
} // operator<<( ofstream, BString
, BStringT,
char, :
'\0' char(0) ( . 13)
char2, (. 6, 12, 16, 17, 25, 29, 30),
, K.
BString, , BStringT.
template < typename K >
class BStringT
{ // I: (0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
friend bool operator==( const BStringT& lhs,
const BStringT& rhs );
public:
BStringT();
BStringT( const K* rhs, int n=0 );
BStringT( const BStringT& rhs );
~BStringT() { delete[] bsData; };
BStringT& operator=( const BStringT& rhs );
BStringT& assign( const BStringT& rhs )
{ return (*this = rhs); }
const K* c_str() const
{ bsData[bsLen] = K(0); return bsData; }
size_type length() const { return bsLen; }
bool empty() const { return ( bsLen == 0 ); }
K& at( int k ) const;
K& operator[]( int pos ) const { return bsData[pos]; }
BStringT& operator+=( const BStringT& rhs );
BStringT& append( const BStringT& rhs )
{ return (*this += rhs); }
void swap( BStringT& rhs );
int compare( const BStringT& rhs ) const;
private:
static const unsigned int bsIncr = 16;
K* bsData;
size_type bsLen;
size_type bsReserved;

2 replace !
954 25

static size_type cStrLen( const K* cs );


static int stringCmpr( const K* lhs, const K* rhs, int n );
}; // BStringT

template < typename K >.
, :
BString s1( "abc" ), s2, s3;
BString bs1( "abcdefg" ), bs2( "abcdefg", 3 );
:
BStringT<char> s1( "abc" ), s2, s3;
BStringT<char> bs1( "abcdefg" ), bs2( "abcdefg", 3 );
()
BStringT - char.
C++ basic_string -
. string :
typedef basic_string<char> string;
:
typedef basic_string<wchar_t> wstring;
, ,
:
typedef BStringT< char > String;
:
String s1( "abc" ), s2, s3;
String bs1( "abcdefg" ), bs2( "abcdefg", 3 );
String BString.
:
typedef BStringT< wchar_t > WString;
typedef BStringT< unsigned char > UString;
:
WString s1( L"abcd" ), s2( L"abcd" );
. ,
c_str(), length(), empty(), assign() append()
. operator+=() += -
. , BStringT
operator+=() .
. : template <
typename K >.
BStringT<char> :
BStringT<char>& BStringT<char>::operator+=( const BStringT<char>& rhs )
, BStringT<wchar_t> :
BStringT<wchar_t>&
BStringT<wchar_t>::operator+=( const BStringT<wchar_t>& rhs )
K
:
BStringT<K>& BStringT<K>::operator+=( const BStringT<K>& rhs )
, () :
template < typename K >
BStringT<K>& BStringT<K>::operator+=( const BStringT<K>& rhs )
{
if ( bsLen + rhs.bsLen + 1 > bsReserved )
{
955

K* tmp;
size_type tmpRes( ((bsLen+rhs.bsLen+1)/bsIncr+1)*bsIncr );
try { tmp = new K[tmpRes]; }
catch( bad_alloc& )
{ throw BStringTXptn( "operator+=",
BStringTXptn::allocFailed ); }
for ( int k(0); k < bsLen; ++k ) tmp[k] = bsData[k];
delete[] bsData;
bsData = tmp;
}
for ( int j(0), k(bsLen); j < rhs.bsLen; ++j, ++k )
bsData[k] = rhs.bsData[j];
bsLen += rhs.bsLen;
return *this;
} // BStringT<K>::operator+=

,
char* tmp K* tmp
new char[tmpRes] new K[tmpRes].
, :
template < typename K >
BStringT<K>::BStringT()
{
try { bsData = new K[bsIncr]; }
catch( bad_alloc )
{ throw BStringTXptn( "BStringT",
BStringTXptn::allocFailed ); }
bsReserved = bsIncr;
bsLen = 0;
} // BStringT<K>::BStringT<K>
BStringT BStringT<K>.

25.2
: ,
:
template < typename K >
class BStringT
{ // I: (0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
friend bool operator==( const BStringT<K>& lhs, const BStringT<K>& rhs );
public:
BStringT(); // default constructor
//
, -
, ..:
template < typename K >
bool operator==( const BStringT<K>& lhs, const BStringT<K>& rhs )
{
int int fv( BStringT<K>::stringCmpr(lhs.bsData, rhs.bsData,
min(lhs.bsLen, rhs.bsLen)) );
if ( fv == 0 ) fv = lhs.bsLen - rhs.bsLen;
return ( fv == 0 );
} // operator==( const BStringT<K>&
, . -
! ;
operator==() friend
.
956 25

:
friend:
template < typename K >
class BStringT
{// I: (0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
friend bool operator==( const BStringT<K>& lhs, const BStringT<K>& rhs )
{
int fv( stringCmpr(lhs.bsData, rhs.bsData,
min(lhs.bsLen, rhs.bsLen)) );
if ( fv == 0 ) fv = lhs.bsLen - rhs.bsLen;
return ( fv == 0 );
} // operator==
public:
BStringT(); // default constructor
//
. (..: gcc)
:
template < typename K1 >
friend bool operator==( const BStringT<K1>& lhs, const BStringT<K1>& rhs )
// . . .
:

(22.4) -
:
template < typename K > class BStringT;
template < typename K >
bool operator==( const BStringT<K>& lhs, const BStringT<K>& rhs );

template < typename K >


class BStringT
{// I: (0 <= bsLen < bsReserved) && (bsReserved % bsIncr == 0)
friend bool operator==( const BStringT<K>& lhs, const BStringT<K>& rhs );
// . . .
, .

25.3

. ( ) operator<<()
<<:
template < typename K >
ostream& operator<<( ostream& tout, const BStringT<K>& rhs )
{
for ( int k(0); k < rhs.length(); ++k ) tout << rhs[k];
return tout;
} // operator<<( ofstream, BStringT<K>
:

wchar_t, operator<<() !
( ).

25.3.1 : pair
#include <utility>
std::pair struct
STL.
957

template < typename T1, typename T2 >


struct PairT
{
T1 first;
T2 second;
// . . .
}; // PairT
pair: struct
. ; < :
PairT<T1, T2> x, y;
x < y :
(x.first < y.first) || (x.first == y.first && x.second < y.second)
, :
x.first < y.first || (!(y.first < x.first) && x.second < y.second
3 T1
.
:
PairT()
: first( T1() ), second( T2() ) { };
T1 T2.
:
PairT( const T1& x, const T2& y )
: first( x ), second( y ) { };
first(x) second(y) T1 T2
.
U V U T1 V 2

PairT( const PairT<U,V>& a )
: first( a.first ), second( a.second ) { };
;
!
template < typename T1, typename T2 >
struct PairT
{
T1 first;
T2 second;

PairT()
: first( T1() ), second( T2() ) { };
PairT( const T1& x, const T2& y )
: first( x ), second( y ) { };
template< typename U, typename V >
PairT( const PairT<U, V>& p )
: first( p.first ), second( p.second ) { };
}; // PairT
, PairT
.
< :
template < typename T1, typename T2 >
bool operator<( const PairT<T1, T2>& x, const PairT<T1, T2>& y )
{ return ( x.first < y.first ||
(!(y.first < x.first) && x.second < y.second) ); }
==:

3
958 25

template < typename T1, typename T2 >


bool operator==( const PairT<T1, T2>& x, const PairT<T1, T2>& y )
{ return ( x.first == y.first && x.second == y.second ); }

T1, T2.
, :
template < typename T1, typename T2 >
PairT< T1, T2 > make_pair( T1 x, T2 y )
{ return PairT< T1, T2 >( x, y ); }
x, y T1, T2 .
T1, T2
PairT:
.
.
<.
==.
: =
T1, T2 . :
= T1, T2.
:
, STL
, :
PairT< CourseKey, Course >
PairT< unsigned int, Student >
, . minmax
13.9.3 (. 1) :
PairT< int, int > minmax( int x, int y )
{
PairT< int, int > fv;

if ( x < y )
fv = PairT< int, int >( x, y );
else // x >= y
fv = PairT< int, int >( y, x );
return fv;
} // minmax
pqer ( 14.9 15.10) :
PairT< double, double > pqer( double x, double y, double z )
{
if ( x == y || x == -y || z <= 0 )
throw ApplicXptn( "pqer", ApplicXptn::paramErr, x, y, z );
PairT< double, double > fv;
fv.first = x*y*pow(z, x-y)/(x*x-y*y);
fv.second = (x*y-1/x)/z;
return fv;
} // pqer
, void.
,

25.4
, , 19.3: -
, , , .h. , ,
PairT , PairT.h, :
959

#ifndef _PAIRT_H
#define _PAIRT_H

using namespace std;

template < typename T1, typename T2 >


struct PairT
{
T1 first;
T2 second;

PairT()
: first( T1() ), second( T2() ) { };
PairT( const T1& x, const T2& y )
: first( x ), second( y ) { };
template< typename U, typename V >
PairT( const PairT<U, V>& p )
: first( p.first ), second( p.second ) { };
}; // PairT

template < typename T1, typename T2 >


bool operator==( const PairT<T1, T2>& x, const PairT<T1, T2>& y )
{ return ( x.first == y.first && x.second == y.second ); }

template < typename T1, typename T2 >


bool operator<( const PairT<T1, T2>& x, const PairT<T1, T2>& y )
{ return ( x.first < y.first ||
(!(y.first < x.first) && x.second < y.second) ); }

template < typename T1, typename T2 >


PairT< T1, T2 > make_pair( T1 x, T2 y )
{ return PairT< T1, T2 >( x, y ); }

#endif // _PAIRT_H

25.5
14.7.1 ()
/
,
.
.
:
class typename .
= () .
class typename .
.4
template
< > class .
= () .
C++03:
template< typename T > class myarray { /* ... */ };

template< typename K, typename V,


template< typename T> class C = myarray >
class Map

4 typename
int double ( ) .
960 25

{
C< K > key;
C< V > value;
// ...
};
myarray
template< typename T > class C.
.
- .
- .
- .
BStringT<AClass> -
, ,
:
template<> class BStringT<AClass> { /* . . . */ };
:
.
!
:
-
. : -
-
.
:
template < typename K > class A
{
public:
A( const K& b=0 ) { a = b; }
void operator+=( const A& q );
const K& getA() { return a; }
private:
K a;
}; // template < typename K > class A
A bool
A<bool> || + && *.
||=( ).
:
template < typename K >
void A<K>::operator+=( const A<K>& q )
{ a += q.a; }
:
template<>
void A<bool>::operator+=( const A<bool>& q )
{ a = a || q.a; }
:
template<> class A< bool > { /* . . . */ }; //

. -
, :
template < typename T1=int, typename T2=char, int n=1 >
class C { /* . . . */ }; // C
:
961

C<> ob0;
C< double > ob1;
C< long, int > ob2;
C< unsigned, wchar_t, 2 > ob3;
:
C< int, char, 1 > ob0;
C< double, char, 1 > ob1;
C< long, int, 1 > ob2;
C< unsigned int, wchar_t, 2 > ob3;
, 14.2 :
, , -
. : C<3>
x; : C<int, char, 3> x;

25.5.1
,
/ .

-
: (partial specialization)
.
( C++03).
:
template< typename T1, typename T2, int I > class A { /* . . . */ };
- .
) :
template< typename T1, typename T2, int I >
class A< T1*, T2, I > { /* . . . */ };
: .
) :
template< typename T1, typename T2, int I >
class A< T1, T2*, I > { /* . . . */ };
.
) :
template< typename T, int I > class A< T, T*, I > { /* . . . */ };
T1 T2 :
.
) :
template< typename T > class A< int, T*, 5 > { /* . . . */ };
int 5.

.
:

.
.
.
.

.
962 25



A< int, int, 1 > a1;
.
, int T1, T2 1 I.
:
A< int, int*, 1 > a2;

() int T1 T2 1 I.
() int T 1 I.
() .
:
A< int, char*, 5 > a3;

() int T1, char T2 5 I.
() char T.
() .
:
A< int, char*, 1 > a4;
() int
T1, char T2 1 I.
, :
A< int*, int*, 2 > a5;
() () .
, a5, .
:
#include <iostream>

using namespace std;

template< typename T1, typename T2, int I >


struct A
{
void f();
};

template< typename T1, typename T2, int I >


void A< T1, T2, I >::f() { cout << "f 0" << endl; }

template<> void A< int, int, 0 >::f()


{ cout << "f 0 ovrld" << endl; }

template< typename T1, typename T2, int I >


struct A< T1*, T2, I >
{
void f();
};

template< typename T1, typename T2, int I >


void A< T1*, T2, I >::f() { cout << "f a" << endl; }

template< typename T1, typename T2, int I >


struct A< T1, T2*, I >
{
void f();
};
963

template< typename T1, typename T2, int I >


void A< T1, T2*, I >::f() { cout << "f b" << endl; }

template< typename T, int I >


struct A< T, T*, I >
{
void f();
};

template< typename T, int I >


void A< T, T*, I >::f() { cout << "f c" << endl; }

template< typename T >


struct A< int, T*, 5 >
{
void f();
};

template< typename T >


void A< int, T*, 5 >::f() { cout << "f d" << endl; }

int main()
{
A< int, int, 0 > a0;
A< int, int, 1 > a1;
A< int, int*, 1 > a2;
A< int, char*, 5 > a3;
A< int, char*, 1 > a4;
A< int*, int*, 2 > a5;

a0.f();
a1.f();
a2.f();
a3.f();
a4.f();
a5.f();
}
A< int*, int*, 2 > a5; 5 : Too
many candidate template specializations from 'A<T1,T2,2>' in function main() .
a5.f();
:
f 0 ovrld
f 0
f c
f d
f b
:
template< typename T >
void A< int, T*, 5 >::f() { cout << "f d" << endl; }
: Error: Unresolved external 'A<int,
char *, 5>::f()' referenced from -
! -
: -
.

5 Borland C++ v.5.5.


964 25

25.6
; , .

25.6.1
. :
template < typename T >
class B
{
public:
B( T a ) : mb( a ) { };
virtual ~B() { };
virtual void display( ostream& tout ) { tout << mb; };
private:
T mb;
}; // B

class D : public B< char >


{
public:
D( char a1=0, int a2=0 )
: B<char>( a1 ), md( a2 ) { };
virtual ~D() { };
virtual void display( ostream& tout )
{ B<char>::display( tout ); tout << " " << md; }
private:
int md;
}; // D
()
: virtual .
display()
.

25.6.2
-
. . :
class B
{
public:
B( int a=0 ) : bCount( a ) { };
virtual ~B() { };
unsigned int getCount() const { return bCount; }
// . . .
protected:
unsigned int bCount;
}; // B

template < typename C, size_type sz=10 >


class D : public B
{
public:
D( int a=sz )
{ if ( a <= 0 ) throw a;
dArr = new C[a]; bCount = a; };
virtual ~D() { delete[] dArr; };
// . . .
private:
C* dArr;
}; // D
965

25.6.3

. :
template < typename T >
class B
{
public:
B( T a ) : mb( a ) { };
virtual ~B() { };
virtual void display( ostream& tout ) { tout << mb; };
private:
T mb;
}; // B

template < typename C >


class D : public B< C >
{
public:
D( C a1=0, int a2=0 )
: B<C>( a1 ), md( a2 ) { };
virtual ~D() { };
virtual void display( ostream& tout )
{ B<C>::display( tout ); tout << " " << md; }
private:
int md;
}; // D
B,
. -
.

D<char> x( 'x', 7 );
- D char.
B<char> D<char>.
STL.
()
(22.6.2). C++ -
#include
<functional>. ( ):
template < typename Arg1, typename Arg2, typename Result >
struct binary_function
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
};

template < typename T >


struct less : public binary_function< T, T, bool >
{
bool operator()( const T& x, const T& y ) const
{ return x < y; }
};
binary_function -
. :
#include <functional>
// . . .
using namespace std;
// . . .
less<int> lt;
966 25

less<int> () lt(1,-1) false.


:
template < typename C1, typename C2 >
class D1 : public B< C1 >
{
public:
D1( C1 a1=0, C2 a2=0 )
: B<C1>( a1 ), md( a2 ) { };
virtual ~D1() { };
virtual void display( ostream& tout )
{ B<C1>::display( tout ); tout << " " << md; }
private:
C2 md;
}; // D1
, (C1) -
(C2) .
,
.
1. B -
template < typename T >
class B
{
public:
void f() { /* . . . */ }
// . . .
T -
D f():
void g() { /* . . . */ f(); /* . . . */ }
(.. gcc) .
; f() this->f()
B<C>::f().
2. B , ..
:
template < typename T >
class B
{
public:
struct Qaz { /* . . . */ };
// . . .
T -
D Qaz:
void g() { Qaz x; /* . . . */ }
.
; :
void g() { typename B<C>::Qaz x; /* . . . */ }
(Cline 1999), 35.18 35.19.

25.7
(container class) -: -
. (container)
. :
SList GrElmn (21.11)
. .
967

CourseCollection, StudentCollection StudentInCourseCollection


Project 4 6 Course, Student Student-
InCourse .6

. -
.
: CourseCollection ( )
Course. ; ; !
.
( -
). CourseCollection (:
CourseCollection) (container adap-
tor) -.


K arr[sz];
int top;
push() pop() ((LIFO)
stack) K. K (.. int
Date Course ) .
.
:
! :
(top) push()
pop() +1 -1 .
top = 47 top += 19.
, .
arr[47] = ... q = arr[29].
arr top -
:
template < typename K, size_type sz = 100 >
class StackT
{
public:
// . . .
void push( const K& v );
void pop();
const K& getTop() const;
// . . .
private:
K arr[sz];
int top;
}; // StackT
:7
template < typename K, size_type sz = 100 >
class StackT
{
public:
StackT() { top = -1; } // empty stack

6 Project.
7 isEmpty(), -
STL.
968 25

StackT( const StackT& aSt );


void push( const K& v );
void pop();
const K& getTop() const;
bool empty() const { return ( top == -1 ); }
bool isFull() const { return ( top == sz-1 ); }
private:
K arr[sz];
int top;
}; // StackT

struct StackTXptn : public exception


{
static const int fnLength = 100;
enum { stackFull, stackEmpty };
char funcName[fnLength];
int errorCode;

StackTXptn( const char* fn, int ec ) : errorCode(ec)


{ strncpy( funcName, fn, 99 ); funcName[99] = '\0'; }
}; // StackTXptn

template < typename K, size_type sz >


void StackT<K,sz>::push( const K& v )
{
if ( top == sz-1 )
throw StackTXptn( "push", StackTXptn::stackFull );
++top; arr[top] = v;
} // push

template < typename K, size_type sz >


void StackT<K,sz>::pop()
{
if ( top == -1 )
throw StackTXptn( "pop", StackTXptn::stackEmpty );
--top;
} // pop

template < typename K, size_type sz >


const K& StackT<K,sz>::getTop() const
{
if ( top == -1 )
throw StackTXptn( "getTop", StackTXptn::stackEmpty );
return arr[top];
} // getTop
, . ;
.
renew(). , -
.
:
int main()
{
StackT<int> intStack;

cout << "Pushing integers on intStack" << endl;


for ( int i = 0; i < 5; i++ )
{
intStack.push( i ); // put items in the stack
cout << i << ' ';
}
cout << endl;

cout << endl << "Popping integers from intStack" << endl;
while ( !intStack.empty() )
{
969

cout << intStack.getTop() << ' ';


intStack.pop(); // remove items
}
cout << endl;

StackT<char> charStack;
cout << endl << endl
<< "Pushing characters on charStack" << endl;
for ( char c = 'A'; c < 'E'; c++ )
{
charStack.push( c ); // put items in the stack
cout << c << ' ';
}
cout << endl;

cout << endl << "Popping characters from charStack" << endl;
while ( !charStack.empty() )
{
cout << charStack.getTop() << ' ';
charStack.pop(); // remove items
}
cout << endl;
} // main
. -
.
:

template < typename K, size_type sz >
const K& StackT<K,sz>::pop()
{
if ( top == -1 )
throw StackTXptn( "pop", StackTXptn::stackEmpty );
--top;
return arr[top+1];
} // pop
-; !
: v K, aStack
StackT<K> :
v = aStack.pop();
K -
v . aStack;
!
:
v = aStack.getTop();
aStack.pop();

.

aStack . -
-
(atomicity), (
). C++11, API ,
.

970 25

25.7.1
SList, GrElmn (21.11),
. .
. SList,
21.11 22.9 .
BString char K
GrElmn K. . find1Elmn(),
get1Elmn() delete1Elmn() int -
, , GrElmn. -
-
. :
bool SList::find1Elmn( const GrElmn& aDtItem ) const
{
return ( findPtr(aDtItem) != slTail );
} // SList::find1Elmn

const GrElmn& SList::get1Elmn( const GrElmn& aDtItem ) const


{
ListNode* ptrToNode( findPtr(aDtItem) );
// . . .
} // SList::get1Elmn

void SList::delete1Elmn( const GrElmn& aDtItem )


{
ListNode* ptrToNode( findPtr(aDtItem) );
// . . .
} // SList::delete1Elmn
.
:
get1Elmn() :
; .
:
tmp = lst.get1Elmn( GrElmn(aa) );
aDtItem . -
(operator==()) GrElmn.
GrElmn K :
template < typename K >
class SListT
{
private:
struct ListNode
{
K lnData;
ListNode* lnNext;
}; // ListNode
public:
class Iterator
{
friend bool operator!=( const Iterator& a, const Iterator& b);
public:
explicit Iterator( ListNode* p = 0 ) { iPNode = p; }
Iterator& operator++();
K& operator*();
K* operator->();
bool operator!=( const Iterator& rhs ) const
{ return ( iPNode != rhs.iPNode ); }
bool operator==( const Iterator& rhs ) const
{ return ( !(*this != rhs) ); }
private:
971

ListNode* iPNode;
}; // Iterator

SListT();
SListT( const SListT& rhs );
~SListT();
SListT& operator=( const SListT& rhs );
void swap( SListT& rhs );
Iterator begin() { return Iterator( slHead ); }
Iterator end() { return Iterator( slTail ); }
bool find1Elmn( const K& aDtItem ) const;
const K& get1Elmn( const K& aDtItem ) const;
void insert1Elmn( const K& aDtItem );
void delete1Elmn( const K& aDtItem );
void save( ostream& bout,
void (*wrProc)(const K&, ostream&) ) const;
void display( ostream& tout ) const;
private:
ListNode* slHead;
ListNode* slTail;

ListNode* findPtr( const K& aDtItem ) const;


void push_front( const K& aData );
}; // SList
:
struct SListTXptn
{
enum { allocFailed, notFound, listEnd };
char funcName[100];
int errorCode;
int errIntVal;
SListTXptn( const char* fn, int ec, int iv=0 )
{ strncpy( funcName, fn, 99 ); funcName[99] = '\0';
errorCode = ec; errIntVal = iv; }
}; // SListXptn
++, *
-> SListT<K>::Iterator:
template < typename K >
SListT<K>::Iterator& SListT<K>::Iterator::operator++()
{
if ( iPNode == slTail ) // ( iPNode->lnNext == 0 )
throw SListTXptn( "Iterator::operator++",
SListTXptn::listEnd );
iPNode = iPNode->lnNext;
return *this;
} // SListT<K>::Iterator::operator++

template < typename K >


K& SListT<K>::Iterator::operator*()
{
if ( iPNode == slTail ) // ( iPNode->lnNext == 0 )
throw SListTXptn( "Iterator::operator*",
SListTXptn::listEnd );
return ( iPNode->lnData );
} // SListT<K>::Iterator::operator*

template < typename K >


K* SListT<K>::Iterator::operator->() const
{
if ( iPNode == slTail ) // ( iPNode->lnNext == 0 )
throw SListXptn( "Iterator::operator->",
SListXptn::listEnd );
return ( &(iPNode->lnData) );
} // SList::Iterator::operator->
972 25

template < typename K >


void SListT<K>::push_front( const K& aData )
{
ListNode* pnln;
try { pnln = new ListNode; }
catch( bad_alloc& )
{ throw SListTXptn( "push_front", SListTXptn::allocFailed ); }
pnln->lnData = aData; pnln->lnNext = slHead;
slHead = pnln;
} // SList::push_front
:
new ListNode lnData
K.
pnln->lnData = aData ()
K.
:
K .
() -
K.
-
ListNode :
struct ListNode
{
K lnData;
ListNode* lnNext;
ListNode()
: lnNext( 0 ) { };
explicit ListNode( const K& aData )
: lnData( aData ), lnNext( 0 ) { };
}; // ListNode
:
pnln = new ListNode; pnln->lnData = aData;

pnln = new ListNode( aData );

(lnData(aData)) K.
! : -
( ) STL -
.
. ,
:
K .
findPtr().
:
template < typename K >
SListT<K>::ListNode* SListT<K>::findPtr( const K& aDtItem ) const
{
ListNode* fv;
slTail->lnData = aDtItem;
fv = slHead;
while ( (fv->lnData) != aDtItem ) fv = fv->lnNext;
return fv;
} // SListT<K>::findPtr
973

slTail->lnData = aDtItem
K8 . GrElmn

K SListT.

:
template < typename K >
SListT<K>::ListNode* SListT<K>::findPtr( const K& aDtItem ) const
{
ListNode* fv;
for ( fv = slHead; fv != slTail; fv = fv->lnNext )
if ( fv->lnData == aDtItem ) break;
return fv;
} // SListT<K>::findPtr
: , !
:
template < typename K >
SListT<K>::Iterator SListT<K>::findIt( const K& aDtItem ) const
{
Iterator fv;
for ( fv = begin(); fv != end(); ++fv )
if ( *fv == aDtItem ) break;
return fv;
} // SListT<K>::findIt
findIt() get1Elmn() :
template < typename K >
const K& SListT<K>::get1Elmn( const K& aDtItem ) const
{
Iterator itToNode( findIt(aDtItem) );
if ( itToNode == end() )
throw SListTXptn( "get1Elmn", SListTXptn::notFound,
aDtItem.getANumber() );
return *itToNode;
} // SList<K>::get1Elmn
findIt() std::find()
22.9 :
Iterator itToNode( std::find(begin(), end(), aDtItem) );
insert1Elmn() delete1Elmn().
: private Iterator :
// . . .
private:
ListNode* iPNode;
ListNode* getPNode() const { return iPNode; }
}; // Iterator
, delete1Elmn() :
template < typename K >
void SListT<K>::delete1Elmn( const K& aDtItem )
{
Iterator itToNode( std::find(begin(), end(), aDtItem) );
if ( itToNode != end() ) //
{
ListNode* ptrToNode( itToNode.getPNode() );
ListNode* pnln( ptrToNode->lnNext );
// . . .

8 !
974 25

:
: .
.

25.7.1.1
, .
SList::~SList() template <typename K> SListT<K>::
~SListT(). :
virtual -
;
SLT : -
STL virtual;
. -
.
:
:
template < typename K >
class StackT
{
public:
// . . .
private:
SListT<K> cont;
}; // StackT
:
StackT< int > aStack;
:
class IntStack : public SListT<int> { /*. . . */ }
:
IntStack aStack;
; -
:
(
size_type sz = 100)
.
(is_a) .
23.14:
-
. .
.9

. virtual
.
;

.

9 23.15: has_a
private.
975

25.7.2

:
: K .
: K .
: K
.
, , :
: K .
STL.
. , ,
.

25.7.3 ,
slist10 ( list STL) :
iterator erase( iterator pos )
a slist<K> p slist<K>::iterator
a.erase( p );
- p. 1 -
.
.

Iterator erase( Iterator pos );
SlistT :
lnNext ! 21.11
. 21-1 SList::erase1Elmn.
:
template < typename K >
SListT<K>::Iterator SListT<K>::erase( SListT<K>::Iterator pos )
{
if ( pos == end() )
throw SListTXptn( "erase", SListTXptn::listEnd );
ListNode* ptrToNode( pos.getPNode() );
ListNode* pnln( ptrToNode->lnNext );
ptrToNode->lnNext = pnln->lnNext;
if ( pnln == slTail ) slTail = ptrToNode;
else ptrToNode->lnData = pnln->lnData;
delete pnln;
return pos;
} // SListT<K>::erase
, (private) Iterator -
:
ListNode* getPNode() const { return iPNode; }
-
:

10 SGI. C++11 forward_list


. forward_list erase() .
erase_after() -.
976 25

pos;
! *pos
. , pos .
.
- pos
.
: ptrTo-
Node->lnData = pnln->lnData. K
.

. . -
: ( )
.

25.7.4
-
. .

(StackT) . :
SListT<K> cont;
:
StackT() { };
.

StackT( const StackT& aSt );
:
template < class K, size_type sz >
StackT<K,sz>::StackT( const StackT<K,sz>& other )
: cont( other.cont ) { }
.
()
.
push() :
template < class K, size_type sz >
void StackT<K,sz>::push( const K& v )
{
try { cont.push_front( v ); }
catch( SListTXptn& x )
{ throw StackTXptn( "push", StackTXptn::stackFull ); }
} // StackT<K,sz>::push
: SListT::push_front() private -
public.

template < class K, size_type sz >
void StackT<K,sz>::pop()
{
if ( cont.empty() )
throw StackTXptn( "pop", StackTXptn::stackEmpty );
cont.pop_front();
} // StackT<K,sz>::pop
SListT::pop_front():
977

template < typename K >


void SListT<K>::pop_front()
{
if ( slHead == slTail )
throw SListTXptn( "pop_front", SListTXptn::listEmpty );
ListNode* pnln( slHead );
slHead = slHead->lnNext;
delete pnln;
} // SListT<K>::pop_front
, getTop() :
template < class K, size_type sz >
const K& StackT<K,sz>::getTop() const
{
if ( cont.empty() )
throw StackTXptn( "getTop", StackTXptn::stackEmpty );
return *cont.begin();
} // StackT<K,sz>::getTop
, inline :
bool isEmpty() const { return cont.empty(); }
bool isFull() const { return false; }
;
. ,
push() StackTXptn::stackFull -
SListTXptn::allocFailed
push_front().
;
! (size_type sz =
100) isFull();
:
,
; . ,
isFull() :
if ( !aStack.isFull() )
aStack.push( v );
StackTXptn stackFull! ,

SListT:
push_front() public
, pop_front() public.

.11
:
25.7
. ( )
.

25.8
16.7
-.

11 SListT
.
978 25

(memory leakage): (-) (-


) (
).
(pending dangling pointer):
(-) (-) (-)
(-)
.
(): p -
delete p; delete p; -
.
(smart pointers) -
.
STL C++.
auto_ptr.
. ,
AutoPtr.12

:
Date* pd( new Date(2010, 11, 26) );
AutoPtr< Date > apd( pd );
*apd *pd .
apd->getYear(), apd->getMonth(), apd->getDay() pd->getYear(), pd-
>getMonth(), pd->getDay() .
AutoPtr<K>
.
.
() :
template < typename K >
class Iterator
{
public:
explicit Iterator( ListNode* p = 0 ) { iPNode = p; }
K& operator*() const
{
if ( iPNode->lnNext == 0 )
throw SListTXptn( "Iterator::operator*",
SListTXptn::listEnd );
return ( iPNode->lnData );
} // operator*
K* operator->() const
{
if ( iPNode->lnNext == 0 )
throw SListXptn( "Iterator::operator->",
SListXptn::listEnd );
return ( &(iPNode->lnData) );
} // SList::Iterator::operator->
private:
ListNode* iPNode;
ListNode* getPNode() const { return iPNode; }
}; // Iterator
:

12 (Alexandrescu 2001) -
. . 7 ( )
http://ptgmedia.pearsoncmg.com/images/9780201704310/samplepages/0201704315.pdf.
979

template < typename K >


class AutoPtr
{
// . . .
private:
K* ap;
}; // AutoPtr
iPNode

.
:
explicit AutoPtr( K* p = 0 ) { ap = p; }
-
:
~AutoPtr() { delete ap; ap = 0; }
getPNode() ( auto_ptr):
: public.
: get.
K* get() const { return ap; }
operator* operator-> :
auto_ptr throw(). C++03
operator*() auto_ptr :
X& operator*() const throw();
: get() != 0
: *get()
operator->() :
X* operator->() const throw();
: get()
!
; :
K& operator*() const { return *ap; }
K* operator->() const { return ap; }
, AutoPtr
ap == 0 operator*() -
. ->
operator->()
-> .
:
AutoPtr<string> aps( new string("abc") );

cout << *aps << endl;
aps->assign( "qwerty" );
cout << *aps << endl;
:
abc
qwerty
:
template < typename K >
class AutoPtr
{
explicit AutoPtr( K* p = 0 ) { ap = p; }
~AutoPtr() { delete ap; ap = 0; }
980 25

K* get() const { return ap; }


K& operator*() const { return *ap; }
K* operator->() const { return ap; }
private:
K* ap;
}; // AutoPtr
; :
void f( int v )
{
int* p( new int(v) );
// . . .
if ( . . . ) throw SomeXptn( . . . );
// . . .
int q( 25 + *p );
// . . .
delete p;
} // f
delete p, -
. :
void f( int v )
{
AutoPtr<int> p( new int(v) );
// . . .
if ( . . . ) throw SomeXptn( . . . );
// . . .
int q( 25 + *p );
// . . .
} // f
: -
p
p. , delete,
.
AutoPtr. release().
release() auto_ptr:
X* release() throw();
: get()
: (*this) (NULL).
: .
K* release() { K* fv( ap ); ap = 0; return fv; }
get() .
auto_ptr< Date > apd( new Date(2010, 11, 26) );
:
cout << *apd << endl;
Date* pd0( apd.get() );
cout << *apd << endl;

Date* pd1( apd.release() );


cout << *pd1 << endl;
if ( apd.get() == 0 ) cout << "it is NULL" << endl;
:
26.11.2010
26.11.2010
26.11.2010
it is NULL
, apd.release(),
apd . pd1,
981

. Date* pd0(apd.get()) apd pd0


, .
reset():
void reset( X* p=0 ) throw();
: get() != p delete get().
: (*this) p.
. : -
.
void reset( K* p=0 )
{ if ( ap != p ) { delete ap; ap = p; } }
:
api1.reset();
api1. , -
.
.
C++03 :
auto_ptr( auto_ptr& a ) throw();
: a.release().
: *this a.release().
AutoPtr :
AutoPtr( AutoPtr& other ) { ap = other.release(); }
:
AutoPtr( AutoPtr& other ) { ap = other.ap; other.ap = 0; }
; ap
other.ap , , other.ap const
. (move
constructor).13
:
auto_ptr& operator=( auto_ptr& a ) throw();
: delete get().
: reset( a.release() ).
: *this.
AutoPtr :
AutoPtr& operator=( AutoPtr& rhs )
{ reset( rhs.release() ); return *this; }
:
AutoPtr& operator=( AutoPtr& rhs )
{ if ( ap != rhs.ap )
{ delete ap; ap = rhs.ap; rhs.ap = 0; }
return *this; }

.
reset() rhs.release() rhs -
. const.
, -
:
.

13 C++11
.
982 25

-
.

.
: get()!
AutoPtr.h:
#ifndef _AUTOPTR_H
#define _AUTOPTR_H

template < typename K >


class AutoPtr
{
public:
explicit AutoPtr( K* p=0 ) { ap = p; }
AutoPtr( AutoPtr& other ) { ap = other.release(); }
~AutoPtr() { delete ap; ap = 0; }
AutoPtr& operator=( AutoPtr& rhs )
{ reset( rhs.release() ); return *this; }
K* get() const { return ap; }
K& operator*() const { return *ap; }
K* operator->() const { return ap; }
K* release() { K* fv( ap ); ap = 0; return fv; }
void reset( K* p=0 )
{ if ( ap != p ) { delete ap; ap = p; } }
private:
K* ap;
}; // AutoPtr

#endif // _AUTOPTR_H
:
#include <iostream>
#include <string>

#include "AutoPtr.h"
#include "Date.cpp"

using namespace std;

int main()
{
AutoPtr< string > aps( new string("abc") );
cout << *aps << endl;
aps->assign( "qwerty" );
cout << *aps << endl;

AutoPtr< Date > apd( new Date(2010, 11, 26) );


cout << *apd << endl;
Date* pd0( apd.get() );
cout << *apd << endl;

Date* pd1( apd.release() );


cout << *pd1 << endl;
if ( apd.get() == 0 ) cout << "it is NULL" << endl;
}
: new delete
. -
C++
(garbage collection). ,
.
983

25.8.1 std::auto_ptr
:
#include "AutoPtr.h" #include <memory>
AutoPtr auto_ptr

(std::)auto_ptr C++.
auto_ptr memory C++ -
AutoPtr .
.
1. :
auto_ptr<int> api1( new int(375) );
auto_ptr<string> aps1( new string(F.C.Barcelona) );
auto_ptr<int> api2;
auto_ptr<string> aps2( aps1 );
: api1 -
( int) 375.
: aps1 (
string) F.C.Barcelona.
: api2 .
aps2
( std::string) F.C.Barcelona
aps1. aps1 .
!
) :
int k( 255 );
auto_ptr<int> api0( &k );
-
. ; delete ! , -
! !
) -
. .. :
int* pi1( new int(511) );
auto_ptr<int> api( pi1 );
cout << *api << endl;
*pi1 = 375;
cout << *api << endl;
int* pi2( api.get() );
*pi2 = 101;
cout << *api << endl;
:
511
375
101
!
2.
get(). * .

if ( api1.get() != 0 ) cout << *api1 << endl;
else cout << " api1 NULL" << endl;
if ( aps1.get() != 0 ) cout << *aps1 << endl;
else cout << " aps1 NULL" << endl;
if ( api2.get() != 0 ) cout << *api2 << endl;
else cout << " api2 NULL" << endl;
984 25

if ( aps2.get() != 0 ) cout << *aps2 << endl;


else cout << " aps2 NULL" << endl;
:
375
aps1 NULL
api2 NULL
F.C.Barcelona
3. , -
, . 1,
:
cout << *api1 << endl;
cout << *(f(api1)) << endl;
if ( api1.get() != 0 ) cout << *api1 << endl;
else cout << " api1 NULL" << endl;
:
auto_ptr<int> f( auto_ptr<int> x )
{
*x += 1;
return x;
} // f
:
375
376
api1 NULL
api1 375. -
f(), api1 . -
api1
. x.
return x , -
,
!
4. reset()
() =.
reset():
void reset( K* p = 0 )
, reset() . , :
api1.reset( new int(1023) );
cout << *api1 << endl;
cout << *aps2 << endl;
aps2.reset( new string("Kavala F.C.") );
cout << *aps2 << endl;
:
1023
F.C.Barcelona
Kavala F.C.
, reset(),
) ,
) ,
( ).
= :
auto_ptr& operator=( auto_ptr& rhs ) throw()
{ reset( rhs.release() ); return *this; }
. ,
--. :
985

double* pd2( new double(7.5) );


auto_ptr<double> apd2( pd2 );
auto_ptr<double> apd3;
apd3 = apd2;
:
apd3 = auto_ptr<double>( new double(7.5) );
:
apd3 = f( pd2 );
,
. :
apd3 = apd2;
apd3 apd2 apd2 -
(apd2.ap = 0).
5. reset() -
( , delete ). ..:
apd3.reset();
6. release() :
double* pd( apd3.release() );

25.8.2 ...

.
auto_ptr, C++.
, -
:
=
.
delete
reset().
auto_ptr .
, C++11 auto_ptr (
) ,
unique_ptr, .
C++11 , shared_ptr
weak_ptr, Boost .14

25.9
#include <limits>
std::numeric_limits. :
template< typename T >
class numeric_limits
{
public:
static const bool is_specialized = false;
static T min() throw();
static T max() throw();
static const int digits = 0;
static const int digits10 = 0;

14 http://www.boost.org/libs/smart_ptr/smart_ptr.htm
986 25

static const bool is_signed = false;


static const bool is_integer = false;
static const bool is_exact = false;
static const int radix = 0;
static T epsilon() throw();
static T round_error() throw();
static const int min_exponent = 0;
static const int min_exponent10 = 0;
static const int max_exponent = 0;
static const int max_exponent10 = 0;
static const bool has_infinity = false;
static const bool has_quiet_NaN = false;
static const bool has_signaling_NaN = false;
static const float_denorm_style has_denorm = denorm_absent;
static const bool has_denorm_loss = false;
static T infinity() throw();
static T quiet_NaN() throw();
static T signaling_NaN() throw();
static T denorm_min() throw();
static const bool is_iec559 = false;
static const bool is_bounded = false;
static const bool is_modulo = false;
static const bool traps = false;
static const bool tinyness_before = false;
static const float_round_style round_style = round_toward_zero;
};
; static!
.
.
. 17. limits
bool, char, signed char, unsigned char, wchar_t, short, int, long,
unsigned short, unsigned int, unsigned long, float, double long double.
min_exponent, min_exponent10, max_exponent, max_exponent10
epsilon(), round_error() -
, float, double long double (
). -
0 false .
-
(2.5):
#include <iostream>
#include <climits>
using namespace std;
int main()
{
cout << "INT_MIN = " << INT_MIN << " INT_MAX = "
<< INT_MAX << endl;
}
:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
cout << "INT_MIN = " << numeric_limits<int>::min()
<< " INT_MAX = " << numeric_limits<int>::max() << endl;
}
:
#include <climits> #include <limits>.
INT_MIN numeric_limits<int>::min().
987

INT_MAX numeric_limits<int>::max().
C. ,
, C++.
, :
#include <iostream>
#include <cfloat>
using namespace std;
int main()
{
cout << "DBL_MIN = " << DBL_MIN
<< " DBL_MAX = " << DBL_MAX << endl;
cout << "DBL_EPSILON = " << DBL_EPSILON << endl;
}
:
#include <iostream>
#include <limits>
using namespace std;
int main()
{
cout << "DBL_MIN = " << numeric_limits<double>::min()
<< " DBL_MAX = " << numeric_limits<double>::max()
<< endl;
cout << "DBL_EPSILON = " << numeric_limits<double>::epsilon()
<< endl;
}
C++
: C,
24.1.3. -
C.
numeric_limits -
(traits) -
C++.


template < typename T >
class MyClass
{
void f( ... )
{ . . . }
}
.
f T.
if:
if ( T o int ) { T mt( INT_MAX ); ... }
else if ( T long ) { T mt( LONG_MAX ); ... }
else . . .
T o int C++ -
typeinfo.

:
T mt( numeric_limits<T>::max() ); ...

, -
.
988 25

:
, ,
BStringT: C++ :
template< typename charT > struct char_traits
:
template<> struct char_traits< char >;
template<> struct char_traits< wchar_t >;
BStringT ( -
.)

25.10
-
.
.

.
:
.

.
.
/
: ( )
( 25.8.2).
numeric_limits
.

25-1 -
Bitmap.

26
-
Standard Template Library (STL)
:
STL.
:

. -
,
.
:
,






:
26.1 , ............................................................................................. 991
26.1.1 .........................................................................................................................................992
26.1.2 ........................................................................................................................................994
26.1.3 ...........................................................................................................................................................996
26.1.3.1 .......................................................................................................... 1000
26.1.4 ..............................................................................................................................1003
26.2 ............................................................................................................................................... 1005
26.2.1 vector ..................................................................................................................................1008
26.2.1.1 , ............................................................................................................... 1011
26.2.1.2 : vector<bool>............................................................................................. 1012
26.2.2 deque...................................................................................................................................1013
26.2.3 list ........................................................................................................................................1014
26.2.4 ; ...........................................................................................................................1018
26.3 ........................................................................................................................... 1018
26.3.1 set ........................................................................................................................................1020
26.3.1.1 .................................................................................................................. 1023
26.3.2 map ......................................................................................................................................1027
26.3.3 multiset multimap.................................................................................................1030
26.3.4 .............................................................................................................................................1031
26.4 ; .................................................................................................................... 1033
26.5 ................................................................................................................................ 1034
26.5.1 bitset ....................................................................................................................................1034
26.5.2 complex...............................................................................................................................1037
26.6 ( ) .......................................................................................... 1038
989
990 26

................................................................................................................................................................. 1038

:
(Standard Template Library STL)
:
,
,
,
.

(allocators)
.

( renew()).
! -
: STL .
:

, .
renew() MyTmpltLib.h qsort() 16.10
:
#include <iostream>
#include <cstdlib>

#include "MyTmpltLib.h"

using namespace std;

int compare( const void* a, const void* b )


{
return ( *reinterpret_cast<const unsigned int*>(a) -
*reinterpret_cast<const unsigned int*>(b) );
} // compare

int main()
{
const unsigned int inc( 5 );
size_type size( inc );
unsigned int* array( new unsigned int[inc] );

int x;
size_type count( 0 );
cin >> x;
while ( x >= 0 )
{
if ( count >= size )
{
renew( array, count, size+inc );
size += inc;
}
array[count] = x;
++count;
cin >> x;
} // while
qsort( array, count, sizeof(int), compare );
for ( int k(0); k < count; ++k )
cout << array[k] << endl;
}
- Standard Template Library (STL) 991

vector list deque


set map

multiset multimap

. 26-1 STL.

-
STL.

26.1 ,
:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
vector< unsigned int > array;

int x;
cin >> x;
while ( x >= 0 )
{
array.push_back( x );
cin >> x;
} // while
sort( array.begin(), array.end() );
size_type count( array.size() );
for ( int k(0); k < count; ++k )
cout << array[k] << endl;
}
, .
vector STL
unsigned int.
array .
array.size() array
. array.push_back(x) x -
. .
sort
.
< -
.
992 26

array.begin() array.end() array


() .
SListT.

26.1.1
(25.7) (container)
(container class) -: -
.
.
STL (. 26-1):
(sequences)
.
vector (). vector<K> vt; vt
() K.
list. list<K> lt; lt
K.
deque (double ended queue, ). -
.

priority_queue ( ). , -
-
. STL < ( )
.
queue () FIFO. -
. -
.
stack () LIFO. .
-
.
(associative containers) -
. :
set ().
multiset ().
map (), (, ).
multimap (), (, ).
:
.
.
.
.
size() .
max_size() -
.
empty() true .
swap() ( ).
get_allocator()
.
- Standard Template Library (STL) 993

.

==, != ( a b !(a == b)),
<, >= ((a >= b) !(a < b)),
>, <= ((a > b) (b < a)).
< (22.7.3). -
( ==) < .
.
iterator SListT. -
++, *, ->, ==, !=. , --":
(bidirectional) SListT .
const_iterator.
C<T>::const_iterator it;
*it.

:
begin():
.
iterator begin();
const_iterator begin() const;
end(): (!)
.
iterator end();
const_iterator end() const;
( const_iterator - const.) -
a a.empty() true a.begin() == a.end().
, : (!)
, (
, .. 25.7.1) ; -

C STL, :
for ( C<T>::iterator it( co.begin() ); it != co.end(); ++it )
{ /* . . . */ }
T --
co. -
C<T>::const_iterator
.
:
list< int > il;
0, 1, 2, 3, 4.
for ( list<int>::iterator it( il.begin() );
it != il.end(); ++it )
cout << *it << " ";
cout << endl;
:
0 1 2 3 4
reverse_iterator const_reverse_iterator. -
.
:
994 26

rbegin(): -
.
reverse_iterator rbegin();
const_reverse_iterator rbegin() const;
rend(): (!)
.
reverse_iterator rend();
const_reverse_iterator rend() const;

for ( list<int>::reverse_iterator rit( il.rbegin() );
rit != il.rend(); ++rit )
cout << *rit << " ";
cout << endl;
:
4 3 2 1 0
++rit.
.
.
.
25.7.2
SListT:
K .
K .
() -
K.
K .
. ,
K -
.

26.1.2
STL
.
. ;

.
, 22.9, .
*, ->, ++, ==, !=.
, ,
--.
(random access itera-
tors) : -
(12.3):
+, -, +=, -=
( ).
:
#include <iostream>
#include <vector>
#include <algorithm>
- Standard Template Library (STL) 995

#include <iterator>

using namespace std;

int main()
{
vector< unsigned int > array;
istream_iterator< unsigned int > cinIt( cin );
istream_iterator< unsigned int > cinEoStream;

while ( cinIt != cinEoStream )


{
array.push_back( *cinIt );
++cinIt;
} // while
sort( array.begin(), array.end() );
size_type count( array.size() );
ostream_iterator< unsigned int > coutIt( cout, " " );
for ( int k(0); k < count; ++k )
*coutIt = array[k];
cout << endl;
}
:
19 0 17 3 11 5 7 e
0 3 5 7 11 17 19
#include <iterator> -
ostream_iterator
T <<
. coutIt ostream. coutIt
unsigned int cout
(" "). v; : *coutIt =
v; cout << v << " ";. , for
.
ostream_iterator (output itera-
tor). :
, () . -
(.. ++).
-l (11.3). -
-
(*coutIt = array[k];).
, -
, .
, istream.
istream :
istream_iterator< unsigned int > cinIt( cin );
istream_iterator< unsigned int > cinEoStream;

while ( cinIt != cinEoStream )


{
array.push_back( *cinIt );
++cinIt;
} // while
O cinIt istream_iterator<unsigned int>:
unsigned int istream, cin. -
istream_iterator cinEoStream -
unsigned int -
.
996 26

(*cinIt).
>>. ++.
( -
unsigned int) cinIt cinEoStream.
istream_iterator (input itera-
tor) :
, () .
, (.. ++). ,
== !=.
-r (
).

: , , .
#include <iterator>

template < typename InputIterator, typename Distance >
void advance( InputIterator& it, Distance n );
+= . Distance
; . InputIterator
Distance int.
unsigned int.
advance(it, n);
it , it += n;
(n ) ++it; --it;.

26.1.3
#include <algorithm>
:
(std::)max(), (std::)min(),
(std::)swap(),
(std::)find(),
(std::)sort().
, .
C++ .

:
template< class InputIterator, class OutputIterator >
OutputIterator copy( InputIterator first, InputIterator last,
OutputIterator result );

[ first, last ) [ result, result + (last - first) ).
*result = *first, *(result+1) = *(first +1) , ...
. result + (last - first)
.
:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
- Standard Template Library (STL) 997

using namespace std;

int main()
{
vector< unsigned int > array;
istream_iterator< unsigned int > cinIt( cin );
istream_iterator< unsigned int > cinEoStream;
back_insert_iterator< vector<unsigned int> > dest( array );
copy( cinIt, cinEoStream, dest );
sort( array.begin(), array.end() );
ostream_iterator< unsigned int > coutIt( cout, " " );
copy( array.begin(), array.end(), coutIt );
cout << endl;
}
:
[array.begin(), array.end()) cout.
.
.
copy(); :
copy( cinIt, cinEoStream, array.begin() );
! : array -
.
:
back_insert_iterator< vector<unsigned int> > dest( array );
copy( cinIt, cinEoStream, dest );
back_insert_iterator : ,
copy(),
array .
,
! copy sort copy ! , :
!
:
1. STL (
). , , -
while for.
2. STL
C++ . -
:
#include <algorithm>
#include <iterator>
#include <iostream>

using namespace std;

int main()
{
int array[100];
int* pEnd;

pEnd = copy( istream_iterator<int>(cin), istream_iterator<int>(),


array );
sort( array, pEnd );
copy( array, pEnd, ostream_iterator<int>(cout, "\n") );
}
998 26

, . -
, array pEnd. copy()
sort().
-
.
min() max() :
template< class T >
const T& min( const T& a, const T& b );
template< class T, class Compare >
const T& min( const T& a, const T& b, Compare comp );

template< class T >


const T& max( const T& a, const T& b );
template< class T, class Compare >
const T& max( const T& a, const T& b, Compare comp );
T
<
.
, min() :
template < class T >
inline const T& min( const T& a, const T& b )
{ return b < a ? b : a; }
T
< comp()
T . min()
:
template < class T, class Compare >
inline const T& min( const T& a, const T& b, Compare comp )
{ return comp(b, a) ? b : a; }
Compare , -
() T
true .
-
: min( i1, i2 ).
"abc" "aggr" .1
:
class Compare:
struct CStrLT
{
bool operator()( const char cs1[], const char cs2[] )
{ return strcmp(cs1, cs2) < 0; }
}; // CStrLT
min("abc", "aggr", cstrLT) cstrLT (-
) CStrLT.
():
bool cstrLTf( const char cs1[], const char cs2[] )
{ return strcmp(cs1, cs2) < 0; }
min("abc", "aggr", cstrLTf).

1 min( string("abc"), string(


"aggr") ).
- Standard Template Library (STL) 999

max() :
> < .
max("abc", "aggr", cstrLTf) "aggr".
:
template< class InputIterator, class T >
InputIterator find( InputIterator first, InputIterator last,
const T& value );
T == !=.
find_if() find():
template< class InputIterator, class Predicate >
InputIterator find_if( InputIterator first, InputIterator last,
Predicate pred );
it pred(*it) -
true. last.
pred comp
pred .
sort() :
template< class RandomAccessIterator >
void sort( RandomAccessIterator first, RandomAccessIterator last );
template< class RandomAccessIterator, class Compare >
void sort( RandomAccessIterator first, RandomAccessIterator last,
Compare comp );
- -
. <
( ) comp()
.
, -
; .
template< class ForwardIterator, class T >
bool binary_search( ForwardIterator first, ForwardIterator last,
const T& value );
template< class ForwardIterator, class T, class Compare >
bool binary_search( ForwardIterator first, ForwardIterator last,
const T& value, Compare comp );
: [first, last) it
*it == value binary_search() true. .
( ):
template< class ForwardIter, class T >
ForwardIter lower_bound( ForwardIter first, ForwardIter last,
const T& value );
template< class ForwardIter, class T, class Compare >
ForwardIter lower_bound( ForwardIter first, ForwardIter last,
const T& value, Compare comp );
rv
value
value. it [first, rv) *it
< value. rv != last it [rv, last) *it >= value (: !(*it < value).)
[first, rv) comp(*it, value) (==
true) [rv, last) !comp(*it, value).
[first, last) rv :
*rv == value (: !(*rv < value) && !(value < *rv).)
:
1. log(lastfirst).
1000 26

2. comp (: )
. .
3. upper_bound()
.

26.1.3.1
-
:
for_each(), transform() random_shuffle().

template< class InputIterator, class Function >
Function for_each( InputIterator first, InputIterator last, Function f );
[first, last) (InputIterator) it
f(*it). f() void .
Function () ( -
)
InputIterator. -
: . -
-r f(*it)
it.
for_each() f
.

#include <iostream>
#include <algorithm>

using namespace std;

template< typename T >


struct Print
{
void operator()( T x )
{ cout << x << ' '; }
}; // Print

int main()
{
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
Print<int> pr;

for_each( intArr, intArr + 7, pr );


cout << endl;
}
:
34 72 -23 8 -11 31 41
:
for_each( intArr, intArr+7, printF<int> );
cout << endl;

template< typename T >


void printF( T x ) { cout << x << ' '; }
for_each() -
Print (SGI 1999):
template< typename T >
struct Print
- Standard Template Library (STL) 1001

{
Print() : count(0) {};
void operator()( T x )
{ cout << x << ' ';
++count; }
unsigned int count;
}; // Print
:
pr = for_each( intArr, intArr+7, pr );
cout << endl << pr.count << " numbers printed" << endl;
:
34 72 -23 8 -11 31 41
7 numbers printed
:
template< class InputIter, class OutputIter,
class UnaryOperation >
OutputIterator transform( InputIter first, InputIter last,
OutputIter result, UnaryOperation op );
template< class InputIter1, class InputIter2,
class OutputIter, class BinaryOperation >
OutputIterator transform( InputIter1 first1, InputIter1 last1,
InputIter2 first2, OutputIter result,
BinaryOperation binary_op );
[first, last) -
(InputIterator) it op(*it) -
result. result
first. -
.
:
#include <iostream>
#include <algorithm>

using namespace std;

template< class T >


struct Sqr
{
T operator()( T x ) { return x*x; }
}; // Sqr

int main()
{
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
int intArr1[7];
Sqr<int> sqr;

copy( intArr, intArr+7, ostream_iterator<int>(cout, " ") );


cout << endl;
int* res1( transform(intArr, intArr+7, intArr1, sqr) );
copy( intArr1, intArr1+7, ostream_iterator<int>(cout, " ") );
cout << endl << (res1-intArr1) << endl;

int* res( transform(intArr, intArr+7, intArr, sqr) );


copy( intArr, intArr+7, ostream_iterator<int>(cout, " ") );
cout << endl << (res-intArr) << endl;
}
:
34 72 -23 8 -11 31 41
1156 5184 529 64 121 961 1681
7
1156 5184 529 64 121 961 1681
1002 26

7
Sqr2 -
.
transform()
intArr intArr1. -
( ) (res1)
intArr1 7 int.
transform()
intArr. (res)
intArr 7 int.
:
. -

( ). :
: [first1, last1).
first2
.

template< typename T >
struct Sum
{
T operator()( T x, T y ) { return x + y; }
};
:
Sum<int> sum;
int intArr2[7];
:
transform( intArr, intArr+7, intArr1, intArr2, sum );
copy( intArr2, intArr2+7, ostream_iterator<int>(cout, " ") );
cout << endl;
:
1190 5256 506 72 110 992 1722
, 1190 34+1156, 5256 == 72+5184 ... , sum 7
intArr[k] + intArr1[k].
intArr2[k]. , intArr2, intArr intArr1.
random_shuffle() :
template< class RandomAccessIter >
void random_shuffle( RandomAccessIter first, RandomAccessIter last);
template< class RandomAccessIter, class RandomNumberGenerator >
void random_shuffle( RandomAccessIter first, RandomAccessIter last,
RandomNumberGenerator& rand );

[first1, last1). -
rand, (),
rand(n) [0..n).
:
#include <iostream>
#include <algorithm>

using namespace std;

2 .
- Standard Template Library (STL) 1003

int main()
{
char* cardDeck[52] = { "S2","S3","S4","S5","S6","S7","S8","S9","S10","SJ",
"SQ","SK","SA",
"H2","H3","H4","H5","H6","H7","H8","H9","H10","HJ",
"HQ","HK","HA",
"D2","D3","D4","D5","D6","D7","D8","D9","D10","DJ",
"DQ","DK","DA",
"C2","C3","C4","C5","C6","C7","C8","C9","C10","CJ",
"CQ","CK","CA" };
random_shuffle( cardDeck, cardDeck+52 );
for ( int k(0); k < 52; ++k )
{
cout << cardDeck[k] << ' ';
if ( k%13 == 12 ) cout << endl;
}
}
:3
DK SK D5 HQ H7 D3 C4 CQ H9 H4 S6 D8 C10
S7 C9 C2 D9 DA H3 D10 CJ S10 H10 CA S9 H8
C3 SA C6 SJ H2 H5 HJ D6 D7 CK S2 C7 DJ
HA D2 H6 C8 S4 C5 S8 S3 SQ DQ HK S5 D4

26.1.4
set :
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> >
class set;
,
,
, set, -
sort(), class Compare = less<Key>
set<T> less<T>
(25.6.3):
template < typename T >
struct less
{
bool operator()( const T& x, const T& y ) const
{ return x < y; }
};
#include <functional> -
-
.
4
template < class Arg, class Result >
struct unary_function
{
typedef Arg argument_type;
typedef Result result_type;
}; // unary_function

template < typename Arg1, typename Arg2, typename Result >

3 ; "Sx" "x", "Hx" "x", "Dx" "x" "Cx" "x".


4 C++11 unary_function, binary_function (
).
1004 26

struct binary_function
{
typedef Arg1 first_argument_type;
typedef Arg2 second_argument_type;
typedef Result result_type;
}; // binary_function
, :
template < class T >
struct negate : public unary_function< T, T >
{
T operator() ( const T& x ) const { return -x; }
};

template < class T >


struct plus : public binary_function<T, T, T>
{
T operator() ( const T& x, const T& y ) const { return x + y; }
};

template < typename T >


struct less : public binary_function< T, T, bool >
{
bool operator()( const T& x, const T& y ) const
{ return x < y; }
};
binary_function
plus() (+), minus() (), multiplies() (*), divides() (/), modulus() (%)
equal_to() (==), not_equal_to() (!=), greater() (>), less() (<), greater_equal() (>=),
less_equal() (<=)
logical_and() (&&), logical_or() (||)
unary_function
negate() (-)
logical_not() (!)
transform()
Sum. #include
<functional>, sum :
plus<int> sum;
.
algorithm
STL. .
-
.

Project04, CourseCollection :
Course* CourseCollection::findDep( string code )
( Course)
(prereq) code. 0
(NULL).
delete1-
Course()
template< class InputIterator, class Predicate >
InputIterator find_if( InputIterator first, InputIterator last,
Predicate pred );
:
- Standard Template Library (STL) 1005

Course* find_if( ccArr, ccArr+ccNOfCourses, pred???? );


pred????; s s.prereq
== code. :
struct EqPrereq
{
bool operator()( const Course& x, const string& y ) const
{ return ( strcmp(x.getPrereq(), y.c_str()) == 0 ); }
}; // EqPrereq
pred????
ccArr[0], ccArr[1] ...
EqPrereq :
bind2nd(EqPrereq(),code)
: EqPrereq()
code.
bind2nd() () -
binary_function. :
struct EqPrereq : binary_function< Course, string, bool >
{
bool operator()( const Course& x, const string& y ) const
{ return ( strcmp(x.getPrereq(), y.c_str()) == 0 ); }
}; // EqPrereq
:
Course* CourseCollection::findDep( string code )
{
Course* k;
k = find_if( ccArr, ccArr+ccNOfCourses, bind2nd(EqPrereq(),code) );
if ( k == ccArr+ccNOfCourses ) k = 0;
return k;
} // findDep

bind2nd() bind1st() -
. --
binder2nd binder1st . -
f()
f binary_function.5

26.2

. :
vector . -
vector<K> vt vt[j]
() j.
list
. list<K> lt lt
( lt.begin()) ( lt.end()).
it
( ++it) ( --it) , ,
.

5 C++11 bind2nd(), bind1st(), binder2nd, binder1st


binary_function ( ).
1006 26

deque -
. -
vector, -
.
S<K> -
- :
(fill constructors).6
explicit S<K>( size_type sz, const K& val = K() );
:
S<K> a( n, c );
n 0 c K a n c. -
,
list< Date > ld( 3, Date(2010, 1, 1) );
ld 1.1.2010. ( ) -
:
list< Date >( 3, Date(2010, 1, 1) )
:
S<K> a( n );
a n K(). , :
vector< Date > vd( 5 );
vt 1.1.1. ( )
: vector<Date>(5)
(range constructors).
template < class InputIterator >
S<K>( InputIterator first, InputIterator last );
:
S<K> a( j, k );
j, k (
) [j, k) K a
. ,
int v0[10] = { 0,1,2,3,4,5,6,7,8,9 };
int* p1( &v0[5] ); int* p2( &v0[8] );
deque< int > dqt( p1, p2 );
dqt 3 : 5, 6, 7.
, ,

: istream_iterators
array:
istream_iterator< unsigned int > cinIt( cin );
istream_iterator< unsigned int > cinEoStream;
vector< unsigned int > array( cinIt, cinEoStream );
sort( array.begin(), array.end() );
// . . .
(head) :
K& front();
const K& front() const;
( const.) ( )
() . : a.front() *(a.begin()).

6 ( ).
- Standard Template Library (STL) 1007

:
S<K>::iterator insert( S<K>::iterator pos, const K& val );
void insert( S<K>::iterator pos, size_type sz, const K& val );
template < class InputIterator >
void insert( S<K>::iterator pos,
InputIterator first, InputIterator last );
S<K>::iterator pos
.
val pos
size() 1.
.
H sz val pos
size() sz.
() [first, last)
pos size() last - first.
.
: -
. vector
. , -
insert()
() pos.
:
S<K>::iterator erase( S<K>::iterator pos );
S<K>::iterator erase( S<K>::iterator first,
S<K>::iterator last );
void clear();
pos size() 1.

.
[first, last).
last.
. a.clear() a.erase(
a.begin(), a.end() ).
:
.

void resize( size_type sz, K val = K() );
vt.resize( n, kv );
n < vt.size()
vt.erase( vt.begin()+n, vt.end() );
n > vt.size()
vt.insert( vt.end(), n-vt.size(), kv );
(
C++11):
(reversible) . ,
reverse_iterator rbegin(), rend().
( ) (back insertion).
( ):
K& S<K>::back();
1008 26

const K& S<K>::back();


a.back() *(--a.end()).
:
void S<K>::push_back( const & );
a.push_back( c ); a.back() c.

( ):
void S<K>::pop_back();

26.2.1 vector
. ,
STL, vector (-
) STL. -
; !
vector STL7 -
.
,
() vector.

12.3.5
double vectorSum( const double x[], int n, int from, int upto )
{
if ( x == 0 && n > 0 )
{ cerr << " vectorSum " << endl;
exit( EXIT_FAILURE ); }
//
double sum( 0 );
for ( int m(from); m <= upto; ++m ) sum += x[m];
return sum;
} // vectorSum
x[from] x[upto]
n double.
vector< double > vx;
, :
ut = vectorSum( &vx[0], vx.size(), 1, 2 );
&vx[0]8
vx.size().

vector :
template < class K, class Alloc = allocator<K> >
class vector;
:
vector :
( string) []
at().
K& operator[]( size_type n );
const K& operator[]( size_type n ) const;

7 C++03. STL C++11 .


8 , vector [].
- Standard Template Library (STL) 1009

K& at( size_type n );


const K& at( size_type n ) const;
( const .) string,
at() n size()
(std::)out_of_range.
string (21.10.1) vector -
(capacity): K -
vector<K>.
:
size_type capacity() const;
, a :
a.size() a.capacity()
a.size() a.capacity()
-
( renew()).
reserve()
.
vector
void reserve( size_type n );
n (a.capacity())
a.capacity() n.
a.
size(), resize(), capacity(), reserve()
o:

0: #include <iostream>
1: #include <vector>
2:
3: using namespace std;
4:
5: int main()
6: {
7: vector<int> av( 3 );
8:
9: cout << "capacity: " << av.capacity()
10: << " size: " << av.size() << endl;
11: for ( int i(0); i <= 6; ++i )
12: {
13: if ( i < av.size() ) av[i] = i*10;
14: else av.push_back( i*10 );
15: cout << "i: " << i << " capc: " << av.capacity()
16: << " size: " << av.size() << " ";
17: for ( int k(0); k < av.size(); ++k )
18: cout << av[k] << ' ';
19: cout << endl;
20: }
21:
22: av.reserve( 31 );
23: av.resize( 4 );
24: cout << "capacity: " << av.capacity()
25: << " size: " << av.size() << endl;
26: for ( int k(0); k < av.size(); ++k ) cout << av[k] << ' ';
27: cout << endl;
28: try { cout << av.at(5) << endl; }
29: catch( out_of_range& x )
30: { cout << x.what() << endl; }
31: }
1010 26

:
capacity: 3 size: 3
i: 0 capc: 3 size: 3 0 0 0
i: 1 capc: 3 size: 3 0 10 0
i: 2 capc: 3 size: 3 0 10 20
i: 3 capc: 6 size: 4 0 10 20 30
i: 4 capc: 6 size: 5 0 10 20 30 40
i: 5 capc: 6 size: 6 0 10 20 30 40 50
i: 6 capc: 12 size: 7 0 10 20 30 40 50 60
capacity: 31 size: 4
0 10 20 30
index out of range in function: vector:: at(size_t)
index: 5 is greater than max_index: 4
7 ()
3, 3 . 9 capacity:
3 size: 3. 3.
: av.size() av. capacity().
3 (i: 0, 1, 2) for va[i] (-
13) .
4 (3) av.push_back(i*10)
.
.
i: 3 av.size() 4 1
av.capacity() 6
! i: 6
: 1
. vector
16.13.3.
capacity: 31 size: 4
22 23. for 26
size: 4.
6
av.at(5) try. out_of_range
what() .

vector.
vector C++ :
template < class T, class Allocator = allocator<T> >
class vector
{
// . . .
public:
typedef T value_type;
// . . .
typedef value_type* iterator;
// . . .
typedef ptrdiff_t difference_type;
// . . .
: vector<T>::iterator T* -
. ,
.
, 20, :
cout << *(av.begin()+3) << endl;
vector<int>::iterator it1( av.begin() ),
it2( av.begin() );
it1 += 2;
- Standard Template Library (STL) 1011

it2 += 6;
vector<int>::difference_type dist( it2 - it1 );
cout << "dist: " << dist << endl;
:
30
*it1: 20 *it2: 60
dist: 4
:
vector
(insert) (erase)
( ) (
).
.

26.2.1.1 ,
vector; -
.
: v vector <K> n
K v.erase(f, l);.
( l
== v.end()) . l - f
~().
( ) .
l - f .
f v[j] l v[k] ( k - j = l - f),
. ;
v[k]..v[n-1] v[j] (copy(l,
v.end(), f)).
l - f
l - f.
: (n-1-k)
v[k+1] .
.
v ( ).
:
v[j] ,
.
. m -
v[k]. :
m ( n+m).
.
v[k]..v[n-1] v[k+m]..v[n+m-1] .
m v[k]..v[k+m-1].
(n-k) -
v[k] m .
:
-
n . -
bad_alloc.
1012 26


. , push_back()
insert() . pop_back().
()
template < class InputIterator >
void insert( S<K>::iterator pos,
InputIterator first, InputIterator last );
. first last -
. -
. , , istream_iterators
m . m
( m = 1).
bad_alloc, , -
. .

26.2.1.2 : vector<bool>
, 8
bool .
, STL vector bool:
template <class Allocator>
class vector<bool, Allocator>
, :
:
void flip();
b ~b
false true true false.
swap(), ,
:
static void swap( vector<bool>::reference ref1,
vector<bool>::reference ref2 );
. reference
bool& ( .)
:
vector reference
vector<K> K&. vector<bool> :
, , . -

8 ( ) . (
vector<bool>) reference.
:
0: #include <iostream>
1: #include <vector>
2: using namespace std;
3:
4: void display( ostream& tout, const vector<bool>& bv )
5: {
6: tout << boolalpha;
7: for ( int k(0); k < bv.size(); ++k ) tout << bv[k] << ' ';
8: tout << endl;
9: }
10:
11: int main ()
12: {
- Standard Template Library (STL) 1013

13: vector<bool> bv1( 3 ) , bv2( 2 );


14:
15: bv1[0] = true; bv1[1] = false; bv1[2] = true;
16: cout << "bv1: "; display( cout, bv1 );
17: bv1.flip();
18: cout << "bv1: "; display( cout, bv1 );
19:
20: bv2[0] = true; bv2[1] = false;
21: cout << "bv2: "; display( cout, bv2 );
22:
23: vector<bool>::swap( bv1[0], bv1[1] );
24: cout << "bv1: "; display( cout, bv1 );
25: vector<bool>::swap( bv2.front(), bv2.back() );
26: cout << "bv2: "; display( cout, bv2 );
27: vector<bool>::swap( bv1[1], bv2[1] );
28: cout << "bv1: "; display( cout, bv1 );
29: cout << "bv2: "; display( cout, bv2 );
30:
31: bv1.swap( bv2 );
32: cout << "bv1: "; display( cout, bv1 );
33: cout << "bv2: "; display( cout, bv2 );
34: }
:
bv1: true false true
bv1: false true false
bv2: true false
bv1: true false false
bv2: false true
bv1: true true false
bv2: false false
bv1: false false
bv2: true true false
:
bv1 bv1.
flip(); 17.
bv1 swap()
23 bv2
swap() 25.
swap() 27 .
, 31 swap(),
STL. : bv1
bv2 . bv2.swap(bv1);.

26.2.2 deque
deque ( deck) :
(double ended queue).
front(),
back(), push_back(), pop_back() push_front(), pop_front()
SListT (25.7.1):
:
void deque<K>::push_front( const K& val );
a.push_front( c ); a.front() c
*a.begin().
( ):
void deque<K>::pop_front();
1014 26

, push_back(),
pop_back().
, -
, deque
vector : deque reserve() capacity().

26.2.3 list
list:
template < class T, class Allocator = allocator<T> >
class list;
T.
list, deque, :
(: )
:
void splice( iterator pos, list<T,Allocator>& x );
void splice( iterator pos, list<T,Allocator>& x, iterator i);
void splice( iterator pos, list<T,Allocator>& x,
iterator first, iterator last );
l1, l2 list<K> :
l1.splice(it, l2);, it l1,
l1 l2
it. l2 .
l1.splice(it, l2, it2);, it l1
it2 l2, l1
it2 it l2.
l1.splice(it, l1, it2); l1.
l1.splice(it, l2, f, l);, it l1
f, l l2, l1
[f,l) l2 it
l2. l1. splice(it, l1, f, l);
l1. it [f,l).

:
void remove( const T& v );
template < class Predicate >
void remove_if( Predicate pred );
l3.remove( v ); l3
v.
pred(), T,
remove_if() .

:
0: #include <iostream>
1: #include <list>
2: using namespace std;
3:
4: template< typename K >
5: void display( ostream& tout, list<K>& lv )
6: {
7: for ( list<K>::iterator it(lv.begin());
- Standard Template Library (STL) 1015

8: it != lv.end(); ++it ) tout << *it << ' ';


9: tout << endl;
10: } // display
11:
12: struct Dec0
13: {
14: bool operator()( const int& v )
15: { return ( (0 <= v) && (v < 10) ); }
16: }; // Dec0
17:
18: int main ()
19: {
20: int ints[] = { 3, 23, 3, 19, 5, 19, 17, 7, 7, 17, 23 };
21: list<int> l3( ints, ints+11 );
22: display<int>( cout, l3 );
23:
24: l3.remove( 23 ); display<int>( cout, l3 );
25:
26: l3.remove( 7 ); display<int>( cout, l3 );
27:
28: l3.remove_if( Dec0() ); display<int>( cout, l3 );
29: }
:
3 23 3 19 5 19 17 7 7 17 23
3 3 19 5 19 17 7 7 17
3 3 19 5 19 17 17
19 19 17 17
24 23
. ,
26 7 .
12-16 (Dec0)
. 28
3, 3 5.
:
bool dec0( int v ) { return ( (0 <= v) && (v < 10) ); }
:
l3.remove_if( dec0() );


:
void unique();
template < class BinaryPredicate >
void unique( BinaryPredicate binaryPred );
it
(*it, *(it-1)). -
it.
, *it, *(it-1). -
true it. -
, .

:
0: #include <iostream>
1: #include <list>
2: using namespace std;
3:
4: template< typename K >
5: void display( ostream& tout, list<K>& lv )
1016 26

6: //
7:
8: struct NotInOrder
9: {
10: bool operator()( const int& v1, const int& v2 )
11: { return ( v1 > v2 ); }
12: }; // NotInOrder
13:
14: int main ()
15: {
16: int ints[] = { 2, 2, 2, 3, 3, 5, 5, 5, 5, 2, 2, 3 };
17: list<int> l4( ints, ints+12 );
18: display<int>( cout, l4 );
19:
20: l4.unique(); display<int>( cout, l4 );
21:
22: l4.unique( NotInOrder() ); display<int>( cout, l4 );
23: }
:
2 2 2 3 3 5 5 5 5 2 2 3
2 3 5 2 3
2 3 5
20; 2 -
(2) 3 5. 2,
, 2
.
NotInOrder true
. 24
2 5 , 3
5.

:
void sort();
template < class Compare >
void sort( Compare comp );
list<K> <
K.
< K
-
(< K) . a < b
a b.

:
Date dates[] = { Date(1821,3,25), Date(1940,10,28),
Date(1904,10,13), Date(1453,5,29),
Date(1912,10,26) };
list<Date> dateList( dates, dates+5 );
:
dateList.sort();
display<Date>( cout, dateList );
:
29.5.1453 25.3.1821 13.10.1904 26.10.1912 28.10.1940
,
. -
. :
- Standard Template Library (STL) 1017

struct MonthFirst
{
bool operator()( const Date& d1, const Date& d2 )
{
bool fv( false );
if ( d1.getMonth() < d2.getMonth() ) fv = true;
else if ( d1.getMonth() == d2.getMonth() )
{
if ( d1.getDay() < d2.getDay() ) fv = true;
else if ( d1.getDay() == d2.getDay() )
fv = ( d1.getYear() < d2.getYear() );
}
return fv;
}
}; // MonthFirst
:
dateList.sort( MonthFirst() );
display<Date>( cout, dateList );
:
25.3.1821 29.5.1453 13.10.1904 26.10.1912 28.10.1940
, , (
) :
struct Decr
{
bool operator()( const Date& d1, const Date& d2 )
{ return ( d2 < d1 ); }
}; // Decr
:
dateList.sort( Decr() );
display<Date>( cout, dateList );
:
28.10.1940 26.10.1912 13.10.1904 25.3.1821 29.5.1453

l.sort() sort(l.begin(), l.end());


(stable):
.
.
( ) -
:
void merge( list& x );
template < class Compare >
void merge( list& x, Compare comp );
list<K> l1, l2 l1, l2 <
K l1.merge(l2); ( ) l1
l2. :
l1 l1, l2
< K.
l2 .
l1, l2
.
(std::)merge() :
l1.merge(l2); l2 () (-)
l1 .
:
1018 26

void reverse();
, :
int ints[] = { 3, 23, 3, 19, 5, 19, 17, 7, 7, 17, 23 };
list<int> l3( ints, ints+11 );
display<int>( cout, l3 );

l3.reverse(); display<int>( cout, l3 );


:
3 23 3 19 5 19 17 7 7 17 23
23 17 7 7 17 19 5 19 3 23 3

26.2.4 ;
: vector! , -
.
deque - /
.
list - /
( ).

26.3
(associative memory) (con-
tent-addressable memory)

(). (asso-
ciative containers) STL.
:
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> >
class set;
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T> > >
class map;
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> >
class multiset;
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T> > >
class multimap;
- (Key) -
. - Compare -
< Key. Key
<
less<Key>.9
<
(binary search tree).10

9 less 25.6.3.
10 red-black.
- Standard Template Library (STL) 1019

, , -
(ordered) .11

() .
STL, -
:
.
size_type A<K>::count( const K& x ) const;
, A set map count() 0 1.12
:
A<K>::iterator A<K>::find( const K& x );
A<K>::const_iterator A<K>::find( const K& x ) const;
x -
. A<K>::end().
.
:
void A<K>::erase( A<K>::iterator pos );
size_type A<K>::erase( const K& x );
void A<K>::erase( A<K>::iterator first, A<K>::iterator last );
void A<K>::clear();
pos.
x.
count(x)
.
[first,
last).
erase( begin(), end() )
.
:
A<K>::iterator A<K>::lower_bound( const K& x );
A<K>::const_iterator A<K>::lower_bound( const K& x ) const;
x.
lower_bound() 26.1.3.
(-) (-) x
( ) .
A<K>::iterator A<K>::upper_bound( const K& x );
A<K>::const_iterator A<K>::upper_bound( const K& x ) const;

x.
pair< A<K>::iterator, A<K>::iterator > A<K>::equal_range( const K& x );
pair< A<K>::const_iterator, A<K>::const_iterator >
A<K>::equal_range( const K& x ) const;
13 f, l [f, l) x.
( ).

11 C++11 - /.
12 A<K> A<K,C> A<K,C,T>.
.
1020 26

lb (lower_bound()), ub (upper_bound())
eqr (equal_range()) eqr.first == lb eqr.second == ub. :
#include <iostream>
#include <functional>
#include <set>
using namespace std;
int main()
{
int ints[] = { 3, 23, 3, 19, 5, 19, 17, 7, 7, 17, 23 };
multiset<unsigned int> ms( ints, ints+11 );
typedef multiset<unsigned int>::iterator msIterator;

msIterator lb( ms.lower_bound(17) );


msIterator ub( ms.upper_bound(17) );
pair<msIterator, msIterator> eqr( ms.equal_range(17) );
if ( lb == eqr.first ) cout << "lb == eqr.first" << endl;
if ( ub == eqr.second ) cout << "ub == eqr.second" << endl;
}

lb == eqr.first
ub == eqr.second
-
:
C A<K,C>::key_comp() const;
.

:

.

(insert()). :
.

26.3.1 set
set :
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> >
class set;
(sets).
.
set -
.
:
#include <set>
:
set< T > s;
s T. s . ..
set< int > intSet;
// intSet == { }
cout << "#intSet == " << intSet.size() << endl;

13 (std::)pair PairT 25.3.1.


- Standard Template Library (STL) 1021

if ( intSet.empty() ) cout<< "intSet == {}" << endl;


else cout<< "intSet != {}" << endl;
:
#intSet == 0
intSet == {}
0 (cardinality) intSet intSet.size().
intSet.empty() true , intSet .
intSet.clear() intSet.

STL:
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
vector< int > intVec( intArr+3, intArr+7 );
// . . .
set< int > intSet1( intVec.begin(), intVec.end() );
copy( intSet1.begin(), intSet1.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
set< int > intSet2( intArr, intArr+5 );
copy( intSet2.begin(), intSet2.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
-11 8 31 41
-23 -11 8 34 72

. .
x s (x s)
:
lower_bound(). *(s.lower_bound(x)) == x true
x s.
if ( *(intSet1.lower_bound(31)) == 31 )
cout << "31 in intSet1" << endl;
else
cout << "31 not in intSet1" << endl;
if ( *(intSet1.lower_bound(61)) == 61 )
cout << "61 in intSet1" << endl;
else
cout << "61 not in intSet1" << endl;
:
31 in intSet1
61 not in intSet1
find(). s.find(x) s.end() x
s. it, set<int> ::iterator ( int
), *it == x.

if ( intSet1.find(31)==intSet1.end() )
cout << "31 not in intSet1" << endl;
else
cout << "31 in intSet1" << endl;
if ( intSet1.find(61)==intSet1.end() )
cout << "61 not in intSet1" << endl;
else
cout << "61 in intSet1" << endl;
count(). s.count(x) 0 x s
1.
if ( intSet1.count(31)==0 ) cout << "31 not in intSet1" << endl;
1022 26

else cout << "31 in intSet1" << endl;


if ( intSet1.count(61)==0 ) cout << "61 not in intSet1" << endl;
else cout << "61 in intSet1" << endl;
.
set<Date>
dates -
.
:
erase()

insert() set<K>:
pair< set<K>::iterator, bool > insert( const K& x );
set<K>::iterator insert( set<K>::iterator position, const K& x );
template < class InputIterator >
void insert( InputIterator first, InputIterator last );
(pair)
first set<K>::iterator
x.
second bool true false
.
: insert(it,v)
it v! -
it 14
. set<K>::iterator
x.
[first, last).
:
set<int> intSet;
pair< set<int>::iterator, bool > retVal( intSet.insert(17) );
cout << boolalpha
<< *(retVal.first) << " " << retVal.second << endl;
:
17 true
retVal.first intSet 17.
true retVal.second .

int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
:
intSet.insert( intArr, intArr+4 );
copy( intSet.begin(), intSet.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
-23 8 17 34 72
:
retVal = intSet.insert( 8 );
cout << *(retVal.first) << " " << retVal.second << endl;
:

14 C++11 it
.
- Standard Template Library (STL) 1023

8 false
retVal.first retVal
.second false: 8 intSet.
:
set<int>::iterator it;
it = intSet.insert( retVal.first, 11 );
cout << *it << endl;
:
11
: insert() 11.
8. -
11.
, :
int n( intSet.erase(72) );
cout << n << endl;
copy( intSet.begin(), intSet.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
intSet.erase( intSet.begin(), intSet.find(17) );
copy( intSet.begin(), intSet.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
1
-23 8 11 17 34
17 34
intSet.erase(72) ( n)
. 1
72 .

17.
, set: set<K>::
iterator it set<K>::const_iterator it -
*it. ; set
.
*it -
.15 *it :
K temp( *it );
oneSet.erase( it );
// temp
oneSet( temp );
K .
: map
.

26.3.1.1
( , ) (),
(), \ () ( )
.
#include <algorithm>.

15 Borland C++ v.5.5 *it!


.
1024 26

A B ( B includes A) includes()
algorithm:
template< class InputIter1, class InputIter2 >
bool includes( InputIter1 first1, InputIter1 last1,
InputIter2 first2, InputIter2 last2 );
template< class InputIter1, class InputIter2,
class Compare >
bool includes( InputIter1 first1, InputIter1 last1,
InputIter2 first2, InputIter2 last2,
Compare comp);
:
#include <set>
#include <algorithm>
// . . .
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
// . . .
set<int> intSet1( intArr, intArr+3 );
copy( intSet1.begin(), intSet1.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
set<int> intSet2( intArr, intArr+7 );
copy( intSet2.begin(), intSet2.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
if ( includes(intSet2.begin(), intSet2.end(),
intSet1.begin(), intSet1.end()) )
cout << "intSet2 includes intSet1" << endl;
else
cout << "intSet2 does not include intSet1" << endl;
:
-23 34 72
-23 -11 8 31 34 41 72
intSet2 includes intSet1
A B (proper strict subset) -
(A B) && (A != B).
:
: -
, , . -
.
STL,
! , :
// . . .
istream_iterator< int > cinIt( cin ), cinEoStream;
if ( includes(intSet2.begin(), intSet2.end(),
cinIt, cinEoStream) )
cout << "intSet2 includes input" << endl;
// . . .
:
-11 8 31 e
:
intSet2 includes input
:
// . . .
copy( intArr+4, intArr+7, ostream_iterator<int>(cout, " ") );
cout << endl;
if ( includes(intSet2.begin(), intSet2.end(),
intArr+4, intArr+7) )
cout << "intSet2 includes [intArr+4, intArr+7)" << endl;
- Standard Template Library (STL) 1025

// . . .
:
-11 31 41
intSet2 includes [intArr+4, intArr+7)
, :
deque<int> intDeque( intArr+1, intArr+6 );
sort( intDeque.begin(), intDeque.end() );
copy( intDeque.begin(), intDeque.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
if ( includes(intSet2.begin(), intSet2.end(),
intDeque.begin(), intDeque.end()) )
cout << "intSet2 includes intDeque" << endl;
:
-23 -11 8 31 72
intSet2 includes intDeque
: includes() sort()
intDeque. :
:
72 -23 8 -11 31
intSet2 does not include intDeque

includes() gcc ( stl_algo.h):16
0: template< typename InputIter1, typename InputIter2 >
1: bool includes( InputIter1 first1, InputIter1 last1,
2: InputIter2 first2, InputIter2 last2 )
3: {
4: while( first1 != last1 && first2 != last2 )
5: if( *first2 < *first1 )
6: return false;
7: else if( *first1 < *first2 )
8: ++first1;
9: else
10: { ++first1; ++first2; }
11:
12: return first2 == last2;
13: }
, 5: 34 < 72
.
5 :
if( comp(*first2,*first1) )
7:
else if( comp(*first1,*first2) )
includes():
. 17
.
comp().

. #include <algorithm> -
:

16 ; (9.5.3).
17 ;
, .. .
1026 26

(std::)set_union ( ),
(std::)set_intersection ( ),
(std::)set_difference ( )
(std::)set_symmetric_difference ( ).18
. , , :
template< class InputIter1, class InputIter2, class OutputIterator >
OutputIterator set_union( InputIter1 first1, InputIter1 last1,
InputIter2 first2, InputIter2 last2,
OutputIterator result );
template< class InputIter1, class InputIter2,
class OutputIterator, class Compare >
OutputIterator set_union( InputIter1 first1, InputIter1 last1,
InputIter2 first2, InputIter2 last2,
OutputIterator result, Compare comp );
( ) .
;
.
result
. -
.
.
:
set< int > intSet1, intSet2;
{ 4, 5, 6 } { 2, 4, 6, 8, 10 } .
cout:
set_union( intSet1.begin(), intSet1.end(),
intSet2.begin(), intSet2.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
2 4 5 6 8 10
:
vector<int> intVec1(11);
:
set_union( intSet1.begin(), intSet1.end(),
intSet2.begin(), intSet2.end(),
intVec1.begin() );
copy( intVec1.begin(), intVec1.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
2 4 5 6 8 10 0 0 0 0 0
; 11
6. :
vector<int> intVec1;
;
26.1.3:
back_insert_iterator< vector<int> > destV( intVec1 );
:

18 A, B A B = (A\B) (B\A)
A B B A. : A B = (AB)\(AB).
- Standard Template Library (STL) 1027

set_union( intSet1.begin(), intSet1.end(),


intSet2.begin(), intSet2.end(),
destV );

set<int> intSet3;
; , : back_insert_iterator
push_back(). -
insert()
inserter. #include
<iterator>.
:
set_union( intSet1.begin(), intSet1.end(),
intSet2.begin(), intSet2.end(),
inserter(intSet3, intSet3.begin()) );
intSet3.
() .
, :
template< class InputIter1, class InputIter2, class OutputIter >
OutputIterator set_intersection(InputIter1 first1, InputIter1 last1,
InputIter2 first2, InputIter2 last2,
OutputIter result );
template< class InputIter1, class InputIter2,
class OutputIter, class Compare >
OutputIterator set_intersection(InputIter1 first1, InputIter1 last1,
InputIter2 first2, InputIter2 last2,
OutputIter result, Compare comp );
.

26.3.2 map
set STL .
(map) :
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T> > >
class map;

#include <map>
set : class T. ;
:
pair< Key, T >
(Key) ( ) (key type)
(T) (value type). , :
Key first;
T second;
map<Key, T> set< pair<Key, T> >; !
(map) first
( ) .19 second
. set< pair<Key, T> >
.

19 Borland C++ v.5.5 -


.
1028 26

, Project 4, CourseCollection
Course. Course* ccArr
map .
:
struct CourseKey
{
enum { cCodeSz = 8 };
char s[cCodeSz];
explicit CourseKey( string aKey="" )
{ strncpy( s, aKey.c_str(), cCodeSz-1 );
s[cCodeSz-1] = '\0'; }
}; // CourseKey
:
class CourseVal
{
public:
enum { cTitleSz = 80, cCategSz = 4 };
explicit CourseVal( string aTitle="" );
// . . .
void display( ostream& tout ) const;
private:
char cTitle[cTitleSz]; //
// . . .
unsigned int cNoOfStudents; // .
}; // Course
:
pair< CourseKey, CourseVal >
CourseKey < -
:
struct CodeLT
{
bool operator()( const CourseKey& ck1, const CourseKey& ck2 )
{ return ( strcmp(ck1.s, ck2.s) < 0 ); }
}; // CodeLT
, :
map< CourseKey, CourseVal, CodeLT > ccCourses;
:
CourseKey aCk( "0201" );
CourseVal aCv( " ()" );
ccCourses:
ccCourses.insert( make_pair(aCk, aCv) );

map<CourseKey, CourseVal, CodeLT>::iterator it;
it ccCateg:
(it->second).setCateg( "" );

[] CourseCollection
allCourses["0201"] map.


.
0: #include <iostream>
1: #include <string>
- Standard Template Library (STL) 1029

2: #include <map>
3:
4: using namespace std;
5:
6: int main()
7: {
8: string monthN[] = { "Jan", "Feb", "Mar", "Apr",
9: "May", "Jun", "Jul", "Aug",
10: "Sep", "Oct", "Nov", "Dec" };
11: unsigned int noOfDays[] = { 31, 28, 31, 30, 31, 30,
12: 31, 31, 30, 31, 30, 31 };
13: map< string, unsigned int > months;
14:
15: for ( int k(0); k < 6; ++k )
16: {
17: pair<string, unsigned int> amp;
18: amp.first = monthN[k];
19: amp.second = noOfDays[k];
20: months.insert( amp );
21: }
22: for ( int k(6); k < 12; ++k )
23: months[monthN[k]] = noOfDays[k];
24:
25: for ( map<string, unsigned int>::const_iterator
26: cit( months.begin() );
27: cit != months.end(); ++cit )
28: cout << cit->first << ", " << cit->second << endl;
29: }
15-21 6
pair<string, unsigned int> insert().
22-23 6 :
months["Jul"] = 31;
months["Aug"] = 31;
// . . .
months["Dec"] = 31;
months["Jul"] = 31 months.insert(make_pair
("Jul",31)).
cout cit -
first second . -
:
Apr, 30
Aug, 31
Dec, 31
Feb, 28
Jan, 31
Jul, 31
Jun, 30
Mar, 31
May, 31
Nov, 30
Oct, 31
Sep, 30
. 25-28
:
for ( int k(0); k < 12; ++k )
cout << monthN[k] << ", " << months[monthN[k]] << endl;
[], :
Jan, 31
Feb, 28
Mar, 31
Apr, 30
1030 26

May, 31
Jun, 30
Jul, 31
Aug, 31
Sep, 30
Oct, 31
Nov, 30
Dec, 31

insert() map
set.
includes(), set_union(), set_intersection(), set_difference() set_symmet-
ric_difference() map set.

26.3.3 multiset multimap


#include <set> -
multiset :
template < class Key, class Compare = less<Key>,
class Allocator = allocator<Key> >
class multiset;
(multi-
sets, bags). , -
. , (x $ m)20,
(multiplicity, multitude) multiset
count().
:
multiset< int > mulSet1;
([ ]).
cout << "#mulSet1 == " << mulSet1.size() << endl;
if ( mulSet1.empty() ) cout<< "mulSet1 == [[]]" << endl;
else cout<< "mulSet1 != [[]]" << endl;
:
#mulSet1 == 0
mulSet1 == [[]]
[ 1, 2, 4, 3, 2, 4, 4 ] :
int intArr[] = { 1, 2, 4, 3, 2, 4, 4 };

multiset< int > mulSet2( intArr, intArr+7 );


copy( mulSet2.begin(), mulSet2.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
1 2 2 3 4 4 4
2 7 mulSet2 :
cout << "mulSet2 # 2 = " << mulSet2.count(2) << endl;
cout << "mulSet2 # 7 = " << mulSet2.count(7) << endl;
:
mulSet2 # 2 = 2
mulSet2 # 7 = 0
multiset insert():

20 Z.
- Standard Template Library (STL) 1031

multiset<K>::iterator multiset<K>::insert( const K& x );


multiset<K>::iterator multiset<K>::insert( multiset<K>::iterator pos,
const K& x );
template < class InputIterator >
void insert( InputIterator first, InputIterator last );
x.
1.
.
x
. (pos) -
, .
[first, last).
includes(), set_union(), set_intersection(), set_difference() set_symmet-
ric_difference() multiset.
:
1. (U) (I) M1 M2
U # v = max(M1 # v, M2 # v) I # v = min(M1 # v, M2 # v).
(.. Z)
(bag sum) S # v = M1 # v + M2 # v.
2. (D) M1 \ M2 D # v = (M1 #
v > M2 # v) ? M1 # v M2 # v : 0.
#include <map> -
:
template < class Key, class T, class Compare = less<Key>,
class Allocator = allocator<pair<const Key, T> > >
class multimap;
map multimap
:
pair< Key, T >

26.3.4
( ) . ,
-
. ;
<
. , -
K <.

:
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };

set< int > intSet( intArr, intArr+7 );


copy( intSet.begin(), intSet.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;

set< int, greater<int> > intSetG( intArr, intArr+7 );


copy( intSetG.begin(), intSetG.end(),
ostream_iterator<int>(cout, " ") );
cout << endl;
:
-23 -11 8 31 34 41 72
72 41 34 31 8 -11 -23
1032 26

.
(greater <int>)
.
( functional)
template < class T >
struct greater : public binary_function<T, T, bool>
{
bool operator() (const T& x, const T& y) const { return x > y; }
};
: greater(5,2) greater(0.5, 1.2)
true false . ,
> T.
; :
( ).
.
:
struct cstrGT
{
bool operator()( const char cs1[], const char cs2[] )
{
return strcmp(cs1, cs2) > 0;
}
};

int main()
{
set<const char*, cstrGT> css;
css.insert( "" ); css.insert( "" );
css.insert( "" ); css.insert( "" );
css.insert( "" ); css.insert( "" );
css.insert( "" ); css.insert( "" );
css.insert( "" );
copy( css.begin(), css.end(),
ostream_iterator<const char*>(cout, " ") );
cout << endl;
:

:
struct cstrLT
{
bool operator()( const char cs1[], const char cs2[] )
{
return strcmp(cs1, cs2) < 0;
}
};

set<const char*, cstrLT> css;


:

:
set< T > s;

set< T, less<T> > s;
T <.
- Standard Template Library (STL) 1033

set -
min(), max(), sort() . -
, comp() <; :
a < b a b.
: a b.
comp(a, b) true a b.
comp() .
< comp()
==: !(a<b) && !(b<a) !comp(a,b) && !comp(b,a).
a b (equivalent)
== ( ).
lower_bound() 26.1.3 comp
(: ) .
. :

(comp less<T>)
.

26.4 ;
; :
;
:
vector vector! !
: 9.5.1 ,
.
set
map.

vector list. ,
.
vector
. , vector
-
.
/
.
.

:
(-
)
set
map.

/ multiset multimap,
() vector.
1034 26

-
vector set/map. ,
:
.

26.5
:
bitset, complex.21

26.5.1 bitset
#include <bitset> -

template < size_t N >
class bitset;
Bitmap (
) : N
.
vector<bool>;
bitset
N

push_back().
&=, |=, =, , [], <<=, >>=,==,
!= &, |, .
<<, >>
:
bitset<N> operator<<(size_t pos) const;
bitset<N> operator>>(size_t pos) const;
/:
template < size_t N >
istream& operator>>( istream& is, bitset<N>& x );
template < size_t N >
ostream& operator<<( ostream& os, const bitset<N>& x );
:
:
bitset();
0:
bitset<12> bsd;
cout << bsd << endl;
:
000000000000
unsigned long int:
bitset( unsigned long val );
:
bitset<12> bsu0( 21UL ), bsu1( 1000000UL );
cout << bsu0 << endl << bsu1 << endl;

21 valarray .
- Standard Template Library (STL) 1035

bitset<32> bsu2( 1000000UL );


cout << bsu2 << endl;
:
000000010101
001001000000
00000000000011110100001001000000
21 (16+4+1)
12 ( ).
1 (32 ).
; 12
bsu1!
:
(N)
( ).
.
string:
explicit bitset( const string& str, size_type pos=0, size_type n=npos );
0 1. -
(std::)invalid_argument. (n -
pos).
bitset<12> bss0( string("100100101010") ),
bss1( string("100100101") ),
bss2( string("1111111001001010100101010") );
cout << bss0 << endl << bss1 << endl << bss2 << endl;
:
100100101010
000100100101
010100101010
bss0 ( 0 1) 12.
bss0.
9 0
.
12.
12 .
( ) Bitmap bitset:
bitValue() [] :
bitset<N>::reference operator[]( size_t pos );
bool operator[]( size_t pos ) const;
bitset<N>::reference 26.2.1.2
vector<bool>::reference.
bool
bool test( size_t pos ) const;
setBit()
bitset<N>& set( size_t pos, int val=1 );

0.
set()
bitset<N>& set();
1 *this.
1036 26

clearBit()
bitset<N>& reset( size_t pos );
set() 0.
reset()
bitset<N>& reset();
*this.
count1()
size_t count() const;
display() <<
.
part(), firstBitSet() .
bitset:
:
bitset<N>& flip( size_t pos );
(01 10) pos *this

bitset<N>& flip();
*this . bs1 = ~bs0 bs1 =
bs0.flip() .
unsigned long int:
unsigned long to_ulong() const;
unsigned long int
*this. -
long (std::)overflow_error.
string:
string to_string() const;
string
0 1.
:
bool any() const;
true *this .
:
bool none() const;
true *this .
:
: , bits set ; ( )
: Project 4 Course
. scN-
OfStudents scArr.
: Course :
Bitset<allStudents.getNOfStudents()> cEnrolled;
scArr[k] crs
crs.cEnrolled[k] 1 0.
cNoOfStudents :
unsigned int Course::getNoOfStudents() const
{ return cEnrolled,count(); }
- Standard Template Library (STL) 1037

;
:
.

26.5.2 complex
#include <complex>

template< class T >


class complex
{
public:
typedef T value_type;
complex( const T& re=T(), const T& im=T() );
complex( const complex& );
template<class X> complex( const complex<X>& );
T real() const;
T imag() const;
complex<T>& operator=( const T& );
complex<T>& operator+=( const T& );
complex<T>& operator-=( const T& );
complex<T>& operator*=( const T& );
complex<T>& operator/=( const T& );
complex& operator=( const complex& );
template<class X> complex<T>& operator=( const complex<X>& );
template<class X> complex<T>& operator+=( const complex<X>& );
template<class X> complex<T>& operator-=( const complex<X>& );
template<class X> complex<T>& operator*=( const complex<X>& );
template<class X> complex<T>& operator/=( const complex<X>& );
}; // complex
.
complex float, double
long double.
, :
+, -, *, /.
abs() arg()
template< class T > T abs( const complex<T>& x )
{ return sqrt( x.real()*x.real()+x.imag()*x.imag() ); }
template< class T > T arg( const complex<T>& x )
{ return atan2( imag(x), real(x) ) }
.
()
template< class T >
complex<T> polar( const T& rho, const T& theta = 0 );
. :
x == polar( abs(x), arg(x) )
, , ==
.

template< class T > complex<T> conj( const complex<T>& x );
x.
sqrt(), pow(), cos(), sin(), tan(), exp(), log(), log10(), cosh(),
sinh().
1038 26

26.6 ( )
STL , , -
( vector ).
STL vector, list, deque () set, map, multiset
multimap ().
( )
vector. -
.

.
, , , .
-
. : STL
.
STL, ,
( ).
.
first, last *it
it [first, last).
C++
. : bitset complex.

26-1
vector < T > v1;
:
set< T > s1( v1.begin(), v1.end() );
vector< T > v2( s1.begin(), s1.end() );
( ) v1 -
v2;
26-2 :
eqmult(): eqmult(v, M1, M2) true M1, M2
v.
(scaling): n M1 (n: ) -
M1 n- M1.
-
multiset, multimap.
project

7
STL
:
Prj07.1 STL I: vector ............................................................................................................. 1040
Prj07.1.1 Course .........................................................................................................................................1040
Prj07.1.2 CourseCollection........................................................................................................................1040
Prj07.1.2.1 getArr()............................................................................................................................. 1043
Prj07.1.3 Student ........................................................................................................................................1044
Prj07.1.4 StudentCollection.......................................................................................................................1046
Prj07.1.5 StudentInCourse ........................................................................................................................1049
Prj07.1.6 StudentInCourseCollection .......................................................................................................1049
Prj07.1.7 - .............................................................................................................................1051
Prj07.2 STL II ......................................................................................................................... 1052
Prj07.2.1 ..................................................................................................................................................1052
Prj07.2.1.1 ccArr CourseCollection ..................................................................................................................... 1052
Prj07.2.1.2 sCourses Student .............................................................................................................................. 1053
Prj07.2.1.3 scArr StudentCollection .................................................................................................................... 1053
Prj07.2.1.4 siccArr StudentInCourseCollection ................................................................................................. 1053
Prj07.2.1.5 - ................................................................................................................................... 1054
Prj07.2.2 Course .........................................................................................................................................1054
Prj07.2.3 CourseCollection........................................................................................................................1054
Prj07.2.4 Student ........................................................................................................................................1057
Prj07.2.5 StudentCollection.......................................................................................................................1058
Prj07.2.6 StudentInCourseCollection .......................................................................................................1061
Prj07.2.6.1 SICKeyLT ..................................................................................................................... 1064
Prj07.2.7 ..............................................................................................................................1065
Prj07.3 .......................................................................................................... 1066

:
Project
STL. Project 4
:
vector.
.
, -
: public
.
:
(-).
.
private .

1039
1040 Project 07

,
: (,
, ccArr CourseCollection).

Prj07.1 STL I: vector


Project 4
vector . -
STL.

Prj07.1.1 Course
Course .

Prj07.1.2 CourseCollection
ccArr:
vector<Course> ccArr;
ccIncr, ccNOfCourses, ccReserved . getNOfCourses() :
size_t getNOfCourses() const { return ccArr.size(); }
getArr() ; :
const Course* getArr() const { return &ccArr[0]; }

, :
CourseCollection() { };
! ,
:
~CourseCollection() { };
() - findNdx()
. linSearch() ( STL) -
(std::)find():
vector<Course>::iterator CourseCollection::findNdx( string code )
{
vector<Course>::iterator ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = ccArr.end();
else
ndx = find( ccArr.begin(), ccArr.end(), Course(code) );
return ndx;
} // CourseCollection::findNdx
findNdx() int ccArr (
ccArr[ndx]). :
ccArr[ndx] *ndx
ccArr[ndx].X ndx->X
, ++ccNOfCourses --ccNOfCourses
.
:
findNdx -
find index ( ).
findIt find iterator
( ).
STL 1041

:
bool find1Course( const string& code ) const
{ return ( findNdx(code) != ccArr.end() ); };
delete1Course():
void CourseCollection::delete1Course( string code )
{
vector<Course>::iterator ndx( findNdx(code) );
if ( ndx != ccArr.end() ) //
{
vector<Course>::iterator k;
k = find_if( ccArr.begin(), ccArr.end(),
bind2nd(EqPrereq(),code) );
if ( k != ccArr.end() )
throw CourseCollectionXptn( "delete1Course",
CourseCollectionXptn::prereqRef,
code.c_str() );
int enrStdnt( ndx->getNoOfStudents() );
if ( enrStdnt > 0 ) //
throw CourseCollectionXptn( "delete1Course",
CourseCollectionXptn::enrollRef,
code.c_str(), enrStdnt );
erase1Course( ndx );
}
} // CourseCollection::delete1Course
, ndx,
: 26.1.4. k
vector<Course>::iterator ccArr, ccArr+ccNOfCourses
ccArr.begin(), ccArr.end() . EqPrereq :
struct EqPrereq : binary_function< Course, string, bool >
{
bool operator()( const Course& x, const string& y ) const
{ return ( strcmp(x.getPrereq(), y.c_str()) == 0 ); }
}; // EqPrereq

void CourseCollection::erase1Course( vector<Course>::iterator ndx )
{
*ndx = ccArr.back();
ccArr.pop_back();
} // CourseCollection::erase1Course
add1Course():
void CourseCollection::add1Course( const Course& aCourse )
{
if ( strlen(aCourse.getCode()) != Course::cCodeSz-1 )
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::entity );
vector<Course>::iterator ndx( findNdx(aCourse.getCode()) );
if ( ndx == ccArr.end() ) //
{
if ( strcmp(aCourse.getPrereq(), "") != 0 ) //
{ //
vector<Course>::iterator ndx(
findNdx(aCourse.getPrereq()) );
if ( ndx == ccArr.end() ) //
//
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::prereqRef,
aCourse.getPrereq() );
}
//
insert1Course( aCourse );
ndx = findNdx( aCourse.getCode() );
ndx->clearStudents();
1042 Project 07

}
} // CourseCollection::add1Course
:
void CourseCollection::insert1Course( const Course& aCourse )
{
try { ccArr.push_back( aCourse ); }
catch ( bad_alloc& )
{ throw CourseCollectionXptn( "insert1Course",
CourseCollectionXptn::allocFailed ); }
} // CourseCollection::insert1Course
, , . ,
.
:
const Course& CourseCollection::get1Course( string code ) const
{
vector<Course>::const_iterator ndx( findNdx(code) );
if ( ndx == ccArr.end() )
throw CourseCollectionXptn( "get1Course",
CourseCollectionXptn::notFound,
code.c_str() );
return *ndx;
} // CourseCollection::get1Course
const_iterator ndx: const
.
-
void CourseCollection::swap( CourseCollection& rhs )
{
ccArr.swap( rhs.ccArr );
} // CourseCollection::swap
.
:
void CourseCollection::save( ofstream& bout ) const
{
if ( bout.fail() )
throw CourseCollectionXptn( "save",
CourseCollectionXptn::fileNotOpen );
size_t ccNOfCourses( ccArr.size() );
bout.write( reinterpret_cast<const char*>(&ccNOfCourses),
sizeof(ccNOfCourses) );
for ( vector<Course>::const_iterator it(ccArr.begin());
it != ccArr.end(); ++it )
it->save( bout );
if ( bout.fail() )
throw CourseCollectionXptn( "save",
CourseCollectionXptn::cannotWrite );
} // CourseCollection::save
:
void CourseCollection::load( ifstream& bin )
{
CourseCollection tmp;
size_t n; //ccNOfCourses

bin.read( reinterpret_cast<char*>(&n), sizeof(size_type) );


if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Course oneCourse;
oneCourse.load( bin );
tmp.insert1Course( oneCourse );
}
STL 1043

if ( bin.fail() )
throw CourseCollectionXptn( "load",
CourseCollectionXptn::cannotRead );
swap( tmp );
}
} // CourseCollection::load
load() . tmp CourseCol-
lection. vector<Course> tmp :
tmp.insert1Course(oneCourse) tmp.push_back(oneCourse)
swap(tmp) ccArr.swap(tmp)
.
display() for. k <
ccArr.size().
add1Student() delete1Student() Course
:
void CourseCollection::add1Student( string code )
{
vector<Course>::iterator ndx( findNdx(code) );
if ( ndx == ccArr.end() ) //
throw CourseCollectionXptn( "add1Student",
CourseCollectionXptn::notFound,
code.c_str() );
ndx->add1Student();
} // CourseCollection::add1Student

void CourseCollection::delete1Student( string code )


{
vector<Course>::iterator ndx( findNdx(code) );
if ( ndx == ccArr.end() ) //
throw CourseCollectionXptn( "delete1Student",
CourseCollectionXptn::notFound,
code.c_str() );
ndx->delete1Student();
} // CourseCollection::delete1Student

Prj07.1.2.1 getArr()
CourseCollection::getArr()
20.7.5
5. getAllStops().

, -
.
.1
, ccArr:
void CourseCollection::getArr( vector<Course>& crsArr ) const
{
try { crsArr = ccArr; }
catch( bad_alloc& )
{ throw CourseCollectionXptn( "getArr",
CourseCollectionXptn::allocFailed ); }
} // CourseCollection::getArr
RAII. :
CourseCollection allCourses;
// . . .
vector<Course> courseTbl;

1 , , , .
1044 Project 07

// . . .
allCourses.getArr( courseTbl );
courseTbl.
.
,
.
.
.

Prj07.1.3 Student
Student
:
enum { sIncr = 3 };
size_t sNoOfCourses; //
Course::CourseKey* sCourses;
size_t sReserved;

vector<Course::CourseKey> sCourses;
:
unsigned int getNoOfCourses() const { return sCourses.size(); }
void clearCourses() { sCourses.clear(); sWH = 0; }
, ++sNoOfCourses --sNoOfCourses
.
getCourses() CourseCollection getArr():
void Student::getCourses( vector<Course::CourseKey>& crsTbl ) const
{
try { crsTbl = sCourses; }
catch( bad_alloc& )
{ throw StudentXptn( sIdNum, "getCourses",
StudentXptn::allocFailed ); }
} // Student::getCourses
: :
Student::Student( int aIdNum )
: sWH( 0 )
{
if ( aIdNum < 0 )
throw StudentXptn( 0, "Student", StudentXptn::negIdNum,
aIdNum );
sIdNum = aIdNum;
sSurname[0] = '\0';
sFirstname[0] = '\0';
}; // Student()
:
Student::Student( const Student& rhs )
{
sIdNum = rhs.sIdNum;
strcpy( sSurname, rhs.sSurname );
strcpy( sFirstname, rhs.sFirstname );
sWH = rhs.sWH;
try { sCourses = rhs.sCourses; }
catch( bad_alloc& )
{
throw StudentXptn( sIdNum, "Student",
StudentXptn::allocFailed );
}
} // Student( const Student& rhs )
STL 1045

:
vector () . ;
bad_alloc.
:
; : !
findNdx() CourseCollection::findNdx()
:

vector<Course::CourseKey>::iterator
( vector<Course>::iterator).
sCourses ( ccArr).
Course::CourseKey(code) ( Course(code)).
vector<Course::CourseKey>::iterator Student::findNdx( const string& code )
{
vector<Course::CourseKey>::iterator ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = sCourses.end();
else
ndx = find( sCourses.begin(), sCourses.end(),
Course::CourseKey(code) );
return ndx;
} // Student::findNdx
:
bool find1Course( const string& code ) const
{ return ( findNdx(code) != sCourses.end() ); };

void Student::add1Course( const Course& oneCourse )


{
if ( findNdx(oneCourse.getCode()) == sCourses.end() )
{
insert1Course( Course::CourseKey(oneCourse.getCode()) );
sWH += oneCourse.getWH();
}
} // Student::add1Course

void Student::delete1Course( const Course& oneCourse )


{
vector<Course::CourseKey>::iterator
ndx( findNdx(oneCourse.getCode()) );
if ( ndx != sCourses.end() ) //
{
erase1Course( ndx );
sWH -= oneCourse.getWH();
}
} // Student::delete1Course
:
void Student::insert1Course( const Course::CourseKey& aCode )
{
try { sCourses.push_back( aCode ); }
catch( bad_alloc& )
{
throw StudentXptn( sIdNum, "insert1Course",
StudentXptn::allocFailed );
}
} // Student::insert1Course

void Student::erase1Course( vector<Course::CourseKey>::iterator ndx)


{
*ndx = sCourses.back();
sCourses.pop_back();
1046 Project 07

} // Student::erase1Course
:
void Student::swap( Student& rhs )
{
std::swap( sIdNum, rhs.sIdNum );

char svs[sNameSz];
strcpy( svs, sSurname ); strcpy( sSurname, rhs.sSurname );
strcpy( rhs.sSurname, svs );

strcpy( svs, sFirstname );


strcpy( sFirstname, rhs.sFirstname );
strcpy( rhs.sFirstname, svs );

std::swap( sWH, rhs.sWH );

sCourses.swap( rhs.sCourses );
} // Student::swap

void Student::save( ostream& bout ) const


{
if ( bout.fail() )
throw StudentXptn( sIdNum, "save", StudentXptn::fileNotOpen );
bout.write( reinterpret_cast<const char*>(&sIdNum), sizeof(sIdNum) );
bout.write( sSurname, sizeof(sSurname) );
bout.write( sFirstname, sizeof(sFirstname) );
bout.write( reinterpret_cast<const char*>(&sWH), sizeof(sWH) );
size_t noOfCourses( sCourses.size() );
bout.write( reinterpret_cast<const char*>(&noOfCourses),
sizeof(noOfCourses) );//
for ( int k(0); k < noOfCourses; ++k )
bout.write( sCourses[k].s, Course::cCodeSz );
if ( bout.fail() )
throw StudentXptn( sIdNum, "save", StudentXptn::cannotWrite );
} // Student::save

void Student::load( istream& bin )


{
Student tmp;
bin.read( reinterpret_cast<char*>(&tmp.sIdNum), sizeof(sIdNum) );
if ( !bin.eof() )
{
bin.read( tmp.sSurname, sizeof(sSurname) );
bin.read( tmp.sFirstname, sizeof(sFirstname) );
bin.read( reinterpret_cast<char*>(&tmp.sWH), sizeof(sWH) );
size_t noOfCourses; // . .
bin.read( reinterpret_cast<char*>(&noOfCourses), sizeof(noOfCourses) );
for ( int k(0); k < noOfCourses; ++k )
{
char aKey[Course::cCodeSz];
bin.read( aKey, Course::cCodeSz );
tmp.sCourses.push_back( Course::CourseKey(aKey) );
}
if ( bin.fail() )
throw StudentXptn( sIdNum, "load",
StudentXptn::cannotRead );
swap( tmp );
}
} // Student::load

Prj07.1.4 StudentCollection
, ,
enum { scIncr = 30 };
STL 1047

Student* scArr;
size_t scNOfStudents;
size_t scReserved;

vector<Student> scArr;
, :
size_t getNOfStudents() const { return scArr.size(); }

void StudentCollection::getArr( vector<Student>& stdntTbl ) const


{
try { stdntTbl = scArr; }
catch( bad_alloc& )
{ throw StudentCollectionXptn( "getArr",
StudentCollectionXptn::allocFailed ); }
} // StudentCollection::getArr
:
StudentCollection::StudentCollection()
{ scPAllEnrollments = 0; }
~StudentCollection() { };
:
vector<Student>::iterator StudentCollection::findNdx( int aIdNum )
{
vector<Student>::iterator ndx;
if ( aIdNum <= 0 )
ndx = scArr.end();
else
ndx = find( scArr.begin(), scArr.end(), Student(aIdNum) );
return ndx;
} // StudentCollection::findNdx

bool find1Student( int aIdNum ) const


{ return ( findNdx(aIdNum) != scArr.end() ); };

const Student& StudentCollection::get1Student( int aIdNum ) const


{
vector<Student>::const_iterator ndx( findNdx(aIdNum) );
if ( ndx == scArr.end() )
throw StudentCollectionXptn( "get1Student",
StudentCollectionXptn::notFound,
aIdNum );
return *ndx;
} // StudentCollection::get1Student

void StudentCollection::add1Student( const Student& aStudent )


{
vector<Student>::iterator ndx( findNdx(aStudent.getIdNum()) );
if ( ndx == scArr.end() ) //
{
if ( scPAllEnrollments == 0 )
throw StudentCollectionXptn( "add1Student",
StudentCollectionXptn::noEnroll );
insert1Student( aStudent );
vector<Course::CourseKey> aStCourses;
aStudent.getCourses( aStCourses );
for ( int k(0); k < aStudent.getNoOfCourses(); ++k )
{
scPAllEnrollments->add1StudentInCourse(
StudentInCourse(aStudent.getIdNum(), aStCourses[k].s) );
}
}
} // StudentCollection::add1Student
1048 Project 07

add1Student() aStCourses
Student::getCourses().
void StudentCollection::delete1Student( int aIdNum )
{
vector<Student>::iterator ndx( findNdx(aIdNum) );
if ( ndx != scArr.end() ) //
{
if ( ndx->getNoOfCourses() > 0 )
throw StudentCollectionXptn( "delete1Student",
StudentCollectionXptn::enrollRef,
aIdNum );
erase1Student( ndx );
}
} // StudentCollection::delete1Student

void StudentCollection::insert1Student( const Student& aStudent )


{
try { scArr.push_back( aStudent ); }
catch( MyTmpltLibXptn& )
{
throw StudentCollectionXptn( "insert1Student",
StudentCollectionXptn::allocFailed );
}
} // StudentCollection::insert1Student

void StudentCollection::erase1Student(vector<Student>::iterator ndx)


{
*ndx = scArr.back();
scArr.pop_back();
} // StudentCollection::erase1Student
:
void StudentCollection::add1Course( int aIdNum, const Course& aCourse )
{
vector<Student>::iterator ndx( findNdx(aIdNum) );
if ( ndx == scArr.end() )
throw StudentCollectionXptn( "add1Course",
StudentCollectionXptn::notFound,
aIdNum );
ndx->add1Course( aCourse );
} // StudentCollection::add1Course

void StudentCollection::delete1Course( int aIdNum, const Course& aCourse )


{
vector<Student>::iterator ndx( findNdx(aIdNum) );
if ( ndx == scArr.end() )
throw StudentCollectionXptn( "delete1Course",
StudentCollectionXptn::notFound,
aIdNum );
ndx->delete1Course( aCourse );
} // StudentCollection::delete1Course
, :
void StudentCollection::swapArr( StudentCollection& rhs )
{
scArr.swap( rhs.scArr);
} // StudentCollection::swap

void StudentCollection::save( ofstream& bout, SIndexEntry* index )


{
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::fileNotOpen );
size_t nOfStudents( scArr.size() );
bout.write( reinterpret_cast<const char*>(&nOfStudents),
sizeof(nOfStudents) );
STL 1049

for ( int k(0); k < nOfStudents; ++k )


{
index[k].sIdNum = scArr[k].getIdNum();
index[k].loc = bout.tellp();
scArr[k].save( bout );
}
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::cannotWrite );
} // StudentCollection::save

void StudentCollection::load( ifstream& bin )


{
StudentCollection tmp;
size_t n;
bin.read( reinterpret_cast<char*>(&n), sizeof(size_t) );
if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Student oneStudent;
oneStudent.load( bin );
tmp.insert1Student( oneStudent );
}
if ( bin.fail() )
throw StudentCollectionXptn( "load",
StudentCollectionXptn::cannotRead );
swapArr( tmp );
}
} // StudentCollection::load
save():
; -
.

Prj07.1.5 StudentInCourse
StudentInCourse .

Prj07.1.6 StudentInCourseCollection
, , :
vector<StudentInCourse> siccArr;
:
StudentInCourseCollection::StudentInCourseCollection()
{
siccPAllStudents = 0;
siccPAllCourses = 0;
} // StudentInCourseCollection::StudentInCourseCollection

~StudentInCourseCollection() { };

size_t getNOfStudentInCourses() const { return siccArr.size(); }

void StudentInCourseCollection::getArr( vector<StudentInCourse>& sicTbl) const


{
try { sicTbl = siccArr; }
catch( bad_alloc& )
{ throw StudentInCourseCollectionXptn( "getArr",
StudentInCourseCollectionXptn::allocFailed ); }
} // StudentInCourseCollection::getArr
:
1050 Project 07

vector<StudentInCourse>::iterator
StudentInCourseCollection::findNdx( int aIdNum, string code )
{
vector<StudentInCourse>::iterator ndx;
if ( aIdNum <= 0 || code.length() != Course::cCodeSz-1 )
ndx = siccArr.end();
else
ndx = find( siccArr.begin(), siccArr.end(),
StudentInCourse(aIdNum,code) );
return ndx;
} // StudentInCourseCollection::findNdx
:
bool find1StudentInCourse( int aIdNum, string code ) const
{ return ( findNdx(aIdNum, code) != siccArr.end() ); }

const StudentInCourse&
StudentInCourseCollection::get1StudentInCourse( int aIdNum,
string code ) const
{
vector<StudentInCourse>::const_iterator
ndx( findNdx(aIdNum, code) );
if ( ndx == siccArr.end() ) //
throw StudentInCourseCollectionXptn( "get1StudentInCourse",
StudentInCourseCollectionXptn::notFound,
StudentInCourse::SICKey(aIdNum, code) );
return *ndx;
} // StudentInCourseCollection::get1StudentInCourse
add1StudentInCourse() if:
void StudentInCourseCollection::add1StudentInCourse(
const StudentInCourse& aStdnInCrs )
{
if ( findNdx( aStdnInCrs.getSIdNum(), //
aStdnInCrs.getCCode()) == siccArr.end() )
{
// . . .
insert1StudentInCourse( aStdnInCrs );
}
} // StudentInCourseCollection::add1StudentInCourse
insert1StudentInCourse() :
void StudentInCourseCollection::insert1StudentInCourse(
const StudentInCourse& aStdnInCrs )
{
try { siccArr.push_back( aStdnInCrs ); }
catch( MyTmpltLibXptn& )
{
throw StudentInCourseCollectionXptn( "insert1StudentInCourse",
StudentInCourseCollectionXptn::allocFailed );
}
} // StudentInCourseCollection::insert1StudentInCourse
:
void StudentInCourseCollection::delete1StudentInCourse( int aIdNum,
string code )
{
vector<StudentInCourse>::iterator ndx( findNdx(aIdNum, code) );
if ( ndx != siccArr.end() ) //
{
if ( siccPAllCourses == 0 )
throw StudentInCourseCollectionXptn( "delete1StudentInCourse",
StudentInCourseCollectionXptn::noCrs );
if ( siccPAllStudents == 0 )
throw StudentInCourseCollectionXptn( "delete1StudentInCourse",
StudentInCourseCollectionXptn::noStdnt );
siccPAllCourses->delete1Student( code );
Course oneCourse( siccPAllCourses->get1Course( code) );
STL 1051

siccPAllStudents->delete1Course( aIdNum, oneCourse );


erase1StudentInCourse( ndx );
}
} // StudentInCourseCollection::delete1StudentInCourse
:
void StudentInCourseCollection::erase1StudentInCourse(
vector<StudentInCourse>::iterator ndx )
{
*ndx = siccArr.back();
siccArr.pop_back();
} // StudentInCourseCollection::erase1StudentInCourse
swapArr() :
void StudentInCourseCollection::swapArr( StudentInCourseCollection& rhs )
{
siccArr.swap( rhs.siccArr );
} // StudentInCourseCollection::swapArr
save() load() :
void StudentInCourseCollection::save( ofstream& bout ) const
{
if ( bout.fail() )
throw StudentInCourseCollectionXptn( "save",
StudentInCourseCollectionXptn::fileNotOpen );
size_t nOfStudentInCourse( siccArr.size() );
bout.write( reinterpret_cast<const char*>(&nOfStudentInCourse),
sizeof(nOfStudentInCourse) );
for ( int k(0); k < nOfStudentInCourse; ++k )
siccArr[k].save( bout );
if ( bout.fail() )
throw StudentInCourseCollectionXptn( "save",
StudentInCourseCollectionXptn::cannotWrite );
} // StudentInCourseCollection::save

void StudentInCourseCollection::load( ifstream& bin )


{
StudentInCourseCollection tmp;
size_t n;
bin.read( reinterpret_cast<char*>(&n), sizeof(size_t) );
if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
StudentInCourse oneStudentInCourse;
oneStudentInCourse.load( bin );
tmp.insert1StudentInCourse( oneStudentInCourse );
}
if ( bin.fail() )
throw StudentInCourseCollectionXptn( "load",
StudentInCourseCollectionXptn::cannotRead );
swapArr( tmp );
}
} // StudentInCourseCollection::load

Prj07.1.7 -
StudentCollection::save()

vector. ; ! main() :
vector<SIndexEntry> sIndex;
try
{ sIndex.reserve( allStudents.getNOfStudents() ); }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
1052 Project 07

:
saveCollections( allCourses, allStudents, &sIndex[0], allEnrollments );
saveCollections() :
allStudents.save( bout, sIndex );
: StudentCollection::save() -
sIndex. () sIndex.reserve().
save()
push_back().

Prj07.2 STL II
() Project 4
.

Prj07.2.1

. ;
Project. , ,
.

Prj07.2.1.1 ccArr CourseCollection


CourseCollection
.
Course. -
( 100 B) (8 B).
map.
:
1 : , ,
.
: 3-4 . -
,
.

26.4: vector. :
1 : , vector <Course>, -
, lower_bound()
.
-
lower_bound().
:
26.4
. (Prj07.1.2).

: -
insert() ( push_back()).
STL 1053

:

( push_back()),
lower_bound(); findNdx(),
find1Course() get1Course(). !

, vector.
Course
StudentCollection
26.3.2.

Prj07.2.1.2 sCourses Student


().
. 2
set, .
.
.

Prj07.2.1.3 scArr StudentCollection


. ;
!
.
.
.
.
.
( ) -
.
( ) 10%
. (..
sCourses ) /.
map, ()
Student.

Prj07.2.1.4 siccArr StudentInCourseCollection


,
.

.
; :
.
(-) .
.
: .
; - vector.

2 .
.
1054 Project 07

( , ) 75% -
. set; -
, ; : --
--. map -
.
map.

Prj07.2.1.5 -
Prj07.1.7; !
( )
vector. :
new[]
delete[],
,
write().
.
( ) :
,

,

.

. . 3 ;
( )

.

Prj07.2.2 Course
, CourseCollection <
Course: 4
bool operator<( const Course::CourseKey& lhs, const Course::CourseKey& rhs )
{ return ( strcmp(lhs.s, rhs.s) < 0 ); }

bool operator<( const Course& lhs, const Course& rhs )


{ return ( Course::CourseKey(lhs.getCode()) <
Course::CourseKey(rhs.getCode()) ); }

Prj07.2.3 CourseCollection
Prj07.1.2 :
vector<Course> ccArr;

3 :
.
4 , :
bool operator>=( const Course::CourseKey& lhs, const Course::CourseKey& rhs)
{ return ( !(lhs < rhs) ); }
bool operator>=( const Course& lhs, const Course& rhs )
{ return ( !(lhs < rhs) ); }
STL 1055

:
CourseCollection() { };
~CourseCollection() { };
size_t getNOfCourses() const { return ccArr.size(); }
const Course* getArr() const { return &ccArr[0]; }
getArr() Prj07.1.2.1.
void CourseCollection::getArr( vector<Course>& crsArr ) const
//
findNdx(). find()
lower_bound():
vector<Course>::iterator CourseCollection::findNdx( const string& code )
{
vector<Course>::iterator ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = ccArr.end();
else
ndx = lower_bound( ccArr.begin(), ccArr.end(), Course(code) );
return ndx;
} // CourseCollection::findNdx
: lower_bound()
( ) ( ).
find1Course() :
bool CourseCollection::find1Course( const string& code ) const
{
vector<Course>::iterator ndx( findNdx(code) );
return ( (ndx != ccArr.end()) && (*ndx == Course(code)) );
} // CourseCollection::find1Course
return .
5.6, ndx != ccArr.end() false false
() ndx.
return :
ndx == ccArr.end() || (*ndx != Course(code))
.
lower_bound()
< Course.
CourseCollection::delete1Course() Prj07.1.2 :
if
:
if ( ndx != ccArr.end() && (*ndx == Course(code)) ) //
EqPrereq. erase1Course()
:
void CourseCollection::erase1Course( vector<Course>::iterator ndx )
{
ccArr.erase( ndx );
} // CourseCollection::erase1Course
add1Course() :
void CourseCollection::add1Course( const Course& aCourse )
{
if ( strlen(aCourse.getCode()) != Course::cCodeSz-1 )
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::entity );
vector<Course>::iterator ndx( findNdx(aCourse.getCode()) );
if ( ndx==ccArr.end() || (*ndx!=aCourse) )
{ //
if ( strcmp(aCourse.getPrereq(), "") != 0 ) //
{ //
1056 Project 07

vector<Course>::iterator ndx(findNdx(aCourse.getPrereq()));
if ( ndx == ccArr.end() ) //
//
throw CourseCollectionXptn( "add1Course",
CourseCollectionXptn::prereqRef,
aCourse.getPrereq() );
}
//
ndx = insert1Course( ndx, aCourse );
ndx->clearStudents();
}
} // CourseCollection::add1Course
;
ndx.
insert1Course()
ccArr.insert(). ,
.
vector<Course>::iterator
CourseCollection::insert1Course( vector<Course>::iterator ndx,
const Course& aCourse )
{
try { return ccArr.insert( ndx, aCourse ); }
catch ( bad_alloc& )
{ throw CourseCollectionXptn( "insert1Course",
CourseCollectionXptn::allocFailed ); }
} // CourseCollection::insert1Course
get1Course() :
const Course& CourseCollection::get1Course( string code ) const
{
vector<Course>::const_iterator ndx( findNdx(code) );
if ( ndx == ccArr.end() || (*ndx != Course(code)) )
throw CourseCollectionXptn( "get1Course",
CourseCollectionXptn::notFound,
code.c_str() );
return *ndx;
} // CourseCollection::get1Course
, ndx if.
:
void CourseCollection::add1Student( string code )
{
vector<Course>::iterator ndx( findNdx(code) );
if ( ndx==ccArr.end() || (*ndx!=Course(code)) )
throw CourseCollectionXptn( "add1Student",
CourseCollectionXptn::notFound,
code.c_str() );
ndx->add1Student();
} // CourseCollection::add1Student

void CourseCollection::delete1Student( string code )


{
vector<Course>::iterator ndx( findNdx(code) );
if ( ndx==ccArr.end() || (*ndx!=Course(code)) )
throw CourseCollectionXptn( "delete1Student",
CourseCollectionXptn::notFound,
code.c_str() );
ndx->delete1Student();
} // CourseCollection::delete1Student
swap() Prj07.1.2 save().
load() : insert1Course() tmp.insert1-
Course(oneCourse) tmp.add1Course( oneCourse ).
STL 1057

Prj07.2.4 Student
:
set<Course::CourseKey> sCourses;
( Prj07.1.3):
unsigned int getNoOfCourses() const { return sCourses.size(); }
void clearCourses() { sCourses.clear(); sWH = 0; }
getCourses() :
void Student::getCourses( vector<Course::CourseKey>& crsTbl ) const
{
try
{
crsTbl.clear();
for ( set<Course::CourseKey>::const_iterator it(sCourses.begin());
it != sCourses.end(); ++it )
crsTbl.push_back( *it );
}
catch( bad_alloc& )
{ throw StudentXptn( sIdNum, "getCourses", StudentXptn::allocFailed ); }
} // Student::getCourses

.
Prj07.1.3, .

( ) sCourses.
sCourses = rhs.sCourses .

() bad_alloc. ( )
Student::operator=(). , :
~Student() { };
findNdx(). Prj07.1.3 -
vector<Course::CourseKey>::iterator set<Course::CourseKey>::
iterator; . :
set<Course::CourseKey>::iterator Student::findNdx( const string& code )
{
set<Course::CourseKey>::iterator ndx;
if ( code.length() != Course::cCodeSz-1 )
ndx = sCourses.end();
else
ndx = sCourses.find( Course::CourseKey(code) );
return ndx;
} // Student::findNdx
sCourses.find() O(log(sCourses.size())) O(sCourses.size())
std::find().
find1Course() , Prj07.1.3:
bool find1Course( const string& code )
{ return ( findNdx(code) != sCourses.end() ); };
add1Course() delete1Course() () in-
sert1Course() erase1Course():
typedef pair< set<Course::CourseKey>::iterator, bool > InsRetType;

void Student::add1Course( const Course& oneCourse )


{
try
{
InsRetType rv(sCourses.insert(Course::CourseKey(oneCourse.getCode())) );
1058 Project 07

if ( rv.second ) sWH += oneCourse.getWH();


}
catch( bad_alloc& )
{
throw StudentXptn( sIdNum, "insert1Course", StudentXptn::allocFailed );
}
} // Student::add1Course
: 26.3.1 insert() set (1 )
: Course::
CourseKey(oneCourse.getCode()) pair ( : rv):
(rv.first)
(set<Course::CourseKey>::iterator) .
(rv.second) bool true
false .
rv.second true -
.
, delete1Course(), erase() set:
void Student::delete1Course( const Course& oneCourse )
{
size_t erased( sCourses.erase(Course::CourseKey(oneCourse.getCode())) );
if ( erased > 0 ) sWH -= oneCourse.getWH();
} // Student::delete1Course
sCourses.erase() erased.
0.
, , 1 erased > 0
.
swap() Prj07.1.3 sCourses.swap(rhs.
sCourses) .
save() : for

:
for( set<Course::CourseKey>::const_iterator it(sCourses.begin());
it != sCourses.end(); ++it )
bout.write( it->s, Course::cCodeSz );
display().
load(),
:
for ( int k(0); k < noOfCourses; ++k )
{
char aKey[Course::cCodeSz];
bin.read( aKey, Course::cCodeSz );
tmp.sCourses.insert( Course::CourseKey(aKey) );
}
, tmp.sCourses.insert()
tmp.sCourses.push_back().

Prj07.2.5 StudentCollection
Prj07.1.1.4 map,
() Student. :
map< unsigned int, Student > scArr;
unsigned int Student. :
Student ( sIdNum)
STL 1059

(, , ); ! ,
. scArr
:
scArr[aStudent.getIdNum()] = aStudent
:
scArr.insert( make_pair(aStudent.getIdNum(),aStudent) )
Prj07.1.4,
size_t getNOfStudents() const { return scArr.size(); }

void StudentCollection::getArr( vector<Student>& stdntTbl ) const
{
try
{
for ( map<unsigned int,Student>::const_iterator it(scArr.begin());
it != scArr.end(); ++it )
stdntTbl.push_back( it->second );
}
catch( bad_alloc& )
{ throw StudentCollectionXptn( "getArr",
StudentCollectionXptn::allocFailed ); }
} // StudentCollection::getArr
it for (, ). it->second -
. getArr() getCourses() Student.

Prj07.1.4.

map< unsigned int, Student >::iterator StudentCollection::findNdx( int aIdNum)
{
map<unsigned int,Student>::iterator ndx;
if ( aIdNum <= 0 )
ndx = scArr.end();
else
ndx = scArr.find( aIdNum );
return ndx;
} // StudentCollection::findNdx
ndx findNdx();
pair<unsigned int,Student>.
find1Student() Prj07.1.4.
const Student& StudentCollection::get1Student( int aIdNum ) const
{
map<unsigned int,Student>::const_iterator ndx( findNdx(aIdNum) );
if ( ndx == scArr.end() )
throw StudentCollectionXptn( "get1Student",
StudentCollectionXptn::notFound, aIdNum );
return ndx->second;
} // StudentCollection::get1Student
Prj07.1.4, ndx -
ndx->second.
ndx add1Student() :
insert1Student():
void StudentCollection::add1Student( const Student& aStudent )
{
map<unsigned int,Student>::iterator ndx( findNdx(aStudent.getIdNum()) );
if ( ndx == scArr.end() ) //
{
if ( scPAllEnrollments == 0 )
throw StudentCollectionXptn( "add1Student",
StudentCollectionXptn::noEnroll );
1060 Project 07

scArr.insert( make_pair(aStudent.getIdNum(),aStudent) );
vector<Course::CourseKey> aStCourses;
aStudent.getCourses( aStCourses );
for ( int k(0); k < aStudent.getNoOfCourses(); ++k )
{
scPAllEnrollments->add1StudentInCourse(
StudentInCourse(aStudent.getIdNum(), aStCourses[k].s) );
}
}
} // StudentCollection::add1Student
, delete1Student() erase1Student():
void StudentCollection::delete1Student( int aIdNum )
{
map<unsigned int,Student>::iterator ndx( findNdx(aIdNum) );
if ( ndx != scArr.end() ) //
{
if ( (ndx->second).getNoOfCourses() > 0 )
throw StudentCollectionXptn( "delete1Student",
StudentCollectionXptn::enrollRef,
aIdNum );
scArr.erase( ndx );
}
} // StudentCollection::delete1Student
/ :
void StudentCollection::add1Course( int aIdNum, const Course& aCourse )
{
map<unsigned int,Student>::iterator ndx( findNdx(aIdNum) );
if ( ndx == scArr.end() )
throw StudentCollectionXptn( "add1Course",
StudentCollectionXptn::notFound, aIdNum );
(ndx->second).add1Course( aCourse );
} // StudentCollection::add1Course

void StudentCollection::delete1Course( int aIdNum, const Course& aCourse )


{
map<unsigned int,Student>::iterator ndx( findNdx(aIdNum) );
if ( ndx == scArr.end() )
throw StudentCollectionXptn( "delete1Course",
StudentCollectionXptn::notFound, aIdNum );
(ndx->second).delete1Course( aCourse );
} // StudentCollection::delete1Course
, / :
void StudentCollection::swapArr( StudentCollection& rhs )
{
scArr,swap( rhs.scArr );
} // StudentCollection::swap

void StudentCollection::save( ofstream& bout, SIndexEntry* index )


{
if ( bout.fail() )
throw StudentCollectionXptn( "save",
StudentCollectionXptn::fileNotOpen );
size_t scNOfStudents( scArr.size() );
bout.write( reinterpret_cast<const char*>(&scNOfStudents),
sizeof(scNOfStudents) );
for ( map<unsigned int,Student>::const_iterator it(scArr.begin()),
unsigned int k(0);
it != scArr.end(); ++it, ++k )
{
index[k].sIdNum = it->first;
index[k].loc = bout.tellp();
(it->second).save( bout );
}
if ( bout.fail() )
STL 1061

throw StudentCollectionXptn( "save",


StudentCollectionXptn::cannotWrite );
} // StudentCollection::save

void StudentCollection::load( ifstream& bin )


{
StudentCollection tmp;
size_t n;
bin.read( reinterpret_cast<char*>(&n), sizeof(size_t) );
if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
Student oneStudent;
oneStudent.load( bin );
tmp.add1Student( oneStudent );
}
if ( bin.fail() )
throw StudentCollectionXptn( "load",
StudentCollectionXptn::cannotRead );
swapArr( tmp );
}
} // StudentCollection::load
, checkWH():
void StudentCollection::checkWH( ostream& log, int maxWH ) const
{
if ( maxWH <= 0 )
throw StudentCollectionXptn( "checkWH",
StudentCollectionXptn::negWH, maxWH );
for ( map<unsigned int,Student>::const_iterator it(scArr.begin());
it != scArr.end(); ++it )
{
if ( (it->second).getWH() > maxWH )
log << "student with id num " << (it->second).getIdNum()
<< ": " << (it->second).getWH() << " hours/week"
<< endl;
} // for
} // StudentCollection::checkWH

Prj07.2.6 StudentInCourseCollection
:
map< StudentInCourse::SICKey, StudentInCourse > siccArr;

float; map<StudentInCourse::SICKey,
float>; , () .
.
<
StudentInCourse. , ,
:
struct SICKeyLT
{
bool operator()( const SICKey& frst, const SICKey& scnd ) const
{
bool fv( false );
if ( frst.CCode < scnd.CCode ) fv = true;
else if ( frst.CCode == scnd.CCode )
{
if ( frst.sIdNum < scnd.sIdNum ) fv = true;
}
return fv;
}
1062 Project 07

}; // SICKeyLT
SICMap :
typedef map< StudentInCourse::SICKey, StudentInCourse,
StudentInCourseCollection::SICKeyLT > SICMap;
:
SICMap siccArr;
;
( ).
; private:
class StudentInCourseCollection
{
public:
// . . .
private:
struct SICKeyLT
//
typedef map< StudentInCourse::SICKey, StudentInCourse,
StudentInCourseCollection::SICKeyLT > SICMap;
SICMap siccArr;
// . . .
}; // StudentInCourseCollection
:
() : <
StudentInCourse:
bool operator<( const StudentInCourse::SICKey& frst,
const StudentInCourse::SICKey& scnd )
{
bool fv( false );
if ( frst.CCode < scnd.CCode ) fv = true;
else if ( frst.CCode == scnd.CCode )
{
if ( frst.sIdNum < scnd.sIdNum ) fv = true;
}
return fv;
} // operator<
() .
:
StudentInCourseCollection::StudentInCourseCollection()
{
siccPAllStudents = 0;
siccPAllCourses = 0;
} // StudentInCourseCollection::StudentInCourseCollection
:
~StudentInCourseCollection() { };
:
size_t getNOfStudentInCourses() const { return siccArr.size(); }

void StudentInCourseCollection::getArr( vector<StudentInCourse>& sicTbl) const


{
try
{
for ( StudentInCourseCollection::SICMap::const_iterator
it(siccArr.begin());
it != siccArr.end(); ++it )
sicTbl.push_back( it->second );
}
catch( bad_alloc& )
{ throw StudentCollectionXptn( "getArr",
StudentCollectionXptn::allocFailed ); }
STL 1063

} // StudentInCourseCollection::getArr

StudentInCourseCollection::SICMap::iterator
StudentInCourseCollection::findNdx( int aIdNum, string code )
{
StudentInCourseCollection::SICMap::iterator ndx;
if ( aIdNum <= 0 || code.length() != Course::cCodeSz-1 )
ndx = siccArr.end();
else
ndx = siccArr.find( StudentInCourse::SICKey(aIdNum, code) );
return ndx;
} // StudentInCourseCollection::findNdx
1 StudentInCourse :
bool find1StudentInCourse( int aIdNum, string code )
{ return ( findNdx(aIdNum, code) != siccArr.end() ); }

const StudentInCourse&
StudentInCourseCollection::get1StudentInCourse( int aIdNum,
string code ) const
{
StudentInCourseCollection::SICMap::const_iterator
ndx( findNdx(aIdNum, code) );
if ( ndx == siccArr.end() )
throw StudentInCourseCollectionXptn( "get1StudentInCourse",
StudentInCourseCollectionXptn::notFound,
StudentInCourse::SICKey(aIdNum, code) );
return ndx->second;
} // StudentInCourseCollection::get1StudentInCourse

void StudentInCourseCollection::delete1StudentInCourse( int aIdNum,


string code )
{
StudentInCourseCollection::SICMap::iterator
ndx( findNdx(aIdNum, code) );
if ( ndx != siccArr.end() ) //
{
if ( siccPAllCourses == 0 )
throw StudentInCourseCollectionXptn(
"delete1StudentInCourse",
StudentInCourseCollectionXptn::noCrs );
if ( siccPAllStudents == 0 )
throw StudentInCourseCollectionXptn(
"delete1StudentInCourse",
StudentInCourseCollectionXptn::noStdnt );
siccPAllCourses->delete1Student( code );
Course oneCourse( siccPAllCourses->get1Course( code) );
siccPAllStudents->delete1Course( aIdNum, oneCourse );
siccArr.erase( ndx );
}
} // StudentInCourseCollection::delete1StudentInCourse

void StudentInCourseCollection::add1StudentInCourse(
const StudentInCourse& aStdnInCrs )
{
if ( findNdx( aStdnInCrs.getSIdNum(),
aStdnInCrs.getCCode()) == siccArr.end() )
{
if ( siccPAllCourses == 0 )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::noCrs );
if ( !(siccPAllCourses->find1Course(aStdnInCrs.getCCode())))
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::unknownCrs,
aStdnInCrs.getCCode() );
if ( siccPAllStudents == 0 )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
1064 Project 07

StudentInCourseCollectionXptn::noStdnt );
if ( !(siccPAllStudents->find1Student(aStdnInCrs.getSIdNum())) )
throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::unknownStdn,
aStdnInCrs.getSIdNum() );
siccPAllCourses->add1Student( aStdnInCrs.getCCode() );
Course oneCourse( siccPAllCourses->get1Course(aStdnInCrs.getCCode()) );
siccPAllStudents->add1Course( aStdnInCrs.getSIdNum(), oneCourse );
try
{
siccArr.insert( make_pair(aStdnInCrs.getKey(), aStdnInCrs));
}
catch( bad_alloc& )
{ throw StudentInCourseCollectionXptn( "add1StudentInCourse",
StudentInCourseCollectionXptn::allocFailed ); }
}
} // StudentInCourseCollection::add1StudentInCourse
, save(), load() swapArr() :
void StudentInCourseCollection::save( ofstream& bout ) const
{
if ( bout.fail() )
throw StudentInCourseCollectionXptn( "save",
StudentInCourseCollectionXptn::fileNotOpen );
size_t siccNOfStudentInCourses( siccArr.size() );
bout.write( reinterpret_cast<const char*>(&siccNOfStudentInCourses),
sizeof(siccNOfStudentInCourses) );
for ( StudentInCourseCollection::SICMap::const_iterator
it(siccArr.begin());
it != siccArr.end(); ++it )
(it->second).save( bout );
if ( bout.fail() )
throw StudentInCourseCollectionXptn( "save",
StudentInCourseCollectionXptn::cannotWrite );
} // StudentInCourseCollection::save

void StudentInCourseCollection::load( ifstream& bin )


{
StudentInCourseCollection tmp;
size_t n;
bin.read( reinterpret_cast<char*>(&n), sizeof(size_t) );
if ( !bin.eof() )
{
for ( int k(0); k < n && !bin.fail(); ++k )
{
StudentInCourse oneStudentInCourse;
oneStudentInCourse.load( bin );
tmp.add1StudentInCourse( oneStudentInCourse );
}
if ( bin.fail() )
throw StudentInCourseCollectionXptn( "load",
StudentInCourseCollectionXptn::cannotRead );
swapArr( tmp );
}
} // StudentInCourseCollection::load

void StudentInCourseCollection::swapArr( StudentInCourseCollection& rhs )


{
siccArr.swap( rhs.siccArr );
} // StudentInCourseCollection::swap

Prj07.2.6.1 SICKeyLT

( ).
.
STL 1065

, , :
log.open( "sic.txt" );
vector<StudentInCourse> allSic;
allEnrollments.getArr( allSic );
for ( int k(0); k < allSic.size(); ++k )
allSic[k].display( log );
log.close();
sic.txt :
2019 0100 0
2099 0100 0
2173 0100 0
2069 0100 0
2077 0100 0
2081 0100 0
2117 0100 0
. . .
2067 0305 0
2240 0305 0
2044 0308 0
2067 0314 0
2059 0314 0
2091 0314 0
2127 0314 0
2153 0314 0
2164 0314 0
2203 0314 0
:
0100
2019
2099
2173
0100
2069
2077
2081
2117
. . .
0305
2067
2240
2044
0314
2067
0314
2059
2091
2127
2153
2164
2203
,
.
-
. ;
( Student ).

Prj07.2.7
Prj07.2.1.5 -
( ) -
.
1066 Project 07

, : !
, Prj07.2.5, StudentCollection,
:
map< unsigned int, Student > scArr;
less<unsigned int>. scArr

scArr.insert( make_pair(aStudent.getIdNum(),aStudent) )
, , :
for (map<unsigned int,Student>::const_iterator it(scArr.begin()),
unsigned int k(0);
it != scArr.end(); ++it, ++k )
{
index[k].sIdNum = it->first;
index[k].loc = bout.tellp();
(it->second).save( bout );
}
; , .

.
(std::)lower_bound() -
:

bool comp( const SIndexEntry& frst, const SIndexEntry& scnd )
{ return ( frst.sIdNum < scnd.sIdNum ); } // comp
:
int ndx( linSearch(sIndex, ndxSz, 0, ndxSz-1,
SIndexEntry(idNum)) );
if ( ndx < 0 )

SIndexEntry* ndx( lower_bound(sIndex, sIndex+ndxSz,
SIndexEntry(idNum), comp) );
if ( ndx->sIdNum != idNum )

bin.seekg( sIndex[ndx].loc );

bin.seekg( ndx->loc );
, #include <algorithm>.

Prj07.3

vector
.

.
vector -
RAII . , -
;
vector .
, ( MyTmpltLib.h)
STL .
project

8

:
Prj08.1 : ................................................................................................. 1067
Prj08.2 ........................................................................................................................... 1068
Prj08.3 jpeg .............................................................................................................................................. 1070
Prj08.3.1 ...........................................................................................................................................1070
Prj08.3.2 ................................................................................................................................................1071
Prj08.4 ................................................................................................................................................ 1072

:
Project ! !

Prj08.1 :

. -
(Project 3)
(CourseCollection ). . Prj08-1.
Prj04.13 :
,
. ,

StudentCollection CourseCollection

1..1 1..1

StudentInCourseCollection

1..1

1..*
StudentInCourse

1..* 1..*
0..* 0..*
Student StudentInCourse Course

. Prj08-1 .
1067
1068 Project 08

, .
:
unsigned int sIdNum; //
char sSurname[sNameSz];
char sFirstname[sNameSz];
//

unsigned int sIdNum; //
char sSemester[10]; //
unsigned int sWH; //
unsigned int sNoOfCourses; //
Course::CourseKey* sCourses;
,
:
CourseKey cCode; //
char cTitle[cTitleSz]; //
unsigned int cFSem; //
bool cCompuls; //
char cSector; //
char cCateg[cCategSz]; //
unsigned int cWH; //
unsigned int cUnits; //
CourseKey cPrereq; //
:
CourseKey cCode; //
unsigned int cNoOfStudents; // .
( ,
.)
. Prj08-1 Student Course
. ; !
. ;
allEnrollments! Student::getWH(), Student::getNoOfCourses(), Student
::getCourses(), Course::getNoOfStudents()
allEnrollments.
STL. -
,
, ,
.

Prj08.2
Karakaxa Airlines (KA)
, , .
:
class Pilot
{
public:
// . . .
private:
unsigned int piIdNum; //
char piSurname[20]; //
char piFirstName[16]; //
????? piExper; //
}; // Pilot
1069

piExper 1
struct ExperAircraft
{
char xaAircraftType[20]; //
double xaFlightTime; //
}; // ExperAircraft
-
. piExper (xaFlightTime)
(xaAircraftType).
Pilot save() load()
- (binary) .
Pilot , (, ) (
).
text pilots.txt :
2105\t\t\n
2088\t\t\n
( 2105,
2088, )
pilots.txt -

????? allPilots;
:
class AircraftType
{
public:
// . . .
private:
char atType[20]; //
unsigned int atNoOfSeats; //
double atMaxTakeOffLoad; // kgr
??????? atExperPilots; //
}; // AircraftType
atExperPilots 2
struct ExperPilot
{
unsigned int xpIdNum; //
double xpFlightTime; //
}; // ExperPilot
-
. atExperPilots.
(xpFlightTime)
xpIdNum.
AircraftType save() load() -
- .
text aircraftTypes.txt :
AIRBUS A340-300\t295\t275000\n
ATR - 42 320\t50\t16700 \n
( AIRBUS A340-300, 295 -
275000 kgr.)
, aircraftTypes.txt

1 (public) ExperAircraft .
2 (public) ExperPilot .
1070 Project 08

?????? allAircraftTypes;
flightHours.txt -
( piExper -
).
text flightHours.txt :
2040\tAIRBUS A319\t21.7\n
2145\tATR - 42 - 320\t1374.2\n
2040, 21.7
AIRBUS A319, 2145, 1374.2 -
ATR - 42 320.
, -
pilotExp.dta
aircraftTypes.dta.
pilotExp.dta
aircraftTypes.dta
( ) .
, :
( ),
( allAircraftTypes),
( allPilots),
( allPilots).3
! : -
( 0
). ,
.
( )
/ .
:
1. STL.
2. , : -
.
3. ( Prj08.1); , :

.

Prj08.3 jpeg

Prj08.3.1
-
.
class Product
{
public:
// . . .
private:

3
.
1071

char prCode[20]; //
char prDescr[100]; //
double prL, prW, prH; // (, , ) cm
unsigned char* prJpeg; // jpeg
unsigned int prJpegSz; // jpeg bytes
char prJpegPath[130];// jpeg
void displayJpeg( ostream& tout,
const unsigned char* jpegImg,
int jpegSz ) { };
}; // Product
prJpeg, prJpegSz, prJpegPath :
prJpeg != 0 (NULL), , prJpegSz > 0 (
bytes), prJpegPath ( )
save.
prJpeg == 0 ( ), prJpegSz == 0 prJpegPath == "".
) .
) ,
:
void save( ostream& bout ) const;
Product --
bout. : ( )
bout (binary) (
) prJpegPath.
void load( istream& bin );
Product binary
bout. prJpeg, prJpegSz
0. prJpegPath != ""
prJpegPath.
void loadJpeg( string jPath );
( )
prJpeg. -
prJpegSz, prJpegPath.
.
, jpeg bytes.
save bout
prJpegPath.
) products.dta (binary)
. display
text. ; ; ...
displayJpeg ({ })!

load()
display() .
) . rondinejr
.jpg Product10.jpg. loadJpeg().
, save() () .

Prj08.3.2
Prj08.3.1
.
1072 Project 08

class ProductConstr
{
// . . .
}; // ProductConstr
.
ProductConstr () Product
()
. ( -
, ), .. (CRW0756, 6), (CXL0718, 10).
Product ProductConstr. -
Product. save, load display : (-
) ( , )
. .
products.dta ( )
( Product). text prodComp.txt -
. :
tab tab

ProductConstr, . ! .
, ,
LED-R NQE4868 9
:
LED-R NQE4868 8
.
)
)
) .
, binary
.

Prj08.4
.
.
Person (
) :
, ( -
0, .. 209084),
,
,
() . (10).
persons.txt , , .:
209084\t\t\t6997208 489\n
Loan :
. ( , ..: 22555 70105),
(, ) 1 6,
( ) ,
,
1073

.
loans.txt , ..:
22555 70105\t5\t467\t190321
: . : 22555 70105, 5 ( ),
467 ( 39 ), 190321.
Account :
IBAN4 ( 27 GR,
(Basic Bank Account Number)
, , ),
(, ) 1 5,
,
.
accounts.txt 5, ..:
GR0133444402010136120121721\t4\t14110
: IBAN : GR0133444402010136120121721, 4
( ), 14110.
M Customer Person
IBAN
().
customers.txt :
\tGR2333407023003420332160230\t212003
\t50281 33128\t215070
: (): GR2333407023003420332160230,
212003 ( ). ( )
50281 33128 () 215070.
) .
)
. ! : text
.
) binary,
() .

4 International Bank Account Number.


IBAN (http://www.hba.gr/iban/IBAN-gr.pdf).
5 IBAN ( ). /
MOD 97-10 .
1074 Project 08

(Stroustrup 1997) . -
C++ . , -
C++ :
,
( ) ,
.
(2) .
C++ C.
, (Kernighan & Ritchie 1988), -
. , (Kernighan 1996), -
. C , ,
C++. .
(Lippman & Lajoie 2013) , ,
C++. 5 C++11.
.
(Deitel & Deitel 2013) 6
(. ), 9 C++11 8 () -
.1 Deitel
.2
(Jamsa 1994), (Liberty 1995), (Lafore 2001)
best-sellers .
( 1992).
:
(Hanly 1997) (Mansfield & Antonakos 1997) , .
best-sellers : (Schildt 1997), (Schildt 1998), (Satir & Brown 1995), (Yaro-
shenko 1995). : , ,
C.
(Feuer 1982) C ( C++),
.
:
( 1987), (-
1977), (Manna & Waldinger 1985).
: (Andrews & Ince 1991), (Diller 1990), (Jones 1990), (Spivey
1988).

:
(ELLEMTEL, 1992) Programming in C++: Rules and Recommendations: -

1 http://aicitel.files.wordpress.com/2011/12/deitel_2012.pdf
2http://www.deitel.com/FreeTutorials/FreeTutorialIndex/tabid/1575/Default.aspx#CPLUSPLUS

1075
1076

ELLEMTEL, Ericsson
Televerket.
(Lockheed Martin, 2005) Joint Strike Fighter Air Vehicle C++ Coding Standards for the System
Development and Demonstration Program: C++
(safety critical), -
.
(CERT 2009) CERT C++ Secure Coding Standard: Software
Engineering Institute (SEI) C++.
.
,
C++ .3
(Cline 1999) (Cline, Lomow,
Girou 2000).
Guru of the Week (Sutter 1998) Exceptional C++ (Sutter 1999)
pdf.
C++11 ( C++14) C++03
(Stroustrup, B. 2011). (Kalev 2011).
:
C++03 (ISO 2003).
C++11 (ISO 2011). .
(ISO/IEC JTC1 SC22 WG21 N3337 2012)
C++11.
(ISO/IEC JTC1 SC22 WG21 N3797 2014)
C++14.
.
, . 1962: - . ', .
, ., . , . , . , 1992: ,
, ...., .
, . . 1977:
, 2 ., , .
, . 1992: C++, Learning Plan, .
, . 1987: , .
Abrahams, D. 2001: Exception-Safety in Generic Components, retrieved on 28.12.2012 from:
http://www.boost.org/community/exception_safety.html
Abrahams, D. 2010: Error and Exception Handling, retrieved on 28.12.2012 from: http://
www.boost.org/community/error_handling.html
Alexandrescu, . 2001: Modern C++ design: generic programming and design patterns applied, Addi-
son-Wesley, Reading Ma, US.
Andrews, D. & D. Ince 1991: Practical Formal Methods with VDM, McGraw-Hill, London, UK.
Bohm, C. & G. Jacopini 1966: Flow Diagrams, Turing Machines and Languages with Only
Two Formation Rules, CACM v.9, pp. 366-71.
CERT, 2009: CERT C++ Secure Coding Standard, retrieved on 01.06.2009 from: http://www.
securecoding.cert.org/confluence/pages/viewpage.action?pageId=637.

3
OpenCourseWare (OCW) ! ;
,
1077

Cline, M. 1999: C++ FAQ, retrieved on 05.03.2007 from: http://www.parashift.com/c++-faq-


lite/index.html.
Cline M., G. Lomow, M. Girou 2000: C++ FAQs (Second Edition), Addison Wesley, 2000, re-
trieved on 19.08.2014 from: http://mmc.geofisica.unam.mx/femp/Herramientas/
CyC++/Documentacion/C++FAQs.pdf.
Deitel, H.M. & P.J. Deitel 2013: C++ How to Program 9th ed., Prentice-Hall, Upper Saddle River,
NJ, USA.
Dijkstra, E.W. 1988: Go to Statement Considered Harmful, CACM v.11, pp. 147-148.
Diller, A. 1990: Z: An Introduction to Formal Methods, J. Wiley & Sons, Chichester, UK.
ELLEMTEL, 1992: Programming in C++: Rules and Recommendations, Document: M 90 0118 Uen,
Rev. C, 27 April 1992, retrieved on 01.06.2009 from: http://www.doc.ic.ac.uk/lab/
cplus/c++.rules/
Feuer, A.R. 1982: The C Puzzle Book, Prentice Hall, Englewood Cliffs, NJ, US.
Haendel, L. 2001: www.Function-Pointer.org: The site dedicated to C and C++ Function Pointers,
retrieved on Oct 2009 from: http://www.newty.de/fpt/index.html
Hanly, J.R. 1997: Essential C++ for Engineers and Scientists, Addison-Wesley, Reading Ma, US.
Henricson, M. & E. Nyquist 1997: Industrial Strength C++ - Rules and Recommendations, Prentice
Hall, Upper Saddle River, NJ, US.
Hosey, P. 2007: Everything you need to know about pointers in C, retrieved on 10.10.2008 from:
http://boredzo.org/pointers/
ISO/IEC 1999 (C99): Programming Languages C, Second Edition, ISO/IEC 9899-1999.
ISO 2003: International Standard ISO-IEC 14882: Programming Language C++, Second Edition,
2003-10-15.
ISO 2011: International Standard ISO-IEC 14882: Information technology Programming languages
C++, Third Edition, 2011-09-01.
ISO/IEC JTC1 SC22 WG21 N3337 2012 (C++0X): Programming Languages C++ (Working Draft
Standard), ISO 2012, retrieved on 16.05.2012 from: http://www.openstd.org/jtc1/sc22/
wg21/docs/papers/2012/n3337.pdf
ISO/IEC JTC1 SC22 WG21 N3797 2014 (C++14): Programming Languages C++ (Working Draft
Standard), ISO 2013, retrieved on 29.05.2014 from: http://open-std.org/jtc1/sc22/wg21/
docs/papers/2013/n3797.pdf
Jamsa, K. 1994: C++, , .
Jones, C.B. 1990: Systematic Software Development using VDM, Prentice Hall, London, UK.
Kalev, D. 2011: The Biggest Changes in C++11 (and Why You Should Care), retrieved on 19.08.2014
from: http://blog.smartbear.com/c-plus-plus/the-biggest-changes-in-c11-and-
why-you-should-care/.
Kernighan, B.W. & R. Pike 1996: The Practice of Programming, Addison-Wesley, Reading Ma,
US.
Kernighan, B.W. & D.M. Ritchie 1988: The C Programming Language, 2nd edition, Prentice Hall,
Englewood Cliffs, NJ, US.
Knuth, D. 1977: Structured Programming with goto Statements, Current Trends in Pro-
gramming Methodology, R.T. Yeh (ed.) vol. 1, Prentice Hall, Englewood Cliffs, NJ, US, -
Comp. Surveys, 6, 4, pp. 261-301 (1974).
Lafore, R. 2001: C++, , .
Liberty, J. 1995: C++, , .
1078

Lippman, S.B., J.Lajoie, B.E.Moo 2013: C++ Primer, 5th ed., Addison-Wesley, Reading Ma, US.
Retrieved on 19.08.2014 from:
http://dl.e-book-free.com/2013/07/ c_primer_5th_edition.pdf.
Liskov, B. & J. Wing 1993: Family Values: A semantic notion of subtyping, MIT Lab for Computer
Science TR-562b, retrieved on 10.10.2001 from: http://citeseer.ist.psu.edu/
liskov94family.html.
Lockheed Martin, 2005: Joint Strike Fighter Air Vehicle C++ Coding Standards for the System Devel-
opment and Demonstration Program, doc. num.: 2RDU00001 Rev C., Dec 2005, retrieved on
01.06.2009 from: http://www.research.att.com /%7Ebs/JSF-AV-rules.pdf.
Manna, Z. & R. Waldinger 1985: The Logical Basis for Computer Programming, Vol.1: Deductive
Reasoning, Addison-Wesley, Reading Ma, US.
Mansfield, K.C.Jr & J.L.Antonakos 1997: An Introduction to Programming using C++, Prentice
Hall, Englewood Cliffs, NJ.
OMG 2010: OMG Unified Modeling Language (OMG UML), Superstructure, Ver. 2.3, May 2010,
retrieved on 19.12.2010 from: http://www.omg.org/spec/UML/2.3/Superstructure.
Satir, G. & D. Brown 1995: C++ : The Core Language, O'Reilly & Associates, New York, NY, US.
Schildt, H. 1997: Teach Yourself C++, Osborne McGraw-Hill, New York, NY, US.
Schildt, H. 1998: C++ from the Ground Up, Osborne McGraw-Hill, New York, NY, US.
SGI 1999: Standard Template Library Programmer's Guide, retrieved on 02.06.2003 from http://
www.sgi.com/tech/stl/
Spivey, J.M. 1988 : Understanding Z: A Specification Language and its Formal Semantics, Cambridge
Univ. Press, Cambridge, UK.
Stepanov, A. A., 2007: Notes on Programming, retrieved on 12.08.2008 from http://www.
stepanovpapers.com/
Stroustrup, B. 1997: The C++ Programming Language, 3rd edition, Addison-Wesley, Reading Ma,
US.
Stroustrup, B. 2011: C++11 - the new ISO C++ standard, retrieved on 19.08.2014 from http://
www.stroustrup.com/C++11FAQ.html
Sutter, H. 1998: GotW #49: Template Specialization and Overloading, Dec 2008, retrieved on March
2007 from: http://www.gotw.ca/gotw/049.htm.
Sutter, H. 1999: Exceptional C++: 47 Engineering Puzzles, Addison Wesley, 1999, retrieved on
20.08.2014 from http://aalmos.kaniserver.net/doc/cpp/Exceptional%20C%2B%2B.pdf
Sutter, H. 2002: More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and
Solutions, Addison Wesley, 2002
Wegner, P. 1990: Concepts and Paradigms of Object-Oriented Programming. ACM SIGPLAN
OOPS Messenger, v.1, i.1, 7-87.
Yaroshenko, . 1995: The Beginner's Guide to C++, Wrox Press Inc., NewYork, NY, US.

A. ................................................................................................................ 1081
B. ........................................................................................................................... 1093
C. - C++ ................................................................................................................................. 1095
D. ................................................................................................................... 1097
E. .................................................................................................................. 1101

A

:

.
:
.1 ........................................................................................................................................................ 1081
.2 ........................................................................................................................................................ 1082
.2.1 && ........................................................................................................................................1083
.2.2 || .......................................................................................................................................1083
.2.3 ! .......................................................................................................................................1084
.2.4 ..............................................................................................................................................1084
.2.5 ..................................................................................................................................1085
.2.6 ................................................................................................................................................1086
.2.6.1 Sheffer |............................................................................................................1086
.2.6.2 ||: ....................................................................................................................1086
.2.6.3 v...............................................................................................................1086
.2.7 ..............................................................................................................................................1086
.3 ........................................................................................................................... 1087
.4 ........................................................................................................................................................ 1087
.5 ........................................................................................................................... 1089
.6 ............................................................................................................................................................. 1090
.7 .................................................................................................................................. 1091
................................................................................................................................................................. 1091

:

,

.
.5 :
.

.

.1
:
{ P, Q, R, P0, Q0, R0, P1, Q1, R1, ..., F, &&, ||, , , !, (, ) }
P, Q, R (propositional symbols).
.
1081
1082

F (constant) .
&&, ||, , , ! (connectives) -
(binary, 2-place) !
(unary, 1-place) . F
(0-place connective).

:
= | F | "!", |
"(", , , , ")" ;
= "P" | "Q" | "R" |
"P0" | "Q0" | "R0" | "P1" | "Q1" | "R1" | ... ;
= "&&" | "||" | "" | "" ;

P, Q2, R4
.
P, Q2, R4
!P, !Q2, !R4
"!", .
P, Q2, R4, !P, !Q2, !R4
(!P && R4), (Q2 || !Q2), (P !R4), (Q2 R4)
"(", , , , ")".
(!P && R4), (Q2 || !Q2), (P !R4), (Q2 R4)
!(!P && R4), !(Q2 || !Q2), !(P !R4), !(Q2 R4)
"!", .
(!P && R4), !R4, P, (Q2 R4), !Q2, (P !R4)
((!P && R4) || !R4),
(P && (Q2 R4)),
((P && (Q2 R4)) || !Q2),
((P !R4) || (Q2 R4))
"(", , , , ")".

, -
. :

, :
!P && R4 (!P && R4),
Q2 || !Q2 (Q2 || !Q2),
P !R4 (P !R4),
Q2 R4 (Q2 R4),
(!P && R4) || !R4 ((!P && R4) || !R4),
P && (Q2 R4) (P && (Q2 R4)),
(P && (Q2 R4)) || !Q2 ((P && (Q2 R4)) || !Q2),
(P !R4) || (Q2 R4) ((P !R4) || (Q2 R4))

.2
(P, P0, P1,... Q, Q0, Q1,... R, R0, R1,...)
false (, ) true (, ). F
false.
1083


() .
,
&&, ||, !. -
, (truth tables).

.2.1 &&
. -1 - A B A && B B && A
(conjunction) &&. false false false false
: A false - false true false false
B false A && B B && true false false false
true true true true
A false.
. -1: &&.
.
&& : A && B B && A
.

&&;
A true ( ) B
true ( ) A && B B && A.

P x 5 (x > 5) Q
x 10 (x < 10). x
5 10 (5 < x < 10)
x 5

x 10
P && Q. x 6, P Q , true.
&& P && Q true, -
.
x 17, P ( true) Q ( false).
&& P && Q false,
.

: , , and (
Pascal, Basic ).
, cand
, : A cand B A false
(), false -
B. &&
C++ (5.6).

.2.2 ||
. -2 (disjunction) ||.
|| :
A, B true ( )
A || B B || A true ( ).
, A || B false A
B false.
1084

|| : A || B A B A || B B || A
B || A . false false false false
false true true true
true false true true
x = 15 true true true true
x - . -2: ||.
2 3. -
: x 2 x
3. P x 2 Q x -
3. P false, Q true.
P || Q true.

: , , or ( Pascal,
Basic ).
( cand), cor:
A cor B A true (),
true B.
5.6 || C++.

.2.3 !
. -3 (ne- A !A
gation) !, : false true
A true, , !A false, - true false
, A false, , !A . -3: -
true, . !.
~ not (Pascal, Basic).

.2.4
. -3 , A B AB BA
(implication). false false true true
A B A (antecedent) false true true false
B (consequent) (apodo- true false false true
true true true true
sis). A B if
. -4: .
A then B, ( ) A ( A B B A -
) B. 1 .
-

. P Q
. P Q :
.
P, Q
.
: P true, Q ( 4 . -3)
-
. , .
true P Q.

1 , if ... then .
1085

P true, Q false (
3) P Q : -
. -
. false P Q.
2 P false Q true,
.
, : ;
; :
; ! ( )
, P Q true.
, 1, false.

. , , P Q
true.
... . ..
:



, .
, , . -
2...
, . A B
B A.
A B A B A B , , if A then B.
:
. A-4 false < true C++
P Q C++ P <= Q.

.2.5
. -4 , A B AB BA
(double implica- false false true true
tion). ; false true false false
A B ( true false false false
true true true true
true false) A B -
. -5: .
( true), A B -
( false).
, A B B A
.

x = 17. P "x > 10" Q "x < 35", P Q
P Q true. P1 "x < 10" Q1 "x > 35"
P1 Q1 P1 Q1 false. P Q1
P true, Q1 false.

2 (material implication)
(strict implication) (modal
logics) "" .
1086

A B A B A if and only if B.
A B : ,
.
:
C++ P Q P == Q.

.2.6
, 24 22 .
; !
, .
.
, nand nor
:
.

.2.6.1 Sheffer |
. -6 | Sheffer (Shef-
fer's stroke). . -1 A | B -
!(A && B).
nand ( and: not and).

.2.6.2 ||:
and or.
. -7 . . -2 ,
, A B !(A && B).
nor (not or).

.2.6.3 v
(exclusive disjunction) . -8
(. -2) . A v B
true A B true. . -
4 !(A B).
xor (Turbo Pascal).

.2.7
-
(P, Q). . -


, :
((P0 && P1) || (P2 && P1)) && P3
A B A |B A B A B A B AvB
false false true false false True False false false
false true true false true False False true true
true false true true false False True false true
true true false true true False True true false
. -6: - . -7: - . -8: -
|. v.
1087

:
true P0, false P1, true P2, false P3
P0 && P1 false (&&, . 3),
P2 && P1 false (&&, . 3),
(P0 && P1) || (P2 && P1) false (||, . 1)
((P0 && P1) || (P2 && P1)) && P3 false (&&, . 1)3.

.3
. (tautology)
true
.
:
!F
A || (!A)
( && (B || C)) (( && B) || ( && C))
( || (B && C)) (( || B) && ( || C))
(!( || B)) ((!) && (!B))
(!( && B)) ((!) || (!B))
B B (equivalent).
.
:
( && (B || C)) (( && B) || ( && C))
( || (B && C)) (( || B) && ( || C))
(!( || B)) ((!) && (!B))
(!( && B)) ((!) || (!B))
,
(. 1):
( B) ((!) || B)
(. 1):
( || B) B ( || B)
:
(A && B) A (A && B) B
(. 2):
( v B) (( || B) && (!( && B)))
( v B) (( && (!B)) || ((!) && B))

.4
|| (!) A !A A || (!A)
. false true true
. . -9. - true false true
, ' . -9:
A||
true.
(!A).

3 , , false,
&& P3 P3 false (&&, . 1, 3).
1088


(P && Q) P P Q P && Q (P && Q) P
. - false false false true
P, Q, P && Q, (P && false true false true
true false false true
Q) P.
true true true true
P, Q . -10:
4 (= 22) . (P && Q) P.
. -10.

, .
:
B.

: && B || B.
-
, A B A && B A || B
( && B) false false false false
false true false true
true.4 4 true false false true
. : true true true true
true - . -11:
true, : : A
&& B A || B. && B A || B.

, (-9) 2 , (-10, -11)


4 . ,
2 .
.
, ,

.
, ,
:
A, B A ,B A& & B A& & B
(1) ( 2) ( 3) ( 4)
&& B&& A A B
: "
&& ". : " &&
". ,
&&:
&& && .
|| :
A B
( 5) ( 6)
A || B A || B

:
|| .

4 , && || ( && ) (||)


.
1089

, , ,
. :
&& || .
1. && .
2. (1) (3).
3. || (2) (5).
,
.
. && ||
:
( && ) E ( || )
: ( && ) e ( || ).
: S E T S e T.
, : S E T S T
.

.5
. ..
: x x2 0.
(.. predicate calculus)
( )
(.. Z, R ). ,
:
x x2 0
"" " " (universal
quantifier). x x2 0 (predicate)
().
(existential), ..:
.
:
x x2 == 0
"" "" (existen-
tial quantifier). "==" " ":5

, ..:
y y2 0 t t2 == 0
(bound) .
:
x x + f(x, y) > 0
x , : u u + f(u,y) > 0 -
y: y (free) .
"" , , .., ..:
y (x x + y == 0)
: y x x + y == 0. x x + y == 0 x
, ..: z z + y
== 0 y . y

5 "==" "="; "=" C++ . "=="


C++.
1090

. x; ,
: x (x x + x == 0)
! ' .. ,
.
: x ((x > 0 ) (-x < 0)). :
x (x > 0) (-x < 0)) : x > 0 (-x < 0))
.
, .. ,
( -
).
.
:
x P( x ) P( a )
( a) ( a)
P( a ) x P( x )
: ( ) x P(x)
() a P(a). : ( ) (
) a P(a) x
P(x).
:
x P( x ) P( q )

P( q ) x P( x )
: ( ) x P(x)
P(q), q . : ( -
) q P(q)
x P(x).

.6
(==). :
1. () : a b !(a == b)
2. : x x == x
3. : S(n)
n m == n, ,
n m S[m/n]:
m n,S( n) n m ,S( n)
(A1) (A2)
S[ m / n] S[ m / n]
,
S(y) x x2 + y == 0
z == y
:
x x2 + z == 0
n m
n, .
1
, :
: x == y : y == x
1. x == y
2. x == x
1091

x == y ( 1.) S(x) x == x 2.
(2) x y
:
3. y == x.
...

2
:
: (!(k N))&& ((y == 2k+1) && (x == (k+1)2))
: (k == N)) && ((y == 2N+1) && (x == (N+1)2))
1. (!(k N))&&((y == 2k+1)&&(x == (k+1)2))
2. !( k N) 1. .. (3) .4
3. !(!(k == N)) 2.
4. k == N 3. (!(!)) .3
5. (y == 2k+1) && (x == (k+1)2) 1. .. (4) .4
6. (y == 2N+1) && (x == (N+1) ) 2 4.,5. .. (A2)
7. (k == N) && ((y == 2N+1) && (x == (N+1)2) 4.,6. .. (1) .4
...

.7
(
. 2, , 4
).
..
int ( Z) double ( R).
:
(a == b) (!(a b))
(a b) (!(a == b)) ((a < b) || (a > b))
(!(a < b)) (a b) ((a > b) || (a == b))
(!(a > b)) (a b) ((a < b) || (a == b))
((a b) && (a b)) (a == b)
((a b) || (a < b)) true ((a > b) || (a b)) true [( || (!A)) true]
((a b) && (a < b)) false ((a > b) && (a b)) false [( && (!A)) false]
( && ( || C)) (( && ) || ( && C))
( || ( && C)) (( || ) && ( || C))
(!( || )) ((!) && (!))
(!( && )) ((!) || (!))
(1)-(6) A.4.

-1 :
) (A B) ((! A) || B) ) A (A || B) B (A || B)
-2 :
) ( xor ) (( || ) && (!( && )))
) ( xor ) (( && (!)) || ((!) && ))
) ( xor ) (!( ))
1092

B

#include <cmath> -
C++ C.
, ,
.
, :
double long double. abs()
: abs() (int), labs() (long), fabs() (double), fabsl() (long double).
: 1 ( ) -
, .. . 2 , ..
. 3 , .. 2. 1,
2 a. 2, -
a1 a2. , -
:
atan2 (. 4), double
(. 5) double (. 6). :
atan2l (. 4), long
double (. 5) long double (. 6).

1093
1094 B

C++
cmath
.

|a| 1 abs int int
labs long long
fabs double double
long double long double
fabsl
. a 1 floor double double
. . floorl long double long double

. a 1 ceil double double
. . ceill long double long double
.
a1 mod a2 2 fmod double double
fmodl long double long double
. 1 sqrt double double
sqrtl long double long double
2 hypotl double double
hypotl long double long double
a 1 sin double double
sinl long double long double
a 1 cos double double
cosl long double long double
a 1 tan double double
tanl long double long double
a 1 asin double double
asinl long double long double
a 1 acos double double
acosl long double long double
a 1 atan double double
atanl long double long double
2 atan2 double double
atan2l long double long double
1 exp double double
expl long double long double
sinha 1 sinh double double
sinhl long double long double
cosha 1 cosh double double
coshl long double long double
tanha 1 tanh double double
tanhl long double long double
lna 1 log double double
logl long double long double
a 1 log10 double double
log10l long double long double
2 pow double double
powl long double long double
10 10a 1 pow10 int double
pow10l int long double

C
- C++
. C-1, , - C++ ( -
) (ISO 2011).
(ISO 2003).
. C-1: - C++
alignas * continue friend register true
alignof * decltype * goto reinterpret_cast try
asm default if return typedef
auto delete inline short typeid
bool do int signed typename
break double long sizeof union
case dynamic_cast mutable static unsigned
catch else namespace static_assert * using
char enum new static_cast virtual
char16_t * explicit noexcept * struct void
char32_t * export nullptr * switch volatile
class extern operator template wchar_t
const false private this while
constexpr * float protected thread_local *
const_cast for public throw
. C-2 - C++, C -
.
.
,
.
. C-2: C++

<% { and && and_eq &=
%> } bitor | or_eq |=
<: [ or || xor_eq =
:> ] xor not !
%: # compl not_eq !=
%:%: ## bitand &
, -
. -
. .
. C-3: 2 3
2 3 2 3 2 3
%: ??= # <: ??( [ <% ??< {
??/ \ :> ??) ] %> ??> }
?? ??! | ??-

1095
1096 C

D

:
D.1 ISO 646 (ASCII) ................................................................................................................................................ 1097
D.2 928 ......................................................................................................................................... 1098
D.3 927 ......................................................................................................................................... 1099

D.1 ISO 646 (ASCII)


ASCII (American Standard Code for Information Interchange)
ISO 646. 128
0 127. 32 (0 .. 31) (127) -
(. -1).
48 57 , '
:
static_cast<char>(48)='0' static_cast<char>(57)='9'
65 90
. 97 122
. 32:
static_cast<int>() == static_cast<int>()-32
0 31 : -
<Ctrl> 64
. .. <ETX> = static_cast<char>(3), -
<Ctrl> <C> ('C' = static_cast<char>(67)).
<Ctrl-C> "^C". -
,
.
, -
. .. -
:
BEL (static_cast<char>(7)):
cout<<static_cast<char>(7) cout << '\a'
, :
(alert).
BS (static_cast<char>(8)):
cout<<static_cast<char>(8) cout << '\b'
(Back Space).
1097
1098 D

0 NUL 16 DLE 32 SP 48 0 64 @ 80 P 96 ` 112 p


1 SOH 17 DC1 33 ! 49 1 65 A 81 Q 97 a 113 q
2 STX 18 DC2 34 " 50 2 66 B 82 R 98 b 114 r
3 ETX 19 DC3 35 # 51 3 67 C 83 S 99 c 115 s
4 EOT 20 DC4 36 $ 52 4 68 D 84 T 100 d 116 t
5 ENQ 21 NAK 37 % 53 5 69 E 85 U 101 e 117 u
6 ACK 22 SYN 38 & 54 6 70 F 86 V 102 f 118 v
7 BEL 23 ETB 39 ' 55 7 71 G 87 W 103 g 119 w
8 BS 24 CAN 40 ( 56 8 72 H 88 X 104 h 120 x
9 HT 25 EM 41 ) 57 9 73 I 89 Y 105 i 121 y
10 LF 26 SUB 42 * 58 : 74 J 90 Z 106 j 122 z
11 VT 27 ESC 43 + 59 ; 75 K 91 [ 107 k 123 {
12 FF 28 FS 44 , 60 < 76 L 92 \ 108 124 |
13 CR 29 GS 45 - 61 = 77 M 93 ] 109 m 125 }
14 SO 30 RS 46 . 62 > 78 N 94 ^ 110 n 126 ~
15 SI 31 US 47 / 63 ? 79 O 95 _ 111 o 127 DEL

. -1 ISO 646 (ASCII).

HT (static_cast<char>(9)):
cout<<static_cast<char>(9) cout << '\t'
(Horizontal Tab).
LF (static_cast<char>(10)):
cout<<static_cast<char>(10) cout << '\n'
(Line Feed).
VT (static_cast<char>(11)):
cout<<static_cast<char>(11) cout << '\v' -
(Vertical Tab).
FF (static_cast<char>(12)):
cout<<static_cast<char>(12) cout << '\f' (
) (Form Feed).
CR (static_cast<char>(13)):
cout << static_cast<char>(13) cout << '\r'
(Carriage Return).
DEL (static_cast<char>(127)):
(DElete Line).
static_cast<char>(26) (<Ctrl>), MS DOS, text.
<ETX> (static_cast<char>(3) = ^C - End
of TeXt).

.

D.2 928
928 (. -3), 48
.
0..31 127..159 ,
ISO ISO 8859.
:
NBSP (static_cast<char>(160)): No-Break SPace = . "-
" .
(text formatters)
.
SHY (static_cast<char>(173)): Soft HYphen = - .
(static_cast<char>(45)).
1099

0 NUL 32 SP 64 @ 96 ` 128 160 NBSP 192 224


1 SOH 33 ! 65 A 97 a 129 161 193 225
2 STX 34 " 66 B 98 b 130 162 194 226
3 ETX 35 # 67 C 99 c 131 163 195 227
4 EOT 36 $ 68 D 100 d 132 164 196 228
5 ENQ 37 % 69 E 101 e 133 165 197 229
6 ACK 38 & 70 F 102 f 134 166 198 230
7 BEL 39 ' 71 G 103 g 135 167 199 231
8 BS 40 ( 72 H 104 h 136 168 200 232
9 HT 41 ) 73 I 105 i 137 169 201 233
10 LF 42 * 74 J 106 j 138 202 234
11 VT 43 + 75 K 107 k 139 171 203 235
12 FF 44 , 76 L 108 140 172 204 236
13 CR 45 - 77 M 109 m 141 173 SHY 205 237
14 SO 46 . 78 N 110 n 142 174 206 238
15 SI 47 / 79 O 111 o 143 175 207 239
16 DLE 48 0 80 P 112 p 144 176 208 240
17 DC1 49 1 81 Q 113 q 145 177 209 241
18 DC2 50 2 82 R 114 r 146 178 242
19 DC3 51 3 83 S 115 s 147 179 211 243
20 DC4 52 4 84 T 116 t 148 180 212 244
21 NAK 53 5 85 U 117 u 149 181 213 245
22 SYN 54 6 86 V 118 v 150 182 214 246
23 ETB 55 7 87 W 119 w 151 183 215 247
24 CAN 56 8 88 X 120 x 152 184 216 248
25 EM 57 9 89 Y 121 y 153 185 217 249
26 SUB 58 : 90 Z 122 z 154 186 218 250
27 ESC 59 ; 91 [ 123 { 155 187 219 251
28 FS 60 < 92 \ 124 | 156 188 220 252
29 GS 61 = 93 ] 125 } 157 189 221 253
30 RS 62 > 94 ^ 126 ~ 158 190 222 254
31 US 63 ? 95 _ 127 DEL 159 191 223 255

. -2 928.


( ).
MS Windows -
928 (. -4). ''
128 .. 159 . -
Windows ( -
ISO 8859 )
.

D.3 927
927
128 (
) . .
1100 D

E

, ,
. .
, '
:
, ,
,

.
: a + b + c (a + b) + c, a = b = c
a = (b = c).
! a*b + c/d + f(e)
: (a*b + c/d) + f(e).
(a*b + c/d) f(e).
a*b c/d.
C++ "".

.

, ().
a b. :
1. a, b long double,
long double .
2. , a, b double,
double .
3. , a, b float,
float .
4. , a b ( ) (integral
promotion), : ( ) a, b "
" (char, short int, signed unsigned), int
unsigned int ( int)
a, b unsigned long,
unsigned long .

1101
1102 E



.
0 . ()
1 ::
::
::
2 ., ->
() []
( )
( )
-l++
-l--
. . () typeid(), typeid()
(.) dynamic_cast< >()
. . () static_cast< >()
const reinterpret_cast<>()
const_cast<>()
3 sizeof , sizeof()
. ++ -l, -- -l
(.) ~
!
- , +
&
*
. . new
. . . new ()
new ()
. . new () ()
delete
delete []
(C) ()
4 .*
->*
5 *
/
%
6 +
-
5. , a, b long int unsigned int,

unsigned int long int
unsigned int long int

unsigned long int.
6. , a, b long, long
.
7. , a, b unsigned,
unsigned .
8. int.
1103

()

.
5 *
/
%
6 +
-
7 <<
>>
8 <
<=
>
>=
9 ==
!=
10 and &
11 xor ^
12 or |
13 and &&
14 or ||
15 -l =
. -l *=
-l /=
-l %=
-l +=
-l -=
. . -l <<=
. -l >>=
. . and -l &=
. . or -l |=
. . xor -l ^=
16 ? :
17 throw
18 ,
+, -, *, /
.
+, - ().
.
1104 E

.................................................................................................................................................... 1107
................................................................................................................................ 1123
- ....................................................................................................... 1133
- ......................................................................................................... 1137

; 71 , 135
\n 21, 198, 206
\r 205 -- 142
-- 602, 616, 720
766 -- 76
766 -- 15, 383
230 a, 239
, 137 1007
424 385
30 197
-- 31 63
-- 31 , 348
55 , 350, 662, 669
, 543 { } GE SE 719
992, 1005 1086
-- 1006 , 212
25 604
300, 310 499
30, 37 , 663, 701, 720
1081 string 273
4 , 1086
-- Horner 238 358
-- 7 9
-- 7 192, 433, 656
1079 -- 657
20 -- 716
693 751, 1003
763, 992, 994 -- 617
193 433
string 263 19, 656
/ 192 50, 79
184, 420 -- string 262
( ) 241, 242 689
-- 243 1084
-- 1018 -- 77
250, 999 ' , 246
string 270 10
1086 107, 548
, 395 992, 1027

1107
1108

12, 76 -- 191
-- binSearch() 254 -- 212
-- 182, 359 Liskov 843, 844
77
15 -- 44, 169
7 -- 700
442 9
() 712, 948, 969
333 -- 948
1082 -- - 713, 949
982 -- 712, 949
764 swap() 712
320, 499, 500 969
, 982 358
425 293, 411
, 26 47
30, 560 , () 160
475 () 875
543
, () 68, 1101 540
843
-- 27 63, 316
540 -- 766
-- 540 -- 320
-- 540 -- 321
-- 540 -- 730
55 -- - 439
32 -- this 668
, 279 977, 978
Fibonacci 423 - -- 494
, 1080 -- 867
507, 978
-- 193 -- 346
-- 197 -- 316
-- ascii 190 -- 320
-- 254 -- 320
-- 197 -- 321
-- 191 -- 496
190, 455 -- void* 515
-- 218 150
text 205, 206 -- 15, 80, 383
-- 196 582
-- 191 -- 582
-- 613 -- 582
-- 190 -- 586
190, 455 610
-- 190 , bool
() 190 127
-- 190 135
1109

-- - 693
952 -- 5
405 -- 694
952 -- 383
, 137 -- 5
691
-- 7 , 978
-- 7 string 273, 274
-- 8 196
-- 8 , 1082
875 , 1079
843 253
20 . 113
205 , 166
-- 205 506. 978
243 20, 25
, 196
-- 197 1019
-- 229 107
-- string 264 1026
, 1026
4 , 25
384 179
4 191
31 21
222 878
-- 320 -- o 395
1018 --, 611, 656, 657
red-black 1018 7, 44, 316
1085 -- 499
44, 46, 353 446
-- 293 1078
, 744 1081
511
-- 698 392
-- 406 76
-- 406 433
437 -- 766
-- 663, 701, 720 -- 442
-- 700 - -- 439
-- 981 -- 451, 478
-- 622, 731 -- 440
-- 1006 -- 436
-- 1006 -- 594
438, 694, 698 -- 436
-- 605 384
, 693
-- 693 250, 999
-- 693 -- 1018
1110

190, 455 -- 150


494, 498 1085
293 927 1099
493 928 1098
-- 505 167, 353
866 -- 308
-- 868, 896 -- 437
500 -- 166
-- 511 --, 688
844 218
, 541 , 689
31
384 193, 364
698 7
20, 21 -- 135
613 -- 113
363 -- , 48, 294
160 -- (if, ifelse) 112
877 -- 295
857 -- break 304
-- 875 -- continue 310
--/ 860 -- do-while 303
499 -- goto 308
861 -- for 151, 299
, 257 -- if 115
51 -- return 161, 353
-- 227 -- switch 305
o -- while 136
10 -- 135
-- 996 -- 115
4 -- 120
10 -- 115
28, 560 114, 355
, 705 71
, 239 -- (if) 117
292 1026
9 416, 419, 927
, 37 -- 927
48, 294, 403 -- 712, 948, 969
77 -- 179, 416
-- string 262 () -- 451, 616
-- 295 -- 416
-- 67 -- 418, 928, 933
-- = 664 -- 416
, 149 -- bad_alloc 504
231 RTTI
4 124
-- 384 409, 960
-- 37 -- 951
1111

-- float 560, 565


-- 26 604
10 308
-- 205 -- 308
-- 995 -- case 305
4 -- default 305
-- 10 473, 766
977, 978 ()- 602
, 141 57, 561
, 13
76 , 757
, 83 35
135
540
-- 142
-- 150 383
-- -, 137 1083
-- n+ 304 1086
-- 137, 150 573, 685
-- 143
340
-- 4
-- 4 358
-- text 205, 206 354
-- 196 956
161 1085
139
-- 166, 356
112 -- 166, 353, 356
120 -- 13
117 -- 15
' -- 246 -- do-while 303
, 9 -- ifelse 121
27 -- n+ 305
-- while 143
-- 398 -- 717
409 166, 353
-- 400, 405 -- 8
-- () 751 13, 1084
-- 739 -- 1086
-- 440, 485 -- 8
107 557
438, 694, 698 57
9 191
444, 456 613

-- 543 656
-- 29 439, 662, 708, 720
-- 541 -- 861
1112

753, 1085 -- 964


-- o 10 -- 876
-- o 10 34, 168
1 12, 1085
() , 384 -- 239
190 -- 239
205 -- 239
115 14
20, 25
1006 766
/ 192 7
, 27, 561 () -- 7, 9
192, 433, 602 -- 7
-- 602, 616, 720 656
-- 604 - 46, 1095
() -- 875 196
-- 843 705
-- 952 527, 723. 970
843 , 35
-- 693 1080
-- 691 120
-- 613 91
-- 604 -- , 127
-- 956 1079
-- 613 1079
-- 451, 616 , 1081
-- C++ 936 6
-- 853, 889 12
-- -- 683 -- 1 12, 1085
-- - 843 12, 1077
-- 510, 740
-- 987 , 141
192, 605 582
-- 613 390
-- 594 560
-- 843 44
-- 952 , 149
-- 952 231
975, 994 392
966, 992 192, 473, 605, 656
-- 875 -- 730
- = 192, 605 -- 875
-- 688 -- 613
442 -- 857
-- 690 -- inline 615
442, 642 -- virtual 857
-- 621 -- 851
192, 842 141
-- 877 436
1113

-- 604
-- 442 -- 268
-- 604 -- 190
437 -- 25, 268
-- - 754 ( ) 657
-- 736 , 7
-- 613 16
-- private 664
-- 735 -- 499
-- 734 293, 411
- -- = 605 -- 506, 978
160 293, 411
12 -- 493
, 981 -- 499
44 -- 293, 411
-- 44, 169 -- 293, 411, 494
-- 358 free store 494
-- 1085 -- 990
44, 46 -- 505
44, 63 293, 411
-- 494 -- 1018
-- 1085 -- 499
-- 354 692
44, 62 1078
-- - 494 190
-- 150 456
-- 48 , 38
-- 48 , 38
-- 656
44, 46 9
355, 357 7
44
-- switch 307 690
44, 45, 62 420
-- 353
9 24
C++ 179 -- define 582
572 -- ifdef 582
736 -- ifndef 585
, () 68, 1101 -- include 23
731 -- undef 582
-- 622, 731 31
698, 732 160
9 12
507, 978 549
134 355
137, 150 -- try 935
190, 455 23, 44, 46
115 -- 613
1114

-- 55 -- 691
21, 593 -- 543
-, 693 -- 29
-- 541
-- 12 -- float 566
-- 12 -- 557
7 -- 91
, 12, 76 -- 27, 561
164 -- - 543
165 -- 27
, 160, 938 -- 298
279 -- 567
25 68, 310
38 -- bool 127
992 , 493
992 990
1081
-- 160, 938
36 -- 160
205 , () 602
-- 205
-- 205 -- 586
() , 383, 384 -- 409
843 -- 409
-- 853, 889 -- 956
952 -- 406, 953
363 -- 952
-- 424 -- 964
-- 348, 364 -- 405
-- - 346, 364 -- 406
-- 436 975, 994
-- 406, 953, 960 966
-- - 231, 335, 364 -- 1007
-- 364 -- 967
-- 392 -- 992
-- 169, 364 966, 992
-- const 234 192, 606
in 363 294
in out 363 -- const 294
-- main 338 -- volatile 294
out 363 , 1006
-- unsigned 170, 350, 547 695
-- 164 , 510
-- 390
-- 605 222
-- 164 -- 230
63 241, 242
-- 385
-- 300, 310 -- 475
1115

-- 222 320
-- 511 1023
-- 500 , 1101
-- 340 7, 14
- -- 231, 335 -- 9
-- -- 76
-- / 860 15
-- 316 -- 9
-- 281 -- 47
-- 327 76
-- 9
333, 334 76
222 -- 10
222, 224 -- 12
241, 247 -- 12
330 -- 10
241, 245, 257 12, 14
-- 223
689 19, 656
1021 7
, 1006 -- 8
3 -- 384
4 -- 12
444 10
--, 690 38
, 238 418, 928, 933
117 10
978 744, 806, 956
295 24
876 -- 24
1030 107
688 390
992, 1031 -- 605
327 private 664
333, 334 967
862 761, 992, 994
-- 851 763, 993, 994
-- 862 -- 996
-- 863 -- 995
-- 863 -- 994
244, 992, 1030 763, 994
, (Horner) 235 563
1085 - , 543
-- 1085 540
-- 1085 763, 994
-- 1086 716
164 1083
27 1078
, 29 1077
1116

12 411, 967, 976, 992


1101 --, 293, 411
, 992 -- 420
160 4
10 51
124 -- 4
-- 4
192 222
-- 205 -- 222
-- 205 , 496
-- 205 , 563
-- 364 875
-- / string 278 757
-- 212 241, 247
406 , 253
, 6 , 1079
, 12
68, 1101 , 1077
8
333 8
190 BNF 17
-- 193 25
-- 218 863
-- 196 1026
99 330
-- open() 212 13, 1084
7 -- 1086
656
, 30, 560 -- 694

-- 1 543
-- 30 -- 2 543
-- 31 406
-- 31 698
-- 27 690
-- 1078 22, 160
-- 55 182, 359
-- 77 -- 586
, 27 -- 610
735 -- 405
65 -- 698
355, 357 -- 363
293 -- 22, 161
734 -- 409
406 -- 398
-- 406 -- 956
-- 406 34, 168
, 698 -- 160
, 656 -- C++ 179
1117

-- 160 -- false 79
-- 165 -- true 79
-- 392 992
-- 363 -- 1019
160, 938 -- 1026
() 160 -- 1026
-- 405 -- 1023
179, 564 -- 1026
-- C++ 34 -- 1023
-- get 720 -- 1026
-- set 721 160
-- 395 222, 224
-- 160, 162 223
-- - = 192, 605 160
-- 698, 732 20, 21
-- inline 390, 584 7
-- main 170 7
-- void 160, 345 , 239
-- 698 191
160 688
22, 161 -- 693
-- 398 - -- 693
-- 370 -- 690
try 935 -- 692
, 751, 1003 -- 688
, 527 -- -- 688
25 -- -- 690
-- string 269 690
1078 1023
-- 1078 571
-- 1078 572
-- Sheffer 1082 -- 571
-- 1078 -- 570
9 571
1018 -- 563, 571
992, 1018 384
1080 320
-- 1081 39
-- 1081 22, 161
-- 1081 , 293, 494
() 68, 1101
36 106
, 15 241, 245, 999
114, 355 -- ' 246
-- 257
-- 298 -- 253
-- o 10 1083
-- o 10 617
-- 83 47
1118

-- 358 143
71
-- 32 330
-- 31 pimpl 764
400, 405 44
-- 440 50
-- 92 -- 44, 169
-- ! 90, 1080 - -- 439
-- % 32 -- 169
-- %= 67, 296 () -- 63
-- & () 63 -- 390
-- & () 550 -- 605
-- && 14, 90, 127, 1079 -- 160
-- () 751 -- 321, 498
-- * () 32 -- (Horner) 235
-- *= 67, 296 -- - 138, 244
-- * () 63, 320 -- -l 295
-- + 32, 320, 323 -- -r 295
-- + string 263 -- -l 295
-- ++ 67, 296, 320 -- 149
-- ++ bool 297 -- 149
-- += 67, 296 611, 657
-- += string 269 1026
-- , 310 switch 307
-- - 32, 323 166
-- -> 764 21
-- = 48, 93, 128, 294, 403, 664, 712 334
-- == 76, 90, 128 , 717
-- -- 67, 296 1081
-- -= 67, 296 212
-- / 32 -l 295
-- /= 67, 296 164
--<= 1081
-- << 23, 27, 99, 197 -- 866
-- << string 263 868, 896
-- >> 52, 193 444, 456
-- >> string 263 -- 65
-- delete 498, 501 -- C 66
-- new 496, 504 -- const 319
-- sizeof 62 44, 45, 62
-- typeid 62 -- 55
-- [] string 274 76
-- ^ 550 107, 548
-- | () 550 -- 55
-- || 90, 127, 1079 -- 952
-- ~ 550 -- 107
-- 91 -- RTTI
845 -- 440
virtual -- 861 -- 573
1119

-- 294 , 8
-- 867
-- 731 690
-- 106 386
-- 350, 662, 669 (, ) 743
-- 496 -- 955
-- void* 515 8
-- bad_alloc 504 8
-- cv 294 1086
-- 496 , -138, 244
-- 223 35
-- bitmask 557 , 541
, 254 (if) 117
, 994 238

384
, 764 -- 20
, 690 -- 20, 21
1085 25
499 -- 281
843 20, 21
30, 58, 362, 545, 562 , 987
844 , 695
(_) 46 749
398 353
370 1009
499
27
27 241
Liskov, 843, 844 7
, 844 20
442, 642 44
843 447
549
-- 137 552
-- 137 552
-- 149 , 30, 560
-- 149 A
-- 68, 310 a_kind_of 845
-- bool , 127 Ada 44, 363, 432
7 ALGOL 8, 44, 432
-- 7 and 91, 1079
, 543 APL 8
string 276 ASCII 1097
160 ascii, 190
1024 auto_ptr 978, 983
-- 1024 B
562 back_insert_iterator 997
621 Backus - Naur Form 17
1120

bad_alloc, 504, 937 DBL_MIN 56


bad_cast, 869, 896 default, 305
bad_typeid 938 deque 992
BASIC 8 define, 582
bitset 1034 delete, 498, 501
BNF, 17 domain_error (C++) 938
bool 56, 97 double ended queue deque
boolalpha 99 do-while, 303
break, 304 -- 303
C double 45
C 44, 435, 544 dynamic_cast 866
C# 44, 952 E
C++ 8, 16 e 35
-- 34 EDOM 923
cand 1079 else 112
carriage return CR endif, 585
case, 305 endl 21, 198
catch 416 enum 107
-- (...) 418 EOF 216
cctype 104 eof (cin) 196
cerr 205 EOT (End Of Transmission), <ctrl-D> 196
char 56, 99, 101 ERANGE 362, 923
--* string 651 errno 362. 922
signed -- 56, 99 ETX (End of TeXt), <ctrl-C> 196
unsigned -- 56, 99, 101 EXIT_FAILURE 172
cin 51, 205 explicit 733
cin.eof() 196 F
class 610, 617 false
climits 55 -- 79
clog 205 -- 91, 99
cmath 34, 36 Fibonacci, 423
COBOL 8, 432 FIFO, First In First Out
const 67, 318 FILE 434
-- 234 float 57
294, 318 560, 565
-- 318 for , 151, 299
const_cast 318 FORTRAN 8, 44, 432
continue, 310 free store 494
cor 1080 G
cout 21, 27, 205 get, 720
CR (Carriage Return) 205 goto, 308
<ctrl-C>, ETX (End of TeXt) 196 H
<ctrl-D>, EOT (End Of Transmission) 196 Habeas Corpus 602
<ctrl-Z> 196 has_a 690, 869
cv, 294 Horner, 235
cwctype 106 HUGE_VAL 362, 923
D HUGE_VALF 362
DBL_EPSILON 56 HUGE_VALL 362
DBL_MAX 56 I
1121

if 112 multiset 992, 1030


-- 115 mutable 736
-- 121 N
-- 117 n+, 304
ifdef, 582 -- 305
ifndef, 585 NaN 923
ifelse, 121 nand 1082
include, 23 new, 496, 504
inline 615 nor 1082
inline 390, 584 not 91
int 45, 55 not_eq 91
intN_t 544 NULL 322
long 56 numeric_limits 985
long long -- 56 O
short 56 or 91, 1080
uintN_t 544 ostream_iterator 995
unsigned -- 56 out_of_range (C++) 940, 1009
unsigned long -- 56 overflow_error (C++) 941
unsigned long long -- 56 P
unsigned short -- 56 Pascal 8, 44, 432, 826
INT_MAX 55 pimpl, 764
INT_MIN 55 PL/I 432
invalid_argument 939 priority_queue 992
iostream 23, 24 private 604, 617, 872
is_a 845, 869 -- 664
is_part_of 690 protected 854, 655, 872
ISO 646 1097 ptrdiff_t 326
J public 610, 617, 872
Java 927, 852 Q
L queue 992
l, 295 R
length_error 940 r, 295
LF 206 RAII 510, 714
LIFO, Last In First Out range_error 941
line feed LF red-black, 1018
Liskov, 843, 844 Resource Acquisition Is Initialization RAII
list 992 reinterpret_cast 445
logic_error 938 return, 161, 353, 921
long double 57 RPG 8
LONG_MAX 362 RTTI 868
LONG_MIN 362 runtime_error 941
LSP Liskov S
M set 992, 1020
main 22, 170 set, 721
-- 338 shared_ptr 985
map 992, 1027 Sheffer, 1082
math.h 36 size_t 269
modus ponens 13 size_type 269
multimap 992, 1031 sizeof 62, 259
1122

sort 991 try 416


sstream 278 -- 935
stack 992 typeid 62
static 357 typeinfo 62
static_cast 65 U
std 21. 593 UML 692
stdin 216 undef, 582
store, free 494 underflow_error 941
string 260 union 448
-- 270 unique_ptr 985
-- 273 unsigned , 170, 350
-- 262 using 22
273, 274 V
-- 262 VDM 15
/ -- 278 vector 991, 992
-- 269 virtual 857
-- 276 virtual 861
char* -- 651 void 345
struct 433, 617 void*, 515
swap(), 712 volatile, 294
switch, 305 vtable 860
-- 307 W
T wchar_t 56, 106, 954
text, 205, 206 weak_ptr 985
this, 668 while, 136
throw 416 -- 143
true WinMain 170
-- 79 wstring 284
-- 91, 99 Z
typedef 108 Z 15
typename 959

0-place connective = 1078 association class = 690
1-place connective = 1078 associative container = 992
2-place connective = 1078 associative memory = 1018
2's complement = 2 543 atomicity = 969
A automatic memory = 293, 358, 411
abstract class = 875 B
access, random file = back insertion = 1007
457 bag = 244, 1030
actual parameter = , base = ( ) 540
164
behavior = 656
adaptor, container =
-- diagram = -- 694
967
base class = 843
additive numeral system =
540 biased representation = 567
address = 7, 44 bidirectional iterator =
763, 992
address space = 499
bidirectional relationship =
addressing = 446
693
aggregation = 690
binary connective = 1078
algorithm = 4
binary file = ( )
correct -- = -- 7 190, 455
efficient -- = -- 7 binary search = 250
allocator = 990 binary search tree =
alphanumeric character = 1018
20 binding, method deferred = -
anomalies, update = 689 () 861
API, Windows Application Program Interface = bisection = 392
o 395 bit-field = 447
application, client = - 602 bitmap = 552
argument = 164 bitset = 552
arithmetic expression = 31 bitwise operation = 549
array = 222 blank = 20
-- component = -- 222 block = 355
-- component type = -- 223 body, function = 161
-- element = -- 222 boolean evaluation, short-circuit =
-- element index = -- 222 bool 128
sparse -- = -- 475 bottom-up implementation =
two-dimensional -- = -- 327 384

assembler = 8 bound variable = 1085

assembly language = 8 branching statements = 113

assignment statement = , buffer = 193


48 business rule = 673

1123
1124

byte = 44 -- type = -- 223


C composition = 688
calculus = compound statement = 114, 355
First Order Predicate -- Predicate Calculus computer = 7
Propositional -- = 12, 1077 digital -- = -- 7
call, function = 34 concatenation = 25
callback function = 395 concrete class = 875
candidate key = 621 condition = 10
capacity = 1009 input -- = -- o 10
cardinality = 1021 output -- = -- o 10
case, use = 695 verification -- = -- 83
casting = conditional expression =
dynamic -- = -- 866 298

reinterpretation -- = -- 445 conjunction, logical = 1079

catch, exception = 416 connective = 1078

character = 0-place -- = -- 1078

alphanumeric -- = -- 20 1-place -- = -- 1078

-- set = 20 2-place -- = -- 1078

child class = - 843 binary -- = -- 1078

choping = 571 unary -- = -- 1078

class = 192 conquer, divide and = 253

abstract -- = -- 875 consequence, rule of =


13
association -- = -- 690
constant = 27
base -- = -- 843
integer -- (literal) = 30
child -- = -- - 843
propositional -- = -- 1078
-- diagram = -- 693
constraint =
-- invariant = -- 602, 616, 720
entity integrity -- = --
-- member function = - 192
748
-- method = -- 192, 605
referential integrity -- = -- -
-- template = --, -- 952 748
concrete -- = -- 875 constructor = , 437, 698
container -- = -- 966 conversion -- = -- 732
derived -- = -- 843 copy -- = -- 663, 701, 720
generic -- = -- 952 default -- = 438, 698
parent -- = -- 843 fill -- = -- 1006
private -- member = -- 604 initializing -- = -- 700
public -- member = -- 604 move -- = -- 981
traits -- = -- 987 range -- = -- 1006
wrapper -- = -- 510 container = 966
client application = ()- associative -- = -- 992
602
-- adaptor = -- 967
coding = 14
-- class = 966
collating sequence = 759
reversible -- = -- 1007
collection, garbage = 982
content-addressable memory =
comments = 39 ,
compile time polymorphism = - 1018
863 contract, programming by =
compiler = 9 12
complement, 2's = 2 543 control = 4
component, array = 222 control variable = 150
1125

conversion constructor = directive, preprocessor =


732 24
conversion function = directory, file = 191
698 disjunction, logical = 1079
convertible = 867 disjunction, exclusive =
copy constructor = 663, 1082
701, 720 documentation = 47
correct program = domain, function =
partially -- = -- 12 160
totally -- = -- 12 -- of definition = 160, 938
correctness proof = 76 -- type = 496
cosine = 36 double ended queue deque
counted repetition, loop = double implication = 1081
137, 150 dynamic casting = 866
counter = 134 dynamic memory = 293
covariance = 863 dynamic variable = 494
creation, instance = 698 E
creator = 698 element, array = 222
cv-qualified type = cv 294 array -- index = -- 222
D ellipsis = 425
dangling pointer = 507, 978 empty statement = 115
data = , 4 encapsulation = 192, 606
-- processing = 4 entity-relationship diagram = -
-- validation = -- 384 - 693
input -- = -- 4 enumerated type = 107
output -- = -- 4 entity integrity constraint = -
debugging = (;) 748

declaration = epsilon = 57

forward -- - -- 744 equivalent propositions =


1083
variable -- = -- 44
ER entity-relationship
default constructor = 438, 698
error =
deferred binding, method =
() 861 propagated -- = -- 572

deque = 992 roundoff -- = -- 563

derived class = 843 error, standard = ()


205
design = 690
escape sequence = 25
destructor = 439, 662, 720
evaluation, short-circuit boolean =
diagram =
bool 128
class -- = -- 693
exception = 416, 927
entity-relationship -- = -- --
-- catch = -- 416
693
-- handling = -- 179, 416
structure -- = -- 693
object = -- 416
difference, set = 1026
-- safety = -- 712
difference, set symmetric =
1026 -- specification = -- 418

divide and conquer = 253 throwing = -- 416

digit = 20 exclusive disjunction = 1082

digital computer = 7 executable program = 9

digits, loss of significant = existential quantifier =


30 1085

digraph = 21 expansion, macro = 582


1126

explicit instantiation = -- overloading = -- 398


406 -- prototype = -- 370
exponent = 28 -- range = ( ) 160
expression = , -- signature = -- 398
arithmetic -- = -- 31 -- template = -- 405
conditional -- = -- 298 generic -- = -- 405
logical -- = -- 91 helper -- = -- 610
F implicit special -- = -- 698
field (bit-) = 447 partial -- = -- 160
field width = 37 recursive -- = -- 184
file = special -- = -- 698
binary -- = , 190, total -- = -- 160
455
functional try-block = try 936
-- directory = -- 191
functor = ,
-- manager = -- 191 751
-- system = 191 G
formatted -- = -- 190 garbage collection = 982
random access -- = -- 457 generic class = 952
sequential (serial) -- = -- generic function = 405
unformatted -- = 190, 455 generic type = 952
fill constructor = 1006 global = 354
find = , 270 H
First Order Predicate Calculus Predicate Calculus handle = 766
fixed point representation = handling, exception = 179,
27 416
flag = 99, 212 head, sequence = 1006
floating point = head, read/write = /
-- constant (literal) = 28 192
-- representation = 27, 561 heap memory = 293, 494
flowchart = , 5 helper function = 610
foreign key = 690 hexadecimal = 31
formal parameter = 164 high level programming language =
format specifiers = 38 8

format string = 38 I

formatted file = 190 identifier = , , 23,


46
formatting = 456
object -- = -- 617
forward declaration - 744
image = 160
forward iterator = 763
implementation, bottom-up =
free variable = 1085
384
friend = (, ) 743
implementation phase = 690
function = 34, 160
implication = 1080
callback -- = -- 395
double -- = -- 1081
class member -- = -- - 192, 605
material -- = -- 1081
conversion -- = -- 698
strict -- = -- 1081
-- body = -- 161
implicit instantiation =
-- call = 34 406
-- domain = -- 160 implicit special function =
-- domain of definition = -- 160 698
-- object = , in place = 460
751 in situ = 460
1127

includes = ( ) 1024 surrogate -- = -- 442


index = 473 keyword = - 46
array element -- = 222 L
inference rule = 13 label = 308
information = 3 language =
-- hiding = -- 614 assembly -- = -- 8
-- processing = 4 high level programming -- = -- -
inheritance = 192, 842 8

virtual -- = -- 877 machine -- = -- 7

initialization list = 705 programming -- = -- 7

initializing constructor = late binding, method =


700 () 861

input = o () letter = 20

-- condition = -- 10 language =

-- data = -- 4 machine -- = -- 7

-- iterator = -- 996 programming -- = -- 7

standard -- = 205 leakage, memory = 506, 978

insertion, back = 1007 length = 25

insertion sort, straight = LIFO stack = 411, 967, 992


257 linear search = 243
instance = linker, linkage editor = 9, 582
-- creation = -- 698 Liskov Substitution Principle = -
-- variable = -- 656 Liskov 844

template -- = -- 406 list, initialization = 705

instantiation = 406 list, simply linked = 527

explicit -- = -- 406 literal, string = ,


25
implicit -- = -- 406
loader = 8
instruction = 7
local entity = 166
integer constant (literal) = 30
log, standard = () -
integral type = 55
205
integrity constraint =
logic, modal = 1081
entity -- = -- 748
logical conjunction = 1079
referential -- = -- 748
logical disjunction = 1079
interface part = 611, 656
logical expression = 91
interpreter = 9
logical negation = 1080
intersection, set = 1026
loop = 135
invariant =
counted -- = -- 137, 150
repetition -- = -- 142
loss of significant digits =
class -- = -- 602, 616, 720 30
type -- = -- 76 LSP Liskov Substitution Principle
iterator = 761 lvalue = -l 295
bidirectional -- = -- 763 modifiable -- = -- 295
forward -- = -- 763 M
input -- = -- 996 macro = 390, 582
output -- = -- 995 -- expansion = 582
random access -- = -- 994 manager, file = 191
K map = 992, 1027
key = 442 material implication = 1081
candidate -- = -- 621 matrix = 222
foreign -- = -- 690
1128

member = positional -- = -- 540


class -- -function, = - -- 192, O
605 object = 192, 433, 656
private class -- = -- 604 exception -- = -- 416
public class -- = -- 604 function -- = --,
struct -- = 433 751
memory = -- identifier = -- 617
associative -- = -- 1018 -- orientation = 433
automatic -- = --, -- 293 -- -oriented programming =
content-addressable -- = -- 16, 656
, -- 1018 temporary -- = -- 716
dynamic -- = -- 293 object program = 9
heap -- = -- 293, 494 octal = 31
-- leakage = -- 506, 978 opaque pointer = 766
-- swapping = -- 499 opaque structure = 766
stack -- = -- 293 operation = 656
static -- = -- 411 operation, bitwise = 549
virtual -- = , -- 499 ordered set = 1019
merge sort = 253 ordered type = 107
message = 657 ordinal type = 107
method = output = ()
class -- = -- 192, 473, 605, 656 -- condition = -- 10
-- deferred (late) binding = -- data = -- 4
() -- 861 -- iterator = -- 995
true virtual -- = -- 875 standard -- = -- 205
virtual -- = -- 858 overflow = 30, 362, 545, 562
microoptimization = 15 overloading, function =
modal logic = 1081 398
modifiable lvalue = -l 295 P
modulo arithmetic = 543 padding = 444
move constructor = 981 parameter =
multimap = 992 actual -- = --, 164
multiplications, nested = - formal -- = -- 164
238 pointer -- = -- 364
multiplicity = 1030 reference -- = -- 348, 364
multiset = 244, 992, 1030 value -- = -- 169, 364
multitude = 1030 parent class = 843
mutable = 736 part, interface = 611
N partial function = 160
name = 44 partial specialization = 961
namespace = 21, 593 partially correct program =
negation, logical = 1080 12
nested multiplications = - past the end pointer =
238 321
nested statement = 117 path = 196
normalized representation = pending pointer = 507, 978
557 phase, implementation = 690
null statement = 115 pointer = 63
numeral system = 540 dangling -- = 507, 978
additive -- = -- 540 opaque -- = -- 766
1129

past the end -- = -- Q


321 qualification, type = 294
pending -- = 507, 978 quantifier = 1085
-- variable = - -- 494 existential -- = -- 1085
smart -- = -- 978 universal -- = -- 1085
polymorphism = 862 queue = 992
compile time -- = -- 863 R
run-time -- = -- 863 radix = ( ) 540
subclass -- = -- 862 random access file = 457
positional numeral system = random access iterator =
540 994
postcondition = 10 range constructor = 1006
precision = 30, 37 range, function = ( )
precondition = 10 160
predecessor = 107 read/write head = /
predicate = 10, 753, 1085 192

input -- = -- 10 recursive function = 184

output -- = -- 10 redundancy = 689

Predicate Calculus, First Order = reference parameter = 348


1 12, 1085 reference type = 350
preprocessor = 24 referencing value = ,
-- directive = 63
24 referential integrity constraint =
Principle, Liskov Substitution = - 748
Liskov 844 refinement, step-by-step = --
priority_queue = 992 15

private class member = reinterpretation casting =


604 445

program = 7 relationship = 688

correct -- = -- 12 bi-directional -- = -- 693

executable -- = -- 9 entity- -- diagram = -


-- 693
object -- = -- 9
-- multiplicity = -- 688
partially correct -- = -- 12
uni-directional -- = -- 692
-- testing = 76
repetition =
source -- = -- 9
counted - = -- 137, 150
totally correct -- = -- 12
-- invariant = -- 142
programming =
repetitive statement = 135
-- by contract = -- 12
replace = 273
object oriented -- = -- 656
representation =
structured -- = -- 384
biased -- = -- 567
proof, correctness = 76
fixed point -- = -- 27
propagated error = 572
floating point -- = -- 27,
proper subset = 1024
561
proposition =
normalized -- = -- 557
equivalent --s = -- 1083
reversible container = 1007
Propositional Calculus = 12
root, square = 35
propositional constant = 1078
roundoff error = 563, 571
propositional symbol = 1077
rule =
prototype = 370
business -- = -- 673
public class member = 604
inference -- = -- 13
1130

-- of composition = -- 15 sorting = 241


-- of consequence = -- 13 merge -- = -- 253
-- of three = -- 717 straight insertion -- = -
run-time polymorphism = 257
863 straight selection -- = -- '
Run Time Type Identification = 246
868 source program = 9
S space = 20
safety, exception = space, address = 499
712 space, white = 196
no-throw guarantee -- = -- - special function = 698
713
sparse array = 475
strong guarantee -- = -- 712
specialization, template =
scientific notation = 27 409
scope = 167 partial -- = -- 961
search = , 241 specifications = 10
binary -- = -- 250 specifiers, format =
binary -- tree = -- 1018 38
linear -- = -- 243 square root = 35
selection sort = ' stack = 411, 967, 992
246 -- memory = -- 293
selectin statement = 112 -- unwinding = -- 420
self-documented = 47 standard error = ()
semantics = () 7 205
sentinel value = - 138 standard input = 205
sequence = 992 standard log = () -
-- head = -- 1006 205

sequence, collating = 759 standard output = 205

sequence, escape = 25 state = 656

sequential (serial) file = 190 statement = 7

set = 992, 1020 assignment -- = -- ,


48
ordered -- = -- 1019
branching --s = -- 113
-- difference = -- 1026
compound -- = 114, 355
-- intersection = -- 1026
empty -- = -- 115
-- symmetric difference = -
-- 1026 nested -- = -- 117

-- union = -- 1026 null -- = -- 115

set, character = 20 repetitive -- = -- 135

Sheffer's stroke = Sheffer 1082 selectin -- = -- 112

shift = 549 -- terminator = 71

short-circuit boolean evaluation = step, repetition = 150


bool 128 step-by-step refinement = --
signature, function = 398 15

significant digits, loss of = straight insertion sort =


30 257

simply linked list = 527 straight selection sort = '


246
sine = 35
stream = 192
size = 44
strict implication = 1081
slicing = 845
strict subset = 1024
smart pointer = 978
string, format = 38
software engineer = 14
1131

string literal = , trace = 340


25 traits class = 987
stroke, Sheffer's = Sheffer 1082 tree, binary search =
structure = 433 1018
opaque -- = -- 766 trigraph = 21
-- member = -- 433 true virtual method = 875
structure diagram = 693 truncation = 571
structured programming = truth table = ,
384 1079
subclass = 843 try-block, functional = try 936
subprogram = 160 two-dimensional array =
subset = 1024 327

proper -- = -- 1024 two state system = 541

strict -- = -- 1024 type = 44

substitutability = 844 array component -- = -- 223

Substitution Principle, Liskov = - convertible pointer -- =


Liskov 844 867

substring = 276 cv-qualified -- = -- cv 294

successor = 107 domain -- = -- 496

suffix = 57 enumerated -- = -- 107

superclass = 843 generic -- = -- 952

surrogate key = 442 integral -- = -- 55

swapping, memory = 499 ordered -- = -- 107

symbol, propositional = 1077 ordinal -- = -- 107

symmetric difference, set = Run Time -- Identification = -- -


1026 868

syntax = 7 target -- = -- 496

system, file = 191 -- invariant = -- 76

T -- qualification = -- 294

table, truth = . U
1079 unary connective = 1078
table, virtual method/function = underflow = 562
/ 860 underscore = (_) 46
target type = 496 unformatted file = 190,
tautology = 1083 455
template = uni-directional relationship =
class -- = -- , 952 692

function -- = -- 405 universal quantifier = 1085

-- instance = -- 406 unwinding, stack = 420

-- specialization = -- 409 update anomalies = 689

temporary object = 716 use case = 695

terminator, statement = 71 V

testing, program = 76 validation, data =


384
text = 190
value = 44
three, rule of = 717
sentinel -- = -- - 138
throwing, exception = 416
-- parameter = 169
top-down design =
383, 384 variable = 44

total function = 160 bound -- = -- 1085

totally correct program = control -- = -- 150


12 dynamic -- = -- 494
1132

free -- = -- 1085
instance -- = -- 656
pointer -- = -- - 494
-- declaration = 44
vector = 992
verification = 76
-- condition = 83
virtual inheritance = 877
virtual memory = , 499
virtual method = 858
true -- = -- 875
--/function table = --/
860
volatile = 294
W
white space = 196
width, field = 37
Windows Application Program Interface (API) =
o 395
wrapper class = 510
-

(C++) countRecords 468
C++ C. D

A DialogBox (Windows) 395

abort (C++) 920, 928 display () 553

abs (C++) 36 displayResults 345


address_load 461, 462 dRound 177

address_save 460, 462 E

assert (C++) 95, 178, 919 editGrName 470

atan (C++) 36 editGrNameMM 521

atan2 (C++) 36 Elmn_load 464

atexit (C++) 920 Elmn_save 462

atof (C++) 283, 361 elmntInTable 524, 534

atoi (C++) 283, 362 even 422

atol (C++) 283, 362 exDisplay 730

atoll (C++) 362 exit (C++) 172, 178, 920, 921

B exp (C++) 35

binary_search (C++) 999 F

bind1st (C++) 1005 f (Fibonacci) 423

bind2nd (C++) 1005 fabs (C++) 36

binSearch 252, 254 factorial 173, 178, 419, 454, 925, 926, 939

bisection 393, 575, 752 fclose (C++) 216

bitValue 551, 553 feof (C++) 216


C find (C++) 534, 763, 999
calloc (C++) 517 find_if (C++) 999

checkWH 782 finish 382

ceil (C++) 187 floor (C++) 180, 187

clearBit 555 fopen (C++) 215

closeFiles 382, 481 for_each (C++) 1000

cntInt 367 fpclassify (C++) 569

comb 419, 454, 926 fprintf (C++) 216

compute 346, 348 free (C++) 517

conj (complex) 435, 438 fscanf (C++) 216

copy (C++) 996 G

copyTitle 378, 481 gcd () 174, 368

cos (C++) 36 get (C++) 101

count1 556, 829 getc (C++) 216

1133
1134 -

getline (C++) 264 minmax 353, 359, 366


GrElmn_copyFromElmn 464 mktime (C++) 750
GrElmn_save 464 multDbl 942
I myRound 176
ignoreStudentData 648 myStrCat 325
inc 391 myStrLen 324, 661
includes (C++) 1024, 1025 myStrLT 396
initialize 378 N
input2DAr 369, 407 natProduct 419, 454, 925
inputH 347, 348 O
intSqrt 171 openFile 468
isalnum (C++) 105 openFiles 375, 479, 483
isalpha (C++) 105 openWrNoReplace 374, 478
isascii (C++) 105 operator++ (WeekDay) 402
iscntrl (C++) 105 operator- (complex) 440
isdigit (C++) 105 operator== (complex) 440
isfinite (C++) 569 operator== (Date) 442
isgraph (C++) 105 operator== (Employee) 441
isinf (C++) 569 operator< (Date) 441
islower (C++) 105 operator< (Employee) 442
isnan (C++) 569 operator<< (complex) 440
isnormal (C++) 569 operator<< (Date) 441
isprint (C++) 105 operator<< (WeekDay) 401
ispunct (C++) 105 output2DAr 369, 407
isupper (C++) 105 P
isxdigit (C++) 105 p1 ( ) 236
isSymmetric 336 p2 ( ) 237
L part 556
lcm () 175, 368 ph ( Horner) 238
linSearch 243, 319, 533 pow (C++) 36
linSearchP 893 power 421
loadAllData 520 printf (C++) 37
loadCourses 646, 813 processData 380
loadIndex 820 putc (C++) 217
loadSylCourse 637 R
localtime (C++) 750 random_shuffle (C++) 1002
log (C++) 35 readAStudent 648, 814
lower_bound (C++) 999 readAtNo 468
lround (C++) 175 readCourseCodes 649
M readParagraph 833
malloc (C++) 517 readRandom 469
max 162, 170, 366, 390, 409 readStudentData 814
max (C++) 409, 998 realloc (C++) 517
maxElmn 351 renew 519, 717
maxNdx 231, 233 retrieve 819, 913
maxormin 425 rFactorial 184
memset 537 rGcd 184
min 163, 166, 366 rMaxNdx 234
min (C++) 409, 998 rVectorSum 234
- 1135

S strtof (C++) 361


save1DTable 651 strtol (C++) 284, 361
saveAllData 521 strtold (C++) 361
saveCollections 816, 910 strtoll (C++) 362
saveUpdateList 728 strtoul (C++) 362
saveUpdateTable 525 strtoull (C++) 362
scanf (C++) 70 succ 168
SecureZeroMemory 537 swap 367, 398, 406, 538
setBit 554 swap (C++) 409, 714
set_difference (C++) 1026 T
set_intersection (C++) 1026 terminate (C++) 928, 930
set_symmetric_difference (C++) 1026 time (C++) 749
set_terminate (C++) 928 to1Dgt 367
set_unexpected (C++) 928, 933 toFile 730
set_union (C++) 1026 tolower (C++) 105
sin (C++) 35 toupper (C++) 105
sort (C++) 999 transform (C++) 1001
sqrt (C++) 35 U
stackavail (C++) 411 uncaught_exception (C++) 928, 934
stdDev 239, 368 unexpected (C++) 928, 933
strcat (C++) 283 upCase 210
strcmp (C++) 282 V
strcpy (C++) 282 va_arg (C++) 426
strerror (C++) 923 va_end (C++) 426
stricmp (C++) 283 va_start (C++) 426
strncat (C++) 283 vectorAvrg ( ) 239, 368
strncmp (C++) 282 vectorSum 232, 317, 326, 407, 1008
strncpy (C++) 282 W
strnicmp (C++) 283 wcscpy (C++) 284
strlen (C++) 283 writeRandom 470
strtod (C++) 284, 360
1136 -
-

(C++) auto_ptr 978, 983
C++. AutoPtr 978

STL (C++) 992 * 979

= 992 -> 979

992 = 981
992 979

begin 993 981

empty 992 979

end 993 get 979

get_allocator 992 release 980

max_size 992 reset 981

rbegin 994 B

rend 994 back_insert_iterator (C++) 997

size 992 bad_alloc (C++) 937

swap 992 bad_typeid (C++) 938

STL (C++) 1006 Battery 625

1006 626, 737

back 1008 getMaxEnergy 626

clear 1007 getVoltage 626

erase 1007 maxTime 627

front 1006 powerDevice 626

insert 1007 reCharge 628


pop_back 1008 binary_function (C++) 1004
push_back 1008 binder1st (C++) 1005

resize 1007 binder2nd (C++) 1005

(C++) 1018 Bitmap 988

clear 1019 bitset (C++) 1034

count 1019 << 1034

equal_range 1019 >> 1034

erase 1019 [] 1035

find 1019 1034

key_comp 1020 any 1036

lower_bound 1019 flip 1036

upper_bound 1019 count 1036

A none 1036

Address 434, 461 reset 1036

1137
1138 -

set 1035 getCompuls 775


test 1035 getFSem 775
to_string 1036 getNoOfStudents 639, 775
to_ulong 1036 getPrereq 775
BString 658, 952 getSector 775
+= 747, 768 getTitle 775
= 664 getUnits 775
== 759 getWH 639, 775
[] 747 load 640, 777, 888
660, 661, 662, 766, 767 save 639, 777, 888
662, 767 setCateg 638, 776
757 setCode 638, 775
assign 666 setCompuls 776
at 661 setFSem 638, 776
c_str 659 setPrereq 638, 777
compare 759 setSector 638, 776
empty 660 setTitle 638, 775
cStrLen 661 setUnits 639, 776
length 660 setWH 638, 776
reserve 722 CourseCollection 779,807, 892, 1040
size 660 []() 787
stringCmpr 758 780
stringCmprCS 760 780, 781, 893, 1040
swap 767 781, 894, 1040
BStringImpl 766 add1Course 783, 895, 896, 1041, 1055
= 767 add1Student 786, 896, 1043, 1055
766, 767 delete1Course 782, 784, 895, 1041, 1055
768 delete1Student 787, 897, 1043, 1055
swap 768 display 1043
BStringT 953 erase1Course 785. 893, 1041, 1055
+= 954 find1Course 782, 1041, 1055
== 954 findDep 1005
955 findNdx 782, 893, 1040, 1055
C get1Course 787, 1042, 1055
CIndexEntry 898 getArr 781, 1043
complex 434, 437, 438, 1037 getNOfCourses 781, 1040
Course 636, 772, 886, 1054 insert1Course 783, 893,894, 1042, 1055
< 1054 load 786, 898, 1042
773 save 785, 898, 1042
774, 888 swap 785, 1042
888 D
add1Student 639, 777 Date 434, 438, 603
clearStudents 639, 777 + 756
CourseKey 772 ++ 751
CourseXptn 779 += 748, 751
delete1Student 777 == 612
display 640, 888 < 612
geCateg 775 << 612
getCode 639, 775 603, 605
- 1139

forward 750 swap 901


getDay 606 EqPrereq 1005, 1041
getMonth 606 EurUn 107
getObjCnt 735 exception 936
getYear 606 what 837
isLeapYear 603 F
isValidDate 735 fstream (C++) 192
lastDay 602 << () 23, 27, 99, 197, 263
load 608 >> () 27, 51, 101, 103, 193, 263
save 609 clear 196
setDay 607 close 195, 198
setMonth 607 endl 197
setYear 607 eof 194, 196, 211
swap 852 fail 211
DateTime 842 get 101, 206
+= 851 getline 264
<< 853 is_open 211
= 845. 852 open 192, 193, 197, 203
== 853 peek 205
843 put 206
847, 848 read 456
849 seekg 203, 457
forward 850 seekp 213, 457
getHour 849 width 198
getMin 849 write 456
getSec 849 G
setHour 849 GrElmn 463, 465
setMin 849 620
setSec 850 622
swap 852 !=() 523
deque (C++) 992, 1013 ==() 523
pop_front 1013 display 623
push_front 1013 getANumber 623
domain_error (C++) 938 GrElmn_display 469
E GrElmn_load 468
Elmn 463 GrElmn_setGrName() 470
Employee 433 GrElmn_writeToTable 473
EnrolledStudent 904 load 622
= 902 save 622
901, 904 setANumber 621
clearCourses 902 setAWeight 620
display 902 setGrName 623
find1Course 902 writeToTable 623
getCourses 902 I
getNoOfCourses 902 ifstream, istream (C++) 192
getWH 902 >> () 27, 51, 101, 103, 193, 263
insert1Course 902 clear 197
load 902 close 195
save 902 eof 194, 196, 211
1140 -

fail 211 add1Student 889


get 101, 206, 281 clearStudents 889
getline 264, 281 delete1Student 889
is_open 211 display 889
open 192, 193, 197 load 888
peek 205 save 888
read 456 ofstream, ostream (C++) 192
seekg 203, 457 << () 23, 27, 99, 197, 263
IndexEntry 798, 819 clear 197
!- () 819 close 198
invalid_argument (C++) 939 endl 197
ios_base (C++) 192 fail 211
app 213 is_open 211
ate 213 open 192, 193, 197
binary 212, 461 put 206
failure ( ) 938 seekp 213, 457
in 212 width 198
out 212 write 456
trunc 212 ostream_iterator 995
istream_iterator (C++) 995 ostringstream (C++) 278
istringstream (C++) 278 out_of_range (C++) 940, 1009
L overflow_error (C++) 941
less (C++) 1003, 1004 P
length_error (C++) 940 pair 956
list (C++) 992, 1014 PairT 957
merge 1017 plus (C++) 1004
remove 1014 priority_queue (C++) 992
remove_if 1014 Q
reverse 1018 queue (C++) 992
sort 1016 R
splice 1014 range_error (C++) 941
unique 1015 Route 671
ListNode 527 <() 676
logic_error (C++) 938 673, 707
M addRouteStop 676
map (C++) 992, 1027 clearRouteStops 674
[] 1028 deleteRouteStop 674
multimap (C++) 1031 erase1RouteStop 675
multiset (C++) 1030 get1RouteStop 678
count 1030 findNdx 674
insert 1031 setFrom 674
MyType 293, 439 setInBetween 674
N setTo 674
negate (C++) 1004 writeToText 680
numeric_limits (C++) 985 RouteStop 670
O 670
OfferedCourse 886 writeToText 680
888, 890 runtime_error (C++) 941
888 S
- 1141

set 992, 1020 SList_push_front 528


count 1021 begin 725, 762
empty 1021 end 725, 762
find 1021 save 728
insert 1022 swap 725
lower_bound 1021 SListT 970
size 1021 974
SetOfUCL 827 delete1Elmn 973
!= 837 erase 975
* 832 findIt 973
*= 832 findPtr 973
+ 829 get1Elmn 973
+= 829, 830 Iterator 970
- 831 Iterator::operator* 971
-= 831 Iterator::operator++ 971
< 837 Iterator::operator-> 971
<= 837 Iterator::getPNode 975
== 837 pop_front 977
>= 837 push_front 972
827 StackT 967, 976
827 976
card 829 getTop 977
clear 832 isEmpty 977
display 828 isFull 977
hasMember 836 pop 976
insert 830 push 976
isMemberOf 836 string (C++) 260
isProperSubset 837 << () 263
isSubset 836 >> () 263
remove 831 []() 274
save 834 append 269
setDifference 831, 839 assign 262
setUnion 829 at 274
SIndexEntry 908 c_str 262
SList 528, 723 compare 266
723 data 262
724 empty 268
725 erase 274
=() 725 find 270
erase1Elmn 728 find_first_not_of 272
find1Elmn 726 find_first_of 272
findPtr 725 find_last_not_of 272
get1Elmn 726 find_last_of 272
insert1Elmn 726 insert 274
Iterator 761 length 268
Iterator::operator!= 762 max_size 269
Iterator::operator* 761 npos 270
Iterator::operator++ 761 rfind 272
SList_listSearch 529 size 268
1142 -

substr 276 swapArr 799, 1048, 1060


swap 263 StudentInCourse 644, 799
Student 640, 900, 1044 != 799
!= 642 799
= 790 799
789 799
789, 790, 899, 1044 display 645
789, 899 getCCode 799
add1Course 642, 792, 1045, 1057 getKey 799
clearCourses 642, 791, 1044, 1057 getMark 799
delete1Course 792, 1045, 1058 getSIdNum 799
display 643, 900, 1058 load 799
erase1Course 792, 1045 save 644, 799
find1Course 791, 1045, 1057 setCCode 799
findNdx 791, 1045, 1057 setIdNumCCode 644
getCourses 790, 1044, 1957 setMark 799
getFirstname 790 setSIdNum 799
getIdNum 642, 790 SICKey 799
getNoOfCourses 790, 1044, 1057 StudentInCourseCollection 802, 1049, 1061
getSurname 790 803, 1049, 1062
getWH 642, 790 1049, 1062
insert1Course 792, 1045 add1StudentInCourse 805, 1050, 1063
load 793, 900, 1046, 1058 delete1StudentInCourse 805, 1050, 1063
readFromText 642 erase1StudentInCourse 1051
readPartFromText 794 find1StudentInCourse 1050, 1063
save 643, 793, 899, 1046, 1058 findNdx 803, 1050, 1063
setFirstname 791 get1StudentInCourse 1050, 1063
setIdNum 790 getArr 1049, 1062
setSurname 791 getNOfStudentInCourses 1049, 1062
swap 790, 899, 1046 getPAllCourses 803
StudentCollection 795, 810, 1046, 1059 getPAllStudents 803
796, 905, 1047 insert1StudentInCourse 1050
905, 1047 load 1051, 1064
add1Course 811, 907, 1048, 1060 save 1051, 1064
add1Student 797, 810, 906, 1047, 1059 setPAllCourses 803
checkWH 816, 909, 1061 setPAllStudents 803
delete1Course 811, 908, 1048, 1060 swapArr 1051, 1064
delete1Student 796, 907, 1048, 1060 SylCourse 633
erase1Student 906, 1048 save 635
find1Student 1047 T
findNdx 905, 1047, 1059 time_t (C++) 749
get1Student 1047, 1059 tm (C++) 749
getArr 1047, 1059 U
getNOfStudents 1047 unary_function (C++) 1003
getPAllCourses 797 underflow_error (C++) 941
insert1Student 906, 1048 V
load 798, 909, 1049, 1061 va_list (C++) 426
save 798, 908, 1048, 1060 vector (C++) 992, 1008
setPAllCourses 797 [] 1008
- 1143

at 1009 -= 490, 760


capacity 1009 ^ 488
reserve 1009 == 487
vector<bool> 1010 abs 761
flip 1010 abs2 761
swap 1010 Vector3 () 486
Vector3 486, 760 Vector3_abs 490
!= 487 Vector3_abs2 490
* 488 W
*= 490, 761 WeekDay 107
+ 488, 761 ++ () 401
+= 489, 760 << () 400
- () 488 wstring (C++) 272
- () 488, 760
1144 -

You might also like