Professional Documents
Culture Documents
/ 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
. 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
. 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
. 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
....................................................................................................................................................................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
. 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
. 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
. 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
. 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
. 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
Prj04.11.2 .................................................................................................................................816
Prj04.11.3 .......................................................................................................................................................816
Prj04.11.4 ... .................................................................................................................................816
Prj04.12 2 ......................................................................................................... 819
Prj04.13 ............................................................................................................................. 821
. 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
. 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
...........................................................................................................................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
.
. -
.
(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
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>
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;
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
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.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
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
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
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;
( ) -
. :
2
. -
: -
:
#include <iostream>
using namespace std;
int main()
{
int a1, a2, sum;
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;
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
: 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.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
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;
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
#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...
%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;
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;
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
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.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
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)
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), "<=" () "==" () -
.
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 );
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
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
: 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 = ''; 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
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.
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
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;
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; //
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;
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;
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
:
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; //
5.4 *
ifelse if.
:
// P
if (S) Et else Ef
S t P && S
Qt. S !S f
121
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))
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
5.5
assert
.
1
h 0. :
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
125
// 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; //
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; //
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;
) 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,
;
, -
;
:
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
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.
.
while .
. :
#include <iostream>
using namespace std;
int main()
{
int d1, d2, p, y;
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
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;
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
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;
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;
7.1
,
,
C++,
, , , -
,
.
-
.
(, ).
, , .
return ,
.
2. C -
, :
#include <iostream>
using namespace std;
int main()
{
int x1, x2, x3;
// 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; . . . }
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;
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;
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;
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;
int main()
{
int x1, x2;
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;
int main()
{
double t;
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().
,
. .
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
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;
{
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
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).
-:
-
.
, .
:
,
,
()
.
:
( )
.
:
.
.
, ,
-,
. , -
-,
,
() .
-.
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
() : , ( ),
.
:
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;
. 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
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;
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;
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
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
/ ,
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
8-9 text.
, . ,
, .
8-10 C++
. .. :
1: #include <iostream>
2: #include <math>
3:
4: int main()
5: {
220 8
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
. . .
. 9-1 .
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
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
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 );
int mxp( 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 );
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;
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 );
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;
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;
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 );
#include <fstream>
#include <cmath>
using namespace std;
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
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 );
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;
//
//
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 );
. 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
int main()
{
const int N( 50 );
//
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
-9 -45 -21
. 9-5 . v
, -
. w .
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 );
//
dv = 1; dw = 1; dz = 1;
249
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
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
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" );
, 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:
#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;
10.5
compare()
(<, >, == ).
s1.compare(s2)
s1 s2,
s1 s2,
(0) s1 s2 .
:
266 10
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;
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
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
, !
:
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" );
KIJHGFEDCBA
E (T IA TEO):
: :
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;
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
, 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;
10.13 C:
C :
1. C++ (
)
2. string.
:
char,
char(0) -
.
:
char a[100] = " ";
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[] = " ";
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-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
:
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
:
. :
,
.
,
.
,
.
,
.
if, ifelse,
.
while,
.
for, .
,
-.
, : -
(+, -, *, /, %), (==, !=, <, <=, >, >=), (&&, ||, !)
:
+ -,
&, ,
*,
,
sizeof, ""
typeid, .
, , -
.
,
.
.
. .
-
/ .
11.1
,
-
. .
.
293
, C++
. -
:
int main()
{
MyType v1;
MyType v3( 15 );
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
-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--). :
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
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
: -
.
.
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
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
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; //
. . .
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;
<< 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
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 );
double sum( 0 );
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
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
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
//
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
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;
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 );
. :
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;
argv[1] ,
( : 1).
argv[k] k- .
argv[argc-1] ( ).
argv[argc] : () 0.
, - .
3, . '
: " 3".
12.8 ...
.
( )
( ).
.
( )
.
. :
) ) .
12-1 ; ( , )
#include <iostream>
using namespace std;
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
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 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.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,
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;
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;
main
h 80
tP vP
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 );
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 );
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
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 );
13.6.1 *
static, a
3:
double rnd01()
{
static double a( 0.13579246801357924680 );
3 (0,1).
358 13
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
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
, ,
, ... ;
.
(-) (-
) .
:
.
:
, !
.
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
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 );
4
, to1Dgt, -
a, double, n
1
.
:
a double
1 -
.
,
[ ] n []. n
.
( a) -
(void). :
void to1Dgt( double a[], //
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
:
, -
.
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 main()
{
double q[5];
, :
#include <iostream>
using namespace std;
int main()
{
double q[5];
#include "truncarr.h"
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
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;
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>
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
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.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 )
{ 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;
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
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 )
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>
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;
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;
14.5
13.9.3 swap()
int.
!
, :
swapI, swapD, double, swapC,
char
.
swap :
#include <iostream>
8 , !
398 14
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
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>
int main()
{
// . . .
WeekDay d( sunday );
for ( int k(0); k < 10; ++k )
{
cout << d << endl;
++d;
}
// . . .
} // main
:
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>
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 ...
,
@
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;
int main()
{
406 14
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
16 using. .
II 407
.
.
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
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; }
14.7.2.1 , ...
-
(-) (-) / (-) (-
) :
.
II 411
14.5.
-
.
.
:
template< typename T >
void qsc( T x, char c )
{ cout << "in template" << endl; }
14.8
C++. () .
.
.
19 :
(static),
,
(automatic) (stack)
,
19 : .
412 14
:
.
:
#include <iostream>
long g = 0;
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;
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>
long g = 0;
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;
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;
:
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>
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;
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>
int main()
{
int m, n;
// 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;
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
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(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>
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
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
:
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, "" );
( ) ( : ) -
(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
(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
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
15.6
C++
- ()
( ).
!
-
. .
15.6.1 *
:
#include <iostream>
5 .
. ,
, (surrogate) -
, , .
- II 443
struct Address
{
char country[17];
char city[17];
int areaCode;
char street[17];
int number;
}; // Address
int main()
{
Address a;
(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;
15.10
:
! ,
Murphy : .8
, ,
:
.
.
.
. -
14.9
:
struct ApplicXptn
{
enum { domainErr, paramErr };
char funcName[100];
int errCode;
double errDblVal1, errDblVal2, errDblVal3;
:
. :
. .
:
double v( double x )
{
const double a( -1 ), b( 1 ), T( b-a );
double m( floor( (x-a)/T ) ), x0( x - m*T ), fv;
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>
struct ApplicXptn
{
char funcName[100];
int errCode;
int iErrVal1;
int iErrVal2;
int main()
{
int m, n;
} // 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;
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
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;
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
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
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 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
.
!
: !
! ! (
).
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 )
{
..
}
.. ( )
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
:
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>
struct ApplicXptn
{
enum { cannotOpen, streamNotOpen, rangeErr, cannotClose,
cannotWrite, cannotRead };
char funcName[100];
int errCode;
char errStrVal[100];
int errIntVal;
- II 471
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 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;
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;
}
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
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&
Prj02.5 -
:
Vector3 v1, v2;
:
v2 = -v1;
v2 v1, : v1 + v2 = 0.
- :
-: Vector3 Vector3
14.6.4 @
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&
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
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
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;
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++ :
) - 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
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
struct ApplicXptn
{
enum { cannotOpen, cannotRead, allocFailed };
char funcName[100];
int errCode;
char errStrVal[100];
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 );
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
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
: -
!
. :
char** monthName( 0 );
:
monthName = new char*[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.
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>
7 .
8 MyTmpltLibXptn , 16.9.
520 16
int main()
{
int* ip( 0 );
double* dp( 0 );
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
struct ApplicXptn
//
struct GrElmn
//
// GrElmn_...
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 ); }
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>
struct MyTmpltLibXptn
//
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 );
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;
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>
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
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
16.13.2 linSearch()
linSearch , C++
(std::)find : -
( ).
. ,
.
, , :
template< typename T >
10 :
T save;
save = v[upto+1]; // v[upto+1]
534 16
11 , :
pos = find( &ar[from], &ar[upto], value );
535
, :
grElmnTbl+nElmn &grElmnTbl[nElmn].
lPos ==
grElmnTbl+nElmn.
find ;
:
++p p = p->lnNext.
.
.
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
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
:
, -
, : 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
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
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
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 main()
{
int x, y, z;
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
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
( <<)
(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;
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.
: -
.
(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 );
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 );
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 );
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
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
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 )
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
:
+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.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
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>
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;
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;
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
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 :
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++
.
"#", "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];
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>
struct MyTmpltLibXptn
// 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"
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"
struct ApplicXptn
// . . .
#include "MyTmpltLib.h"
MyTmpltLibXptn renew() linSearch(). renew()
GrElmn linSearch() .
(16.9) :
#include <iostream>
#include <fstream>
#include "MyTmpltLib.h"
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>
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 );
#endif // _MYNUMERICS_H
MyNumerics.cpp :
#include <string>
#include <cmath>
#include "MyNumerics.h"
MyNumerics.o MyNumerics.cpp.3
.
17.14 :
#include <iostream>
#include <cmath>
#include "MyNumerics.h"
double q( double x );
int main()
{
double riza;
int errCode;
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>
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.
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
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
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
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) );
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 )
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 )
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;
3 static!
611
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
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>
class Date
//
614 19
struct DateXptn
//
#endif // _DATE_H
Date.cpp:
#ifndef _DATE_CPP
#define _DATE_CPP
#include <fstream>
#include "Date.h"
#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).
, .
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. , -
.
, struct ( ),
-
.
.
Circle : -
cXC, cYC cR. cR 0.
, . -
; private public -
; ! -
:8
class private.
620 19
{
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
#include <fstream>
#include <string>
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
, 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.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>
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"
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"
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
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];
2 Course :
public:
enum { cCodeSz = 8, cTitleSz = 80, cCategSz = 4 };
638 Project 03
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
Prj03.6.2
enrllmnt.txt
.
. :
Student* stArr; unsigned int nOfStudents( 0 );
const int sIncr( 10 );
unsigned int resStudents;
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;
ofstream log;
try
{
loadCourses( "gCourses.dta", crsArr, nOfCourses );
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, !
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;
()
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
20.1.2 at()
, at,
. 10.10:
:
if ( s3.at(0) == '' ) s3.at( 0 ) = '';
,
, .
out_of_range
stdexcept. :
#include <iostream>
#include <stdexcept>
#include <string>
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;
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;
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
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
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 .
.
. -
. , 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
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
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
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
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"
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>
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
#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
20.7.4
:
#include <iostream>
#include <fstream>
#include <string>
#include "Route.cpp"
int main()
{
try
{
ifstream tin( "kvadra.txt" );
string name, buf;
double dist, fare;
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
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) );
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;
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.
-
:
: ( ),
Route 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.
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
:
,
(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;
21.2
(copy constructors).
, ..:
Date d1( 2002, 7, 2 ), d2( d1 ); // d1 == d2 == 02.07.2002
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++,
: .
-
. -
( ),
!
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
:
.
. (;)
, ,
.
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'; }
21.4
. 5
() .
( -
.) .
.
; ; , ,
.
, ,
; .
:
.
: -
Route. BString
:
5 () . ;
.
707
.
; :
,
.
: 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.
{
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().
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;
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
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;
}
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. , .
.
.
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
(*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
21.11.2
:
#include <iostream>
#include <fstream>
#include <string>
#include "GrElmn.cpp"
#include "SList.cpp"
struct ApplicXptn
//
int main()
{
fstream bInOut;
string flNm( "elementsGr.dta" );
try
{
SList lst;
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 );
, , , -
.
: 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
, :
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
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>
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
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
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
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 << 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
22.7.2
6 -
( ) . , ==
< Date, 19.1.4 .
:7
@
@.
== < !=
>= :
bool operator!=( const Date& lhs, const Date& rhs )
{ return !(lhs == rhs); }
22.7.3 BString
(==,
<, ) BString. -
, .
:
char lhs[10], s2[12];
len1 len2. :
minLen = min( len1, len2 );
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 = "" );
// ...
.
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;
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-=
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
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;
.
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
bsReserved = ((bsLen+1)/bsIncr+1)*bsIncr;
{
BString::BStringImpl tmp( rhs );
if ( &rhs != this )
swap( tmp );
return *this;
} // BString::BStringImpl::BStringImpl& operator=
,
BString.
:
BString::~BString() { delete bsHandle; }
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
#include <fstream>
#include <string>
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
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
:
.
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
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;
4 (constraint)
(entity integrity)...
5 ... (referential integrity).
781
} // 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
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
, ,
.
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;
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
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
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 )
char svs[sNameSz];
strcpy( svs, sSurname ); strcpy( sSurname, rhs.sSurname );
strcpy( rhs.sSurname, svs );
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
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
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
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;
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
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;
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
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;
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
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
Prj04.11 1
-
(Prj03.2)
.
813
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
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"
#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
int main()
{
try
{
CourseCollection allCourses;
StudentCollection allStudents;
StudentInCourseCollection allEnrollments;
allEnrollments.setPAllStudents( &allStudents );
allEnrollments.setPAllCourses( &allCourses );
allCourses.setPAllEnrollments( &allEnrollments );
allStudents.setPAllEnrollments( &allEnrollments );
log.close();
SIndexEntry* index;
try
{ index = new SIndexEntry[allStudents.getNOfStudents()]; }
catch( bad_alloc )
{ throw ProgXptn( "main", ProgXptn::allocFailed ); }
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"
#include "Course.cpp"
#include "Student.cpp"
#include "SIndexEntry.h"
struct ProgXptn
// 1
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
bin.seekg( 0, ios_base::end );
unsigned int flSize( bin.tellg() );
820 Project 04
ndxSz = flSize/sizeof(IndexEntry);
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
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,
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 );
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 );
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;
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"
int main()
{
SetOfUCL curSet, nextSet, common, notInNext;
ifstream tin( "mstrpc.txt" );
ofstream bout( "paragltr.dta", ios::binary );
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
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
#include <string>
#include <fstream>
class SetOfUCL
{
friend bool operator==( const SetOfUCL& lhs, const SetOfUCL& rhs );
public:
SetOfUCL() { bitmap = 0UL; };
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
:
-
: -
(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
. :
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
5 . :
DateTime::DateTime( const DateTime& rhs )
: Date( rhs ), dtHour( rhs.dtHour ), dtMin( rhs.dtMin ), dtSec( rhs.dtSec ) { }
850 23
6 22.5.1.4.
851
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
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.
: .
,
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
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; }
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
)
/ (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. , ;
...
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
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 )
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; }
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;
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 );
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!
{
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.
,
.
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
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.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
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 { /* ... */ };
TechnManager TechnManager
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;
};
void printStates()
{ cout << "cadence:" << cadence << " speed:" << speed
16 C#.
17 http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
879
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
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
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.
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.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
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
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
catch( bad_alloc& )
{
throw CourseCollectionXptn( "load",
CourseCollectionXptn::allocFailed );
}
if ( bin.fail() )
throw CourseCollectionXptn( "load",
CourseCollectionXptn::cannotRead );
swap( tmp );
}
} // CourseCollection::load
char svs[sNameSz];
strcpy( svs, sSurname ); strcpy( sSurname, rhs.sSurname );
strcpy( rhs.sSurname, svs );
:
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 );
if ( bout.fail() )
throw StudentXptn( getIdNum(), "save",
StudentXptn::cannotWrite );
} // EnrolledStudent::save
903
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
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
!= == -
.
:
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
} // StudentCollection::save
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"
#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
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 );
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 ); }
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
, delete pOneStudent,
virtual ~Student() { };
( virtual ~EnrolledStudent() { delete[] esCourses; }.)
main() :
#include <fstream>
#include <iostream>
#include <new>
#include "MyTmpltLib.h"
#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
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
:
-
. -
:
,
,
(-
),
.
, -
. 4.3, , :
cout << " m: "; cin >> h;
assert( h >= 0 );
( .)
, 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:: .
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 . , -
-
-
. ,
.
:
.
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
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;
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();
}
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>
void myTerminateHandler()
{
cout << ", ," << endl
<< ", ." << endl;
abort();
} // myTerminateHandler
int main()
{
set_terminate( &myTerminateHandler );
terminate();
}
:11
, ,
, .
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
, ,
, .
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!
, ,
, .
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>
void myTerminateHandler()
{
cout << ", ," << endl
<< ", ." << endl;
abort();
} // myTerminateHandler
int main()
{
set_terminate( &myTerminateHandler );
try {
cout << natProduct( 3, 1 ) << endl;
}
catch( char* )
{ cout << "catching char*" << endl; }
catch( int& )
{ cout << "catching int" << endl; }
}
:
, ,
, .
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
. 24-1 exception -
. logic_error runtime_error -
.
15 exception C++ .
938 24
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
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.
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.
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
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() { };
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 -
. ; !
.
:
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
:
, 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
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 );
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
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
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
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
#endif // _PAIRT_H
25.5
14.7.1 ()
/
,
.
.
:
class typename .
= () .
class typename .
.4
template
< > class .
= () .
C++03:
template< typename T > class myarray { /* ... */ };
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>
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 -
! -
: -
.
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
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
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
25.7
(container class) -: -
. (container)
. :
SList GrElmn (21.11)
. .
967
6 Project.
7 isEmpty(), -
STL.
968 25
cout << endl << "Popping integers from intStack" << endl;
while ( !intStack.empty() )
{
969
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
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;
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; }
-
:
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
25.8
16.7
-.
11 SListT
.
978 25
12 (Alexandrescu 2001) -
. . 7 ( )
http://ptgmedia.pearsoncmg.com/images/9780201704310/samplepages/0201704315.pdf.
979
13 C++11
.
982 25
-
.
.
: get()!
AutoPtr.h:
#ifndef _AUTOPTR_H
#define _AUTOPTR_H
#endif // _AUTOPTR_H
:
#include <iostream>
#include <string>
#include "AutoPtr.h"
#include "Date.cpp"
int main()
{
AutoPtr< string > aps( new string("abc") );
cout << *aps << endl;
aps->assign( "qwerty" );
cout << *aps << endl;
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
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
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"
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
multiset multimap
. 26-1 STL.
-
STL.
26.1 ,
:
#include <iostream>
#include <vector>
#include <algorithm>
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
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>
int main()
{
vector< unsigned int > array;
istream_iterator< unsigned int > cinIt( cin );
istream_iterator< unsigned int > cinEoStream;
(*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
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>
int main()
{
int array[100];
int* pEnd;
, . -
, 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 );
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>
int main()
{
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
Print<int> pr;
{
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>
int main()
{
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
int intArr1[7];
Sqr<int> sqr;
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>
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
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; }
};
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
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) , ,
.
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
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;
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
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
:
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
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 );
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;
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;
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>.
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
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> >
.
, 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.
20 Z.
- Standard Template Library (STL) 1031
26.3.4
( ) . ,
-
. ;
<
. , -
K <.
:
int intArr[] = { 34, 72, -23, 8, -11, 31, 41 };
.
(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 -
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
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>
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.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
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
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() ); };
} // 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 );
sCourses.swap( rhs.sCourses );
} // Student::swap
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(); }
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
Prj07.1.5 StudentInCourse
StudentInCourse .
Prj07.1.6 StudentInCourseCollection
, , :
vector<StudentInCourse> siccArr;
:
StudentInCourseCollection::StudentInCourseCollection()
{
siccPAllStudents = 0;
siccPAllCourses = 0;
} // StudentInCourseCollection::StudentInCourseCollection
~StudentInCourseCollection() { };
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
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. , ,
.
:
( push_back()),
lower_bound(); findNdx(),
find1Course() get1Course(). !
, vector.
Course
StudentCollection
26.3.2.
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 ); }
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
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;
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
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(); }
} // 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::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
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,
() .
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
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.
, , ,
. :
&& || .
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
. 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
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
. -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
-- 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
-- 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
1123
1124
declaration = epsilon = 57
format string = 38 I
input = o () letter = 20
-- condition = -- 10 language =
-- data = -- 4 machine -- = -- 7
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
terminator, statement = 71 V
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
B exp (C++) 35
binSearch 252, 254 factorial 173, 178, 419, 454, 925, 926, 939
1133
1134 -
992 = 981
992 979
rbegin 994 B
A none 1036
1137
1138 -