You are on page 1of 266

^^

00(o)((o)S

^'

^
. . , . .

C++
-

300.piter.com

300
300- -

1^'
- --

2006

32.973-018.1
681.3.06
12

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

. ., . .
12

C++. - : . .:
, 2006. 265 : .
ISBN 5-94723-842-

, C++
. , , , , , UML,
(software engineering)
, }.
, . 20 .

,
.
32.973-018.1
681.3.06

, , ,
. , ,

, .

ISBN 5-94723-842-

, 2006

1.

12

2.

58

3. .

105

4.

143

5. . string

181

6.

196

241

260

261

11

1 .

12





1.1.







1.2.
1

2
3
4

12
13
14
16
16
25
27
28
29
30
31
32
33
34
41
42
44
48
53

2 .

58






.
.

58
59
60
61
62
63
64


. UML


2.1.
2.2.
2.3.

3 . .









3.1.




.



3.2. ( )

65
66
67
67
68
69
72
81
. . . . 88
102

105
105
106
107
107
108
110
110
112
113
119
120
121
122
123
124
125
129
129
141

4 .

143



/ C++
/

,

4.1. ,
/
4.2.

143
144
144
144
147
148
149
166
173

5. .
string

181



string
5.1.
5.2.

181
185
186
189
191
193

6 .

196

STL


6.1.
print()

.

6.2.
6.3.

196
197
197
200
201
202
204
205
206
208
215
215
217
218
220
233

241




(Strategy)
(Composite)

243
245
247
252
255

260

261


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

(software engineering), ,
, , ,
.

.
.

, ,
?

,
?

()
?

,
,
. ,
.
,
, ,

,
.

UML,
.
UML
.
,
, ,
. ,

.
Microsoft
/ Windows.
,
. . C/C++.
(, 2001, 2003)^
.
, .
,
.
,
.
,
.
, , , , ,
, ,
.
C++, , ANSI
ISO/IEC 14882 (1998).
, , Microsoft Visual C++ 6.0 ( Windows) gcc
(GNU Compiler Linux, Cygwin Windows).
.
-



-
2003 . , ,
().
^ C/C++.
2002 .

1 1

80% . . ,
20% . . , .
,
. ,
shupak@mail.ru.


,
comp@piter.com ( , ).
!
web-
http://www.piter.com.

1
: . 178-199.



- () ,
,

.
, ,
.
:
,
. , ,
,
.
,
: (
) ,
.
.
divide
et impera ( ).
,
. , ,
, .

,
, .

13

,
.
? , ,
, .
,
.
.
-

, '^ ?
. , ,
.

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

. ,
,
, ,
.
, ?
.
.
( ),
- , .
- ,
,
. /
, -
- .
, -
.

14

1.


.
, , :

{cohesion) ,
. :
, ,
() .

{coupling) ,
- -.
.
,
.
,
.

, , , ,
. ,
( )
,
.

? ,
,
/ .
, ,
, ,
.
.
,
( ) .
,
,

.

. ,
,
, .



. ,
, .

1 5

,
. , ,
, .
, ,
. ^
,
. PI , .

- .

, .
: public ( ), private
( ) protected ( )1
, ,
.
,
, -'^
,
. ,
,
, ( ).
.
,
. ,
. ,
.
,

, .
, -
, ( ) .
: ,

, . ,
, .
.
,
: .
^ -,
.
^
.
^ .

16

1.

.

. .
,
.

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

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


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

- .
, .
6.1 ,
, .

1 . 1 .
.
100 . .
: (30 ,
), (5 ), (10 ).
, ,
.
.

1.1.

17

, , 6.1 (1)\

Man:
struct Man {

char name[l_name + 1]:


1nt birth_year;
f l o a t pay:
}:

, , ,
,
:
class Man {

char name[l_name + 1]:


1nt b1rth_year:
float pay;
}:

. !
(private). ma1n() Man
man, - , : man.pay =
value, ,
.
. , (public).
.
6.1 (1) name l_name + 1.
. , Man
. ,
, l_name = 30, -, ,
, ,
, l_name = 200.
. char named_name + 1]
char* pName. :
? :
, .
, ,

( Man). ,
, .
,
.
, ,
.
1 , 6.1 .

18

1.

().
, ,
. , ,
{ }, ,
. ;
new, :
Man* = new Man;

delete, : delete .
, :
class Man {
public:
Mandnt IName = 30) { pName = new char[lName + 1]; } //
-ManO { delete [] pName; }
//
private:
char* pName:
1nt b1rth_year:
f l o a t pay;
}:


(;).
,
, . ,
...
:
IName (30).

, .
?

? ! ,
.
-, ,
, : Man man[25]. 25
Man,
!
, ^

. .
.
(Inline) . ^ , ,
.

1.1.

19

, ,
:
// Man.h ( )
class Man {
public:
Mandnt IName = 30);
//
~Man();
//
private:
char* pName;
int
birth_year;
float pay:
}:

// Man.cpp ( )
#include "Man.h"
Man::Man(int IName) { pName = new char[lName + 1]; }
Man::~Man() { delete [] pName: }
,
::.
:
, .
, ,
^
.
? ^?
:
Man?
:
. ,
1 , . ,

.
, .
GetNameO, GetBirthYearO,, GetPayO. ,
,
.
SetNameO, SetBirthYearO, Set Pay .
, ,
. , 6.1 (1)
^ ( )
, , ,
, ,
.
^ , , - (. ,
).

20

1.

(
man dbase):
1nt 1 = 0;
while (f1n.getline(buf, l_buf)) {
// . . .

strncpy(man[1].name, but'. l_name);


man[1].name[l_name] = '\0';
man[1].birth_year = ato1(&buf[l_name]);
man[i].pay = atof(&buf[l__name + l_year]);
1 ++;
}

, while i-
:
fin buf;

buf name man[i ] l_name ;

buf ,
, int birth_year
man[i];

, ,
float pay man[i].


(main) ( Man),
:
man[i].SetName(buf);
man[i].SetBirthYearCatoi(&buf[l_name]));
man[i].SetPay(atof(&buf[l_name + l_year])):
i++;

.
atoi (&buf[l_name]).
,
! ,
. ,
, () .
void SetBirthYear(const char"^
fromBuf). SetPayO.

,
.
,
i (),
.

1.1.

21

, 6.1 (1)
() . :
for (1 = 0: 1 < n_record; ++1) {
if (strstr(man[1].name. name))
// 1
if (man[1].name[strlen(name)] = = ' ' ) {
111
. strcpy(name. man[1].name);
// 3
cout name man[i].b1rth_year ' ' man[1].pay endl;
// 4
//

}
}
:
? :
name ( 1 2)
cout ( 3 4).
CompareName(const char* name),
,
Print .
Man .
, Man.

:
: (.h),
(.),
, maInO
.
, ,
() .
IIIIIIIIIIIIIIIIIIIIII1111

II Taskl_l
III nil nil III IIII IIIIIIIIIIIIIIIIIIIIII
II Man.h
//#1nclude "CyrlOS.h"
const
const
const
const

1nt
1nt
1nt
1nt

1111IIIIIIIIIIIIIIIIII1111
IIIIIIIIIIIIII

mil

// for Visual C++ 6.0

l_name = 30;
l_year = 5 ;
l_pay = 1 0 ;
l_buf = l_name + l_year + l_pay;

class Man {
public;
Mandnt IName = 30);
-ManO;
bool CompareNameCconst char*) const;
Int GetBlrthYearO const { return b1rth_year; }

22

1.

float GetPayO const { return pay; }


char* GetNameO const { return pName: }
void PrintO const;
void SetB1rthYear(const char*);
void SetName(const char*);
void SetPayCconst char*);
private:
char* pName;
int birth__year;
float pay;
}:
///////////////////////////////////////////////////////////
// Man.cpp
#include <iostream>
#include <cstring>
#include "Man.h"
using namespace std;
Man::Man(int IName) {
cout "Constructor is working" endl;
pName = new char[lName + 1];
}
Man::~Man() {
cout "Destructor is working" endl;
delete [] pName;
}
void Man::SetName(const char* fromBuf) {
strncpyCpName. fromBuf. l_name);
pName[l_name] = 0;
}
void Man::SetBirthYear(const char* fromBuf) {
birth_year = atoi(fromBuf + l_name);
}
void Man::SetPay(const char* fromBuf) {
pay = atof(fromBuf + l_name + l_year);
}
bool Man::CompareName(const char* name) const {
i f ((strstr(pName. name)) && (pName[strlen(name)] == ' ' ) )

return true;
else
return false;
}
void Man::Print() const {
cout pName birth_year ' ' pay endl;
}
///////////////////////////////////////////////////////////

// Main.cpp
#include <fstream>
#include "Man.h"
const char filename[] = "dbase.txt";

1.1.

23

1nt ma1n() {
const 1nt maxn_recorcl = 10;
Man man[maxn_record]:
char buf [l_buf + 1 ] :
char name[l_name + 1 ] ;
ifstream flnCfUename);
1f (!f1n) {
cout " " filename end!; return 1;
}
i n t 1 = 0;
while (fin.getlineCbuf. l_buf)) {
i f ( i >= maxn_record) {

cout " "; return 1; }


man[i].SetName(buf);
man[i].SetBi rthYear(buf);
man[i].SetPay(buf);
i++;

}
int n_record = i. n_man = 0 :
float mean_pay = 0 ;
while (true) {
cout " end: ";
cin name;
if (0 == strcmp(name. "end")) break;
bool not_found = true;
for (i = 0; i < n_record; ++i) {
if (man[i].CompareName(name)) {
man[i].Print();
n_man++; mean_pay += man[i].GetPay();
not_found = false;
break;

if (not_found) cout " " endl;


}
if (n_man) cout " : " mean_pay / n_man endl;
return 0;
}
///////////////////////////////////////////////////////////

.
/ .
. ,
ASCII (,
MS-DOS), / .
Windows (,
Visual C++ 6.0), ANSI, Windows,
() ASCII.

24

1.

.
cout <:
Rus(CTpOKOBafl_KOHCTaHTa), CharToOem
( Win32 API). 1
, OemToChar.
,
- .
, , :
4 CyrIstream CyrOstream,
1 Cout 1 cout
/
. ,
: CyrlOS.h CyrlOS.cpp,
. 159~l^ , ,
/, 7#111 CyrlOS.h.
. C++ ;1.
71
.h, <1ostream.h>. ,
, ISO/IEC 14882
(1998), ,
<1ostream>. , using namespace std;,
std.
,
,
, string^.
. , ,
, const
. -
, .
const
. ,
, - ,

, const. const
, , !.
. Cons
tructor is working, Destructor is working
. ,
.
^ http://www.piter.conn.
2 Microsoft Visual Studio.NET
, ISO/IEC 14882 (1998).

1.1.

25

!
, , .
.



^ Taskl_l
.
dbase.txt, , ^:
..
..
..
..

1957
1947
1938
1963

4200
3800
3000
6200

.
Ave Maria
.
:
Constructor 1s working
Constructor is working
Constructor is working
Constructor is working
Constructor is working
Costructor is working
Constructor is working
Constructor is working
Constructor is working
Constructor is working
end:

,
! . , 10
man.
. : .
Enter :
..
1938
3000
end:

: . Enter :
..
1947
3800
end:

1 Visual C++ 6.0,


2 Borland C++ 3.1.
Visual C++ 6.0
, (NotePad).

26

1.

: end. Enter :
: 3400
Destructor 1s working
Destructor is working
Destructor is working
Destructor is working
Destructor is working
Destructor is working
Destructor is working
Destructor is working
Destructor is working
Destructor is working
Press any key to continue

Bee ! end while (true)


.
. (return 0),
,
.


.
SetBirthYear SetPay

(, ).
, ,
. 6.1
.
:

:
strncpy(man[i].pName. buf. l_name);
man[i].pName[l_nanie] = ' \ 0 ' :
man[i].birth_year = atoi(&buf[l_name]):
man[i].pay = atof(&buf[l_name + l_year]);

:
man[i].SetName(buf);
man[i].SetBi rthYear(buf);
man[i].SetPay(buf):

, ?
.
.

1.1.

27


Windows
/ , : I OS. h
CyrlOS.cpp, . 160-164 http://www.piter.com,
#1 1 ude CyrlOS. h ,
/.
,
.



,
.
_ ()
. ,
. ,
.
, Point,
:
class Point {
double X. ;
public:
Point (double _x = 0. double _y = 0) { x = _x:
//. . .

= _y; }

:
Point(double _ = 0. double _ = 0) : (_), {_) {}

, ,
.
.
,
:
, ,
, ;
;
.
,
.
: .

28

1.

,
,
. , Point
(1.5. 2.0), ,
1
( C++),
1.5 2.0. Point , nppi
1.5 2.0.


, , .

{ constructor). :
;
;
.
, C++
, ,
.
, . , ,
,
,
.
, ,
.
, .
.

, ,
.
:
_(const _ & obj) {
/ /
}

obj , .
, , .
:
X = ;
Funcl(y);
= Func2();

/ /
/ /
/ /

1.1.

29

.
,
Func2().

1.2.


^ C++,
. ,
- ( ).
:
_ operator 7^ ( ) { }

# .
- ,
( ) .
1- ,
, .
, Point:
:
class Point {

double X. :
public:
//. . .
Point operator +(Poir1t&):
}:
Point Point::operator +(Point& p) {
return Point(x + p.x. + p.):
}

!, ,
, ,
.:
class Point {
double X. :
public:
//. . .
friend Point operator +(Point&. Point&):
}:
Point operator +(Point& p i . Point& p2) {
return Point(pl.x + p2.x. pi. + p2.y):

3a ::, ?:>>, ., .*, #, ##.

30

1.

+ :
Point . 2). 2(-1. 5):
Point = 1 + 2:

, , , 1 + 2,
1.operator +(2),
~ operator +(1, 2).

X = -1, = 7. ,
, ,
-.
,
, ? :
, - , .
, ( )
( , Int),
.


: .

, () .
. ,
, .
,
, :
Po1nt& operator ++():

/ /

Point o^^er^tor ++(1nt);

/ /

Point:
Po1nt& Point::operator ++() {
X++ ;

y+4-;

return 4h1s:
}
Point Point::operator ++(1nt) {
Point old = 4h1s;
X++;

++;

return old:
}

,
.
.
,
, -

1.1.

31

old. ,
, .
,
for. ,
: for (1 = 0: 1 < ; 1++). ,
1 ,
: . , 1

.
, 1
-.

for
.


.
-, ,
,
.
,
(. ). :
,
, .
-,
.
-, (
).
, Man 1,1
:
// Man.h ( )
class Man {
public:
// . . .
Man& operator =(const Man&): //
private:
char* pName:
// . . .
}:

32

1.

// . ( )
// . . .

8( Man: :operator =(const Man& man) {


if (this == &man) return 4h1s; //
delete [] pName:
//
pName = new char[strlen(man.pName) + 1];
strcpyCpName. man.pName);
birth_year = man.b1rth_year:
pay = man.pay;
return 4 h i s :
}

,
:
, = .
, .
, ,
pName, , ;
;
;
;
, this ( 4h1s).



. , ,
?
, .
static ,
.
,
, :
class Coo {

static int count; //


//
}:
int Coo::count = 1; //
// int Zoo:-.count', II


( static).
,
this.
(const) (virtual). -

1.2.

33

,
, , , .

.

1.2.

7
(
, ).
.

. (main)
.
, : 1)
; 2) > (
); 3)
: 1 ( ) 2.
,
.
, . ,
.
: mainO
, -, mainO,
.
/ .
Triangle .

, .
, , .
;
,
XVI .

, .
, , Point.
, ,
,
, Point .
, - : Triangle
Point. ?

34

1.


. ,
:
( is );
( has ).
, , Bis /\ (
, : Triangle is
Polygon).
, , has (,
: Triangle has
Point).
: ,
? ,
,
, .
, .
mainO.
, .

.
.
.
- ,
.
, :
.
, .
.
1.2
.
,
.
Point
Triangle, , Triangle
.

1
///////////////////////////////////////////////////////////
// Taskl_2
///////////////////////////////////////////////////////////
// Point.h
#ifndef POINT_H
#define POINT H

1.2.

35

class Point {
public:
//
PointCdouble _ = 0. double _ = 0) : (_). (_) {}
//
void ShowO const:
public:
double X. :
}:
#endif /* POINT_H */
///////////////////////////////////////////////////////////
// Point.cpp
#1nclude <1ostream>
#include "Point.h"
using namespace std;
void Point::ShowO const {
cout " (" X

")'

///////////////////////////////////////////////////////////
// Triangle.h
#ifndef TRIANGLEJ
#define TRIANGLEJ
#include "Point.h"
class Triangle {
public:
Triangle(Point. Point. Point, const char*): //
// ()
Triangle(const char*):
//
-TriangleO:
// vl
Point Get_vl() const { return vl: }
Point Get_v2() const { return v2: }
// v2
Point Get_v3() const { return v3: }
// v3
char* GetNameO const { return name: } //
void ShowO const:
//
void ShowSideAndArea( ) const:
//
public:
//
static int count:
private:
//
char* objID:
//
char* name:
//
Point vl. v2. v3:
// , vl v2
double a:
// , v2 v3
double b:
// , vl v3
double c:
#end1f /* TRIANGLE */

36

1.

IIIIIIIIIIIIIIIIIIIIIII

mill II

//Triangle.
/ / Triangle
#inclucie <math.h>
#include <iostream>
#inclucle <iomanip>
#inclucle <cstring>
//#inclucle "CyrlOS.h"
#include "Triangle.h"

/ / for Visual C++ 6.0

using namespace std:


//
Triangle: :Triangle(Point _vl. Point _v2. Point _v3. const char'^ ident)
: vl(_vl). v2(_v2). v3(_v3) {
char buf[16]:
objID = new char[strlen(ident) + 1];
strcpy(objID. ident);
count++:
sprintf(buf. " %d". count);
name = new char[strlen(buf) + 1 ] ;
strcpy(name, buf);
a = sqrt((vl.x - v2.x) * (vl.x - v2.x) +
b = sqrt((v2.x - v3.x) ^ (v2.x - v3.x) +
= sqrt((vl.x - v3.x) * (vl.x - v3.x) +
cout "Constructor_l for: " objID
" (" name " ) " endl;

(vl.y - v2.y) * (vl.y - v2.y))


(v2.y - v3.y) * (v2.y - v3.y))
(vl.y - v3.y) * (vl.y - v3.y))
//

// ()
Triangle::Triangle(const char* ident) {
char buf[16];
objID = new char[strlen(ident) + 1]:
strcpy(objID, ident);
count++;
sprintf(buf " ^d" . count);
name = new char[strlen(buf) + 1]
strcpy(name buf);
a = b = = 0;
cout . "Constructor_2 for: " ObjID
'' (" name ")' ' endl

//

//
Triangle::~Triangle() {
cout "Destructor for: " objID endl;

1.2.

delete [] objID;
delete [] name;
//
void Triangle::Show() const {
cout name ":":
vl.ShowO; v2.Show():
cout endl;

v3.Show();

//
void Triangle::ShowSideAndArea const {
double p = (a + b + ) / 2;
double s = sqrt(p * (p - a) '^ (p - b) ^ (p - c)):
cout "

" endl;
cout name ":";
cout.precision(4); '
cout " a= " setw(5) a;
cout ". b= " setw(5) b;
cout ". c= " setw(5) c;
cout ";\ts= " s endl;
}
///////////////////////////////////////////////////////////
// Main.cpp
#include <iostream>
#include "Triangle.h"
//#include "CyrlOS.h"
// for Visual C++ 6.0
using namespace std;
int
int
void
void
void
void
void

MenuO;
GetNumber(int. int);
ExitBackO;
ShowCTriangle* []. int);
Move(Triangle* []. int);
FindMaxCTriangle'^ [], int);
IsIncluded(Triangle* []. int);

//
int Triangle::count = 0 ;
//
int mainO {
//
Point pKO. 0);
Point p3(l. 0);
Point p5(2. 1);
Point p7(2, 2);

Point
Point
Point
Point

p2(0.5. 1);
p4(0. 4.5);
p6(2, 0);
p8(3. 0);

37

38

1.

//
Triangle triaA(pl. 2, ,
Triangle triaB(pl. 4. 8.
Triangle triaC(pl. p5. p6.
Triangle tr1aD(pl. p7. p8.

"tr1aA")
"triaB")
"triaC")
"triaD")

//
Triangle^ pTria[] = { &triaA. &triaB. &triaC. &triaD
int n = sizeof (pTria) / sizeof (pTria[0]);
//
bool done = false:
while (!done) {
switch (MenuO)
case 1 Show(pTria. n);
case 2 Move(pTria. n):
case 3 FindMax(pTria. n):
case 4 IsIncluded(pTria, n):
case 5 cout " ."
done = true;
break;

break;
break:
break:
break;
endl;

return 0;

}
//
int MenuO {
cout
endl:
cout
cout
cout

"\n=

==================="

"1 - oe\t 3 - " endl;


"2 - nepeMecTHTb\t\t 4 - " endl;
"\t\t
5 - " endl:

return GetNumberd. 5):


//

int GetNumber(int min. int max) {
int number = min - 1;
while (true) {
cin number;
if ((number >= min) && (number <= max) && (cin.peekO == '\n'))
break;
else {
cout " ( " min
" " max " ) : " endl;
cin.clearO;
while (cin.getO != '\n') {};

1.2.

39

return number;
}

//

void ExItBackO {
cout " Enter." endl;
cin.getO; cin.getO:
}
//

void Show(Tr1angle^ p_tr1a[]. Int k) {
cout "======= ========" endl:
for d n t 1 = 0; 1 < k: ++1) p_tr1a[1]->Show():
for (1 = 0 ; 1 < k: ++1) p_tr1a[1]->ShowS1deAndArea():
:
}

//

void Movedrlangle* p__tr1a[]. Int k) {


cout "============= =============" endl;
// ...
:
}
//

void F1ndMax(Tr1angle* p_tr1a[]. Int ) {
cout "=== ==" endl:
// ...
;
}
//

void Islncludeddrlangle'*' p_tr1a[]. Int ) {
cout "======== ==========" endl;
// ...
;
}
//

Taskl_2

//////////////////////////////////////////////////////////
Taskl_2.

Point ( Point.h, Point.).

Point ShowO,
: Point .
, -
ShowO ,
. - C++,

.

1 angl ( 1 angl . h, 1 angl . ).

40

1.

static int count ^


;
: 1, 2 . .,
count (
).
char* objID
; ,

.
ShowSideAndAreaO ,
,
( ), .
Q ()
,
.
ShowO . ShowO
Point. ,
; .

( Main.cpp).
:
int Triangle::count = 0; ,
.
mainO:
1,..., 8 , ,
;
,
;
,
;
Triangle* pTria[]
;
pTria ;

.
Menu()
Get Number (), ,
. GetNumberO?
: cin number;?
. -
static.

41

1.2.


4 4.2.
GetlntO^
ShowOnpocTo .
ExitBack,

.

, .

01
:
Constructor_l for triaA
Constructor_l for triaB
Constructor_l for tr1aC
Constructor 1 for triaD

(
(
(
(

1)
2)
3)
4)

===============
================
1 - 3 -
2 -
4 -
5 -
1^. :
1

1 (, 0) (0.5. 1) (1. 0)
2 (0. 0) (0. 4.5) (3. 0)
3 (0. 0) (2. 1) (2. 0)
4 (0. 0) (2. 2) (3. 0)
1: = 1.118. = 1.118. =

1:

s= 0.5

2: = 4.5. = 5.408. =

3:

s= 6.75

3: = 2.236. =

1. =

2;

s= 1

4: = 2.828. = 2.236. =
Enter.

3:

s= 3

9.2
( ),
stdio, .
Enter.

42

1.

. Enter. :
===============

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

. 2.
:
2

======================= =======================
Enter.

. Enter. :
===============

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

.
, w, Enter. :
( 1 5):

. 5. :
5
.
Destructor for
Destructor for
Destructor for
Destructor for

triaD
tr1aC
tr1aB
triaA

. ,
, .
. Point
Triangle , ; ,
! MoveO. , Triangle
ShowS1deAndArea(),
.

2
.
1. Point.h: ShowO
- +=,
MoveO Triangle:
void operator +=(Po1nt&):

2. Polnt.cpp. :
void Point::operator +=(Po1nt& p) {
X += p.x;
}

+= p.;

1.2.

43

3. 1 angl . h.
ShowSideAndAreaO.
:
void Move(Polnt);
4. 1 angl . .

ShowSideAndAreaO.
Move():
/ / (dp.x. dp.)
void Triangle::Move(Point dp) {
v l += dp:
v2 += dp:
v3 += dp:
}

5. Main.cpp.
:
double GetDoubleO:

6etDouble()
Show(), .
MoveO.
(, )
, GetNumberO:
//

double GetDoubleO {
double value:
while (true) {
c1n value:
if (cin.peekO == '\n') break:
else {
cout " ( ):" endl:
cin.clearO:
while (cin.getO != '\n') {}:
}
}
return value:
}

MoveO :
//

void Movedriangle* p _ t r i a [ ] . i n t ) {
cout "============^ =============" endl:
cout " ( 1 " " ) : ":
int i = GetNumberd. ) - 1:
p_tria[i]->Show():
Point dp:

44

1.

cout
dp.x
cout
dp.

" : ":
GetDoubleO:
" : ";
GetDoubleO:

p_tria[1]->Move(dp):
cout " :"
p_tr1a[1]->Show():
ExitBackO:

endl:

,
. ,
, ,
:^
2

============= =============
' ( 1 4): 1
1: (0. 0) (0.5. 1) (1. 0)
: 2,5
: -7
:
1: (2.5. -7) (3. -6) (3.5. -7)
Enter.
.

3
Triangle ,
,
F1ndMax(). :
1. Triangle.h: -:
bool operator >(const Tr1angle&) const:

2. Triangle.cpp: -:
/ / ( ) t r i a
bool Triangle::operator >(const Tr1angle& t r i a ) const {
double p = (a + b + c) / 2:
double s = sqrt(p * (p - a) ^ (p - b) * (p - c ) ) :
double pi = ( t r i a . a + t r i a . b + t r i a . c ) / 2:
double s i = sqrt(pl * (pi - t r i a . a ) * (pi - t r i a . b ) -^ (pi - t r i a . c ) ) :
i f (s > si) return true:
else
return false:

, .

1.2.

45

3. Main.cpp: FindMaxO :
//

void FindMax(Tr1angle* p_tr1a[], 1nt ) {

cout' "=== ==" endl;


// triaMax.
// .
// 1- .
Triangle tr1aMax("tr1aMax");
triaMax = *p_tria[0];
//
for (int i = 1; i < 4: ++i)
if (*p_tria[i] > triaMax)
triaMax = ^p_tria[i];
cout " : " triaMax.GetNameO endl:
ExitBackO:

. .
:
3
=== ==
Constructor_2 for: triaMax ( 5)
: 2
Enter.

, . ,
Enter. :
Destructor for:
===============
1 -
2 -
5

triaB

===================
3 -
4 -
-

, 5 Enter. ...
??? --!!! ! Visual Studio,

; :
Debug Assertion Failed!
Program: C:\. . . MAIN.EXE
File: dbgdel.cpp
Line 47

A ,
: ,
, Visual C++,
assert. . ,
...

46

1.

.
, :
5
.
Destructor for
Destructor for
Destructor for

tr1aD
triaC

. ,
:
? ,
. , -
triaB! ?
; .
FlndMaxO

: 2

Enter.
ExitBackO. Enter
:
Destructor for: triaB

.
, triaB
FindMaxO. ? triaB
mainO, , ! - ,
, FindMaxO. ... !
triaMax,
:
Constructor_2 for: triaMax ( 5)

,
FindMaxO? ,
. triaMax
.
, triaMax
triaB. ,
, ,

. ,
.
objID name triaMax
triaB. FindMaxO
, .

1.2.

47

mainO triaB
. , .
. Triangle
, .
:
1. Triangle.h.

:
Triangle(const Triangle&);

/ /

:
Triangles operator =(const TriangleS);
2. Triangle.cpp.

:
/ /
Triangle::Triangle(const Triangle& t r i a ) : v l ( t r i a . v l ) . v2(tria.v2).
v3(tria.v3) {
cout "Copy constructor for: " tria.objID endl: / /
objID = new char[strlen(tria.objID) + strlen("(o)") + 1]:
strcpyCobjID. t r i a . o b j I D ) ;
strcat(objID, "()");
name = new char[strlen(tria.name) + 1];
strcpy(name. tria.name);
a = tria.a;
b = tria.b
= tria.
}

:
/ / t r i a
Triangle& Triangle::operator =(const Triangle& t r i a ) {
cout "Assign operator: " objID " = " tria.objID
/ /

endl;

i f (&tria == this) return 4 h i s ;

delete [] name;
name = new char[strlen(tria.name) + 1];
strcpy(name. tria.name);
a = tria.a: b = tria.b; = tria.c;
return 4 h i s ;
}

,
, char*, -

48

1.

. ,
objID ().
, ,
. .
. .
:
3
=== ==
Constructor_2 for: triaMax ( 5)
Assign operator: triaMax = triaA
Assign operator: triaMax = triaB
: 2
Enter.

.
. 1 Enter. :
Destructor for: triaMax
===============
===================
1 -
3 -
2 -
4 -
5 -

, triaMax,
triaB. . 5. :
5
.
Destructor for:
Destructor for:
Destructor for:
Destructor for:

triaD
triaC
triaB
triaA

Bee. , .
, , .
.

4

,
^
, beg_p end_p.
.
,
. ,
.

1.2.

49

,
. (beg_p, end_p)
:
1) \
( LEFT),
2) ,
( RIGHT),
3) begp
( BEHIND),
4) end_p
( AHEAD),
5) , ( BETWEEN).
,
Point, Point :
enum ORIENT { LEFT. RIGHT. AHEAD. BEHIND. BETWEEN } :

a Class1fy(beg_p, end_p), ORIENT


(beg_p, end_p).
, ,
.
,
.
, .

, -
: RIGHT, BETWEEN.
InTriangleO Point.
, .
1. Point.h.
Point ORIENT,
Triangle:
enum ORIENT { LEFT. RIGHT,, AHEAD, BEHIND. BETWEEN } :
class T r i a n g l e ;

, Triangle
,
InTriangleO.
Point :
Point operator +(Point&):
Point operator -(Point&):

, ,
.

50

1.

double LengthO const;

//
//
ORIENT Class1fy(Po1nt&. Po1nt&) const: //
// .
//
bool InTr1angle(Tr1angle8i) const:
// ,
//
//

- - LengthO
ClassifyO, - + .
ClassifyO, , InTriangleO.
1. Point..
#inclucle <iostream> #include <math.h>.
sqrt(x)
C++ LengthO.
#i ncl ude Poi nt. h #i ncl ude Tri angl e. h.
Triangle
.
-:
Point Point::operator +(Point& p) {
return Point(x + p.x, + p.):
}

Point Point::operator -(Point& p) {


return Point(x - p.x. - p.):
}

LengthO:
double Point::LengthO const {
return sqrt(x*x + y^y):
}

ClassifyO:
ORIENT Point::Classify(Point& beg_p. Point& end_p) const {
Point pO = n h i s :
Point a = end_p - beg_p;
Point b = pO - beg_p:
double sa = a.x * b.y - b.x * a.y:
i f (sa > 0.0) return LEFT:
i f (sa < 0.0) return RIGHT:
i f ((a.x * b.x < 0.0) II (a.y * b.y < 0.0)) return BEHIND:
i f (a. Length < b. LengthO) return AHEAD:
return BETWEEN:

1.2.

51

[6],
. ,
.
InTriangleO:
bool Point::InTr1angle(Triangle& t r i a ) const {
ORIENT o r l = Class1fy(tr1a.Get_vl(). tr1a.Get_v2())
ORIENT or2 = Class1fy(tr1a.Get_v2(). tr1a.Get_v3())
ORIENT = Class1fy(tr1a.Get_v3(). tr1a.Get_vl())
I f ( ( o r l == RIGHT II o r l BETWEEN)
&& (or2 == RIGHT I I 02 == BETWEEN)
&& ( RIGHT II == BETWEEN)) return true:
else
return false:
}

2. Triangle.h: Triangle
( , ):
friend bool Tr1aInTr1a(Tr1angle. Triangle); / / .
/ /

3. Triangle.:
:
/ / , t r i a l tr1a2
bool Tr1aInTr1a(Tr1angle t r i a l , Triangle tr1a2) {
Point v l = tr1al.Get_vl();
Point v2 = tr1al.Get_v2():
Point v3 = tr1al.Get_v3();
return (vl.InTr1angle(tr1a2) &&
v2.InTr1angle(tr1a2) &&
v3.InTr1angle(tr1a2)):
return true:
}

, ,
(trial) (tr1a2).
4. 1 . : I s I 1 uded () :
//

void IsIncluded(Tr1angle* p_tr1a[]. Int ) {
cout "======== ==========" endl:
cout " 1- ( 1 "
Int 11 = GetNumberd. ) - 1;
cout " 2- ( 1 "
Int 12 = GetNumberd. ) - 1:
I f (Tr1aInTr1a('^p_tr1a[11]. *p_tr1a[12]))
cout p_tr1a[11]->GetName() " - - "
p_tr1a[12]->GetName() endl;

" ) : ";

" ) : ":

52

1.

else
cout p_tr1a[1l]->GetName() " - - "
p_tr1a[12]->GetName() endl; .
ExitBackO;
}

. .
. ,
, 1 2.
:
4
======== ==========
1- ( 1 4): 1
2- ( 1 4): 2
constructor for: triaB
Copy constructor for: triaA
Destructor for: tr1aA()
Destructor for: tr1aB(o)
1 - - 2
Enter.

:
Tr1aInTr1a(),
.
:
Triangle.h Triangle.cpp,
.
, .
, .
, ,
// ,
. .
1.2 .
.
1. -
,
, .
2. (,
, ). ,
, ,
( )
( ),
- -.
3. , .
(), (),
.

53

4. :
public ( ), private ( ) protected (
).
. , ,
.
5.
,
.
6. ,
.

1
, . ,
- .
,
( ).
.

2
, ,
, , ,
.
, -
. ,
.
.

3
: ,
, . ,
, .
, .
, .

4
,
.
, .
, .
, .

54

1.

5
.
, .
, .
, .

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

7
,
.
, , ,
, ,
() .
, .
, .

8

().
,
,

, ,
, .
, .
,
.

9

.
, , -

55

,
,
.
, .
, .

10
,
.
, ,
-,
.
, .
, .

11
,
.
,
,
,
, .
, .
, .

12
,
,
.
, .
, .

13
,
,
. :
;
;
;
.

56

1.

, .
, .

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

15
1 .
, - (,
, ), ,
.
, .
, .

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

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

57

, .
, .

18
,
, , .
, .
, .

19
, . ,
.
, .
, . .
, , .
.
.

20
.
, .
, , .
, ,
, .
, .
, .

2
: . 200-210.

.
.
. UML.
.
() .


-
. ( )
.
( / /).
, 1.2
, , Tetragon
angle.
, , (
, ) .
Polygon, ,
Triangle Tetragon,
() Polygon. C++ :
class Polygon {
// . . .
};
class Triangle : public Polygon {
public:
ShowO;

59

class Tetragon : public Polygon {


public:
ShowO:
}:

Triangle Tetragon
Polygon, Show().
Z5 ,
. Triangle is Polygon,
Tetragon is Polygon.
:
class : _ __ {
/ /
}:


() .
, , .
.
, .

(): private
, public .
protected,
. ,
,
.
,
, .
: (public), (protected)
(private).

, public
protected, , public protected
private. , C++
/5 .


,
. .
{)
. -
, ::, :
#1nclude <1ostream>
using namespace std;

60

2.

class Base {
public:
void Display { cout

"Hello, world!" endl: }

class Derived : public Base {


public:
void DisplayO {

Base::Display(): //
cout "How are you?" endl:

class SubDerived : public Derived {


public:
void DisplayO {
Derived::DisplayO : //
cout "Bye!" endl:

int mainO {
SubDerived sd:
sd.DisplayO:
return 0:
}

, , :
Hello, world!
How you?
Bye!



,
,
.
,
:

, ,
, .
,
,
.

61

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

, ,
- .^
. (,
) 1>1 , .



, , ,
, D 13
( ).
D, D:: ^
. C++ ,
D .
virtual
:
#1nclude <1ostream>
using namespace std:
class A {
public:
Adnt _x = 0) { X = _x: }
protected;
1nt x:
\class : virtual public A {
public:
void AddBdnt y) { x += y: }

class : virtual public A {


public:
void AddCdnt y) { x += y; }

, : f
.

62

2.

class D : public . public {


public:
void ShowXO { cout "x = " x endl: }

int mainO {
D d:
d.ShowXO:
d.AddB(lO):
d.AddB(5):
return 0:

d.ShowXO:
d.ShowXO:



. , (public)
,
. :
(, Polygon)
(, Triangle Tetragon).
, (
), ,
.
,
, . ,
:
class Base {
public:
// . . .
void ModifyO:
)
class Derived : publ ic Base {
public:
void ModifyO:
}:
int mainO {
i n t mode:
Base^ pB:
cin mode:
i f (mode == 1) pB = new Base
else
pB = new Derived:
pB->Modify():
// ?
return 0;

63

,
, , Base:: Modi .
, , . ,
(
, Derived:: Modify ), .
:
#1nclude <1ostream>
using namespace std:
class Base {
public:
Basednt _x = 10) { x = _x: }
void ShowXO { cout "x = " x
void ModifyXO { x *= 2; }
protected:
i n t x;

"; "; }

class Derived : public Base {


public:
void ModifyXO { x /= 2: }
}:

int mainO {
Base b:
Derived d:
b.ShowXO; d.ShowXO:
Base* pB;
pB = &b:
pB = &d:
return 0:

pB->Mod1fyX():
pB->Mod1fyXO;

pB->ShowX():
pB->ShowX();

:
X = 10; X = 10; X = 20: X = 20:

ModifyXO .


, ,
C++
. ,
virtual.
.

, , . ,

64

2.

, ,
, ,
, , .
.

{vtbl),
(vptr) vtbl^. ,
,
^.
,
virtual
Mod1fyX() , :
virtual void ModifyX { x *= 2: }

:
X = 10: X = 10: X = 20: = 5:
ModlfyXO .

. ,
, .
,
,
^.
,
,
''.

.
, , ,
. ,
Shape,
Polygon, Ellipse . .
, , Show() .
, ?
, ,
. , ' . .
^ .
'^ .
^
.
.

. UML

65

. , ,
.
= , :
virtual void ShowO = 0:
,
.

, ,
.

,
, 4 4.1.

.
UML
C++
- .


UMLK UML
.

, .
UML ^.
, ^ .

. ,
^ {design patterns),
-
.
UML ,
. .
("^), , ,
UML Unified Modeling Language.
( 2.3) euie
UML: .
pattern ,
template.
. . .
UML C++.

66

2.

. ('), ,
.
, (
), .
: + publ 1,
- private, # protected.
$.
,
, .
, . ,
Triangle 1.2,
1, . 2.1.
Triangle
Triangle
+Show()
+Move(clp: Point)

Triangle
+& count: int
-v1: Point
-v2: Point
-v3: Point
-obJIP: char*
+Triangle(_v1: Point, _v2: Point, _v3: Point, ident: const char*)
+Triangle(tria: const Triangle&)
+Show()
+Move(clp: Point)

. 2 . 1 . Triangle UIV1L

-
:
;
;
;
.
,
.

,
. , ,
: ( Product) ( Sale).
Sale , 1
Product. . 2.2
.
{multiplicity'^), , ' UML C++.
^ - cardinality.

. UML

67

.
UML

Product

1..*

Sale

. 2.2.


, .
, ,
.

(, Z5 ) ,
( ) ,
( ).

, .
, . 2.3, .
Superclass

Subclass 1

Subclass 2

. 2.3.

,
. ,
/, ^has , .
,
. . 2.4
( ). ,
( ),
.
?
: C++
. , ,

68

2.

.
.

. 2.4.

. ,
, .
1 1.2: ,
Triangle Point.
(. 2.5).
Triangle

Point

. 2.5.

-
, .
,
:
, .

( )
, (Client)
(Supplier), :
Client Supplier;
Client Supplier;
Client , Supplier.
,
Supplier. ,
1.2, . 2.6, Client Triangle,
Supplier Point.
Triangle
>^

Point

+Move(dp: Point)
. 2.6. ()

69




! .
,
(, , ).

.
, , ,
.
,
.
.
-
switch.
, , : SomeFunctionO
mode
:
typedef enum { model. mode2. mode3 } ModeType;
void SomeFunct1on(ModeType mode) {
switch (mode) {

case model: DoSomethinglO;


case mode2: DoSomething2():
case modes: DoSomething3();

break
break
break

ModeType
. , ,
ModeType.
,
mode4 mode. ,
.
,
switch . ,

, ,
.
-
? , ,
, . ,
, , , ,

70

2.

.
.
,
, .
, {design patterns^).
. (. Gamma), .
(R. Helm), . (R.Johnson) . (J. Vlissides) [7].

, .
, , ,
, ,
- .
,
. :
GoF95 Gang of four, 1995^.
23 .
, -
.


-+-+: string vector.
5 ,
: string -,
vector .

, .
.

. , [7], : ,
( ) , ,
!. [
. ?
!
: ( Switch)
,
, AbstractEntlty
DoSomethingO.
AbstractEntlty Entity 1, Ent1ty2 . .
, Switch
Entity 1, Ent1ty2 . ., ,

.
1995 .

71

std: :vector<AbstractEntity*>.
(. 2.7).
Switch
: std::vector<AbstractEntity*:
>^ SelectEntityO: AbstractEntity*

1..*

AbstractEntity
'">] DoSomethingO

Entityl

Entity2

DoSomethingO

DoSomethingO

. 2.7. Switch ()

, Switch AbstractEntity
( ), Switch
std: :vector<AbstractEntity*>. Switch
AbstractEntity ( ),
AbstractEntity*.
? , SelectEntity
Switch ( ). ,
SelectEntityO, , AbstractEntity*,
AbstractEntity.

DoSomethingO Entityl, Entity2...
?
.
- ,
EntityK,
vector<AbstractEntity*>.

, . 2.7
, , Switch.
2.1.
,
,
! ,
, ,
Strategy, ,
.

72

2.

Strategy (
) , , Switch
( Context Switch, Strategy AbstractEntity).
, -, : Switch
, , -,
Strategy, uia6 Switch SelectEntityO.
.
, ,
. , 2.2,
, DoubleSwitch.

2 . 1 .

,
, -
, , ,
.
:
= "";
= + .
/
.
, ,
.
,
, , 1.2 ( 1).
menu

. :
switch (MenuO) {

case 1: Show(...);
case 2: Move(...);

break;
break;

case 5: //
}
.
,
.
Switch, , .

73

2.1.

1. , Switch
Menu.
? ,
( --
, ). ,
, Menu
(
). : Function,
,
Line.
, . 2.8.
Menu
pObj: std::vector<Function*>

L._.>

SelectObject(): Function*

Main

Function

^ CalculateO
GetNameO
z\
1

CalculateO
GetNameO

1
|

Line
CalculateO
GetNameO

. 2.8.

, , ,
. CalculateO,
DoSomethingO Switch,
GetNameO, name,
. Menu
.
,
std::string std: -.vector.
string s string,
: -: std::string sC'C-cipo");
=. , s, ,
.
<string>.

74

2.

vector
^
<vector>. ,
,
-.
push_back().
, ^.
sizeO.
vector ,
,
^.
:
#1nclude <1ostream>
#1nclucle <vector>
using namespace std;

1nt mainO {
1nt a[5] = { 5. 4. 3. 2, 1 };
double b[] = { 1.1. 2.2. 3.3. 4.4 };
vector<char> vl:
vl.push_back('A'); vl.push_back('B'); vl.push_back('C):
for (1nt 1 = 0; 1 < vl. SizeO; ++i)
cout vl[i] ' ';
cout endl;
vector<int> v2(a. a + 5);
for (i = 0; i < v2.SizeO: ++i)
cout v2[i] ' ':
cout endl:
vector<double> v3(b. b + sizeof(b) / sizeof(double)):
for (i = 0: i < v3.SizeO: ++i)
cout v3[i] ' ';
cout endl:
return 0:
}

:
ABC
5 4 3 2 1
2.2 3.3 4.4

' (
, ).
^ , 6.
^ . 3.

2.1.

75

vl,
char, v2 1nt,
v3 double.

. ( v2) ,
. ( v3) ,
.

:
///////////////////////////////////////////////////////////
/ / Task2_l
///////////////////////////////////////////////////////////
/ / Function.h
#1fndef FUNCTIONJ
#def1ne FUNCTION_H
#1nclude <str1ng>
class Function {
public:
virtual -FunctionO {}
virtual const std::str1ng& GetNameO const = 0;
virtual void CalculateO = 0:
protected:
double x:
/ /

#endif / * FUNCTIONJ */
///////////////////////////////////////////////////////////
/ / Exp.h

#1nclude "Function.h"
// = ^
class Exp : public Function {
public:
ExpO : nameC'e ^ x") {}
const std::string& GetNameO const { return name; }
void CalculateO;
protected:
std::str1ng name; / / .
}:
extern Exp f_exp;
///////////////////////////////////////////////////////////

// Exp.cpp
#1nclude <1ostream>
#include <math.h>

76

2.

#1nclude "Exp.h"
using namespace std;
void Exp::Calculate() {
cout "Calculation for function = " name endl:
cout "Enter X = ": cin x:
cIn.getO:
cout "y = " exp(x) endl:
cIn.getO:
}
//
Exp f_exp:
///////////////////////////////////////////////////////////
// Line.h
#1nclude "Function.h"
// = * + b
class Line : public Function {
public:
LIneO : name("a ^ x + b") {}
const std::str1ng& GetNameO const { return name: }
void CalculateO:
protected:
std::str1ng name: // .
double a:
double b:
}:
extern Line f_11ne:
///////////////////////////////////////////////////////////
// Line.cpp
#1nclude <1ostream>
#1nclude "Line.h"
using namespace std:
void Line::Calculate() {
cout "Calculation for function = " name endl:
cout "Enter a = ": cin a:
cout "Enter b = ": cin b:
cout "Enter X = ": cin x:
CIn.getO:
cout "y = " (a "^ X + b) endl:
cIn.getO:
}
//
Line f_11ne:
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

II Menu.h
#1nclude <vector>
#1nclude "Functlon.h"

2.1.

class Menu {
public:
Menu(std::vector<Function*>);
Function* SelectObjectO const:
private:
int Selectltem(int) const;
std::vector<Function*> pObj:
}:
IllllllUllllllllllilllllllllllllllUIIIIIUIIIIIIIIIIIIIII
II Menu.cpp
finclude <iostream>
#include "Menu.h"
using namespace std:
Menu::Menu(vector<Function*> _pObj) : pObj(_pObj) {
pObj.push_back(0): // 'Exit'
}
Function* Menu::SelectObject() const {
int nitem = pObj.sizeO;
cout

"=====:==:=;====:=:===.==:====================\n";

cout "Select one of the following function:\n":


for (int i = 0: i < nItem; ++i) {
cout i+1 ". "; //
// , pObj
if (pObj[i]) cout pObj[i]->GetName() endl:
else
cout "Exit" endl;
}
int item = Selectltem(nltem);
return pObj[item - 1];
int Menu::SelectItem(int nItem) const {
cout "
\n";
int item;
while (true) {
cin item;
if ((item > 0) && (item <= nItem)
&& (cin.peekO == '\n')) {
cin.getO; break;
}
else {
cout "Error (must be number from 1 to
nItem " ) : " endl;
cin.clearO;
while (Cin.getO != '\n') {};

return item;

77

78

2.

IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
II Main.cpp
#include <iostream>
#include "Function.h"
#include "Exp.h"
#include "Line.h"
#i^clude "Menu.h"

using namespace std:


Function^ pObjs[] = { &f_exp. 8(fjine };
vector<Function*> funcList(pObjs. pObjs +
sizeof(pObjs) / sizeof(Function*));
int mainO {
Menu menu(funcList);
while (Function* pObj = menu.SelectObjectO)
pObj->Calculate():
cout "Bye!\n";
return 0:
}
//

Task2_l

//////////////////////////////////////////////////////////
.
Function ,
. (.
, ), ,
,
( Function.cpp). ,
(
), .
,
. -
,
, double.
,
.
virtual const std: :string8( GetNameO const
Function. ( const
), .
, (
) : std: :string&. ,
virtual std: :string& GetNameO const,
, string& -

2.1.

79

const. :
const std::string&.

CalculateO Line
( , , )
.

, . f_exp,
. Line f_l1ne.

Menu pObj
Function^, .
pObj ( )
pObj .push_back(0).

Exit (. Menu: :SelectObject()).

Menu: :SelectObject()
pObj.sizeO. for
SelectltemO,
. , SelectltemO
private Menu, .

main.cpp pObjs[],
&f_exp, 8(f_line.
fundi St.

mai() :
menu Menu, fundist, while,
. , menu.SelectObjectO
() f_exp f_line,
CalculateO .
, .

, ,
using . ,
using namespace std (
) std C++.
, cin, cout, string, vector.
:
using (, using std::string)^ std:: (, std::string). using.
:
std , ,

using.
[8] .
, .

80

2.

1. using, using,
. ^^
. std:: .
2. using
include.
, using -
.
.
mainO 1.2 2.1, ,
Switch. ,
,
.
Parabola, :
///////////////////////////////////////////////////////////
/ / Parabola.h

#include "Function.h"
// = * x^2 + b * x + c
class Parabola : public Function {
public:
ParabolaO : nameC'a * x^2 + b * x + c") {}
const std: :str1ng& GetNameO const { return name: }
void CalculateO:
protected:
std::string name: // .
double a. b. ;
}:
extern Parabola f_parabola:
///////////////////////////////////////////////////////////
// Parabola.cpp
#1nclude <1ostream>
#include "Parabola.h"
using namespace std;
void Parabola::Calculate() {
cout "Calculation for function = " name endl;
cout "Enter a = "; cin a;
cout "Enter b = ": c1n b;
cout "Enter = ": cin ;
cout "Enter x = "; cin X;
cIn.getO;
cout "y = " (a * X * X + b ^ X + c) endl:
cin.getO:
}
//
Parabola f_parabola;
///////////////////////////////////////////////////////////

2.2.

81

, mi . #1 1 ude
bo 1 . h;, pObjs
&f_parabola. !!! .

2.2.

.
, . ,
,
,
.
.
, . !
. -, ,
Function .1 Tabulation,
.
Function, . -,
:
, .

Switch.
' switch?
, .
.
( Switch)
? ,
EntityA_I
AbstractEntityA,
EntityB_J AbstractEntityB,

^ DoubleSwitch,
, . 2.9.
, SelectEntityAO Switch
AbstractEntityA'^,
SelectEntityBO,
, . AbstractEntityB
:
OperateO.

OperateO, .
, ?

82

2.

AbstractEntltyA* OperateO
AtomOperatelO, Atom0perate2() . .,
AbstractEntltyA.
OperateO
AbstractEntltyB. , ,
AbstractEntltyA
, .
Switch
: std::vector<AbstractEntityA*>
: std::vector<AbstractEntityB*>
SelectEntityA():AbstractEntityA*
SelectEntityB(aea: AbstractEntltyA*): AbstractEntityB*

1..*

_y_

lAbstractEntityAk,
AtomOperatelO
AtomOperate2()

1..*
AbstractEntityB
Operate(aea: AbstractEntltyA*)

EntityA_1

EntltyA_2

AtomOperatelO
AtomOperate2()

AtomOperatelO
AtomOperate2()

EntityBJ

EntityB_2

Operate(aea: AbstractEntltyA*)

Operate(aea: AbstractEntltyA*)

. 2.9. DoubleSwitch

. ,
Switch Menu, ,
AbstractEntltyA Function. AbstractEntityB
Action,
Calculation, Tabulation, AnyAction.
- ,
.
AbstractEntityB: :Operate(AbstractEntltyA*)
Action: :Operate(Function*). , , Calculate
Function Calculation,
Action. Function
, SetArg , SetCoeff
, GetVal .

2.2.

83

,
( ,
1 2.1).
:
///////////////////////////////////////////////////////////
/ / Task2_2
///////////////////////////////////////////////////////////
/ / Function.h
#ifndef FUNCTION_H
#def1ne FUNCTION_H
#1nclude <str1ng>
class Function {
public:
virtual -FunctionO {}
void SetArg(double arg) { x = arg: }
virtual void SetCoeffO = 0;
virtual double GetValO const = 0;
virtual const std::string& GetNameO const = 0:
protected:
double x;
/ /

#end1f /^ FUNCTIONJ ^/
///////////////////////////////////////////////////////////
/ / Exp.h
#include <math.h>
#include "Function.h"
/ / = ^
class Exp : public Function {
public:
ExpO : nameC'e ^ x") {}
const std::string& GetNameO const { return name; }
void SetCoeffO {}
double GetValO const { return exp(x); }
private:
s t d : : s t r i n g name:
/ / .
}:
extern Exp f_exp;
///////////////////////////////////////////////////////////

// Exp.cpp
#include "Exp.h"
//
Exp f_exp:
///////////////////////////////////////////////////////////
/ / Line.h
#include "Function.h"

84

2.

// = * + b
class Line : public Function {
public:
LineO : nameC'a * x + b") {}
const std::string& GetNameO const { return name; }
void SetCoeffO;
double GetValO const { return (a '^ x + b); }
private:
std::string name; // .
double a;
double b;
}:
extern Line f_line;
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

II Line.cpp
#include <iostream>
#include "Line.h"
using namespace std;
void Line::SetCoeff() {
cout "Enter a = ";
cout "Enter b = ";

cin a;
cin b;

//
Line f_line;
///////////////////////////////////////////////////////////
// Action.h
#ifndef ACTION_H
#define ACTION_H
#include "Function.h"

class Action {
public:
virtual -Action {}
virtual void OperateCFunction'^) - 0;
virtual const std::string& GetNameO const = 0;
#endif /* ACTION_H V
///////////////////////////////////////////////////////////
// Calculation.h
#include "Action.h"
class Calculation : public Action {
public:
CalculationO : name("Calculation") {}
const std::string& GetNameO const { return name; }
void Operate(Function*);

2.2.

private:
std: .-string name: //
}:
extern Calculation calculation;
///////////////////////////////////////////////////////////
// Calculation.cpp
#include <iostream>
#include "Calculation.h"
using namespace std;
void Calculation::Operate(Function* pFunc) {
cout "Calculation for function = ";
cout pFunc->GetName() endl;
pFunc->SetCoeff();
double x;
cout "Enter X = "; cin x;
cin.getO;
pFunc->SetArg(x);
cout "y = " pFunc->GetVal() e n d l ;
Cin.getO;

//
Calculation calculation;
///////////////////////////////////////////////////////////
// Tabulation.h
#include "Action.h"
class Tabulation ; public Action {
public:
TabulationO : name("Tabulation") {}
const std::string8i GetNameO const { return name; }
void Operate(Function*);
private:
std::string name; //
}:
extern Tabulation tabulation;
IIIIIIIIIIIIIIIIIIII
III II IIIIIIIIIIIIIIIIIIII
mm III III II
II Tabulation.cpp
#include <iostream>
#include <iomanip>
#include "Tabulation.h"
using namespace std;
void Tabulation::Operate(Function* pFunc) {
cout "Tabulation for function = ";
cout pFunc->GetName() endl;
pFunc->SetCoeff();
double x_beg, x_end. x_step;

85

86

2.

cout "Enter x_beg = "


cin x_beg;
cout "Enter x_end = "
cin x_end;
cout "Enter x_step =
cin x_step;
cin.getO:
cout "
" endl;
cout "
X
y" endl;
cout "
" endl:
double X = x_beg:
while (x <= x_end) {
pFunc->SetArg(x):
cout setw(6) X setw(14) pFunc->GetVal() endl;
X += x_step;
}
Cin.getO;
}
//
Tabulation tabulation;
///////////////////////////////////////////////////////////
// AnyAction.h
#include "Action.h"
class AnyAction ; public Action {
public;
AnyActionO ; name("Any action") {}
const std;;string& GetNameO const { return name; }
void OperateCFunction*);
private;
std;;string name; //
}:
extern AnyAction any_action;
///////////////////////////////////////////////////////////
// AnyAction.cpp
#include <iostream>
#include "AnyAction.h"
using namespace std;
void AnyAction;;Operate(Function*) {
cout "Your advertising might be here!" endl;
Cin.getO;

//
AnyAction any_action;
///////////////////////////////////////////////////////////
// Menu.h
#include <vector>
#include "Function.h"
#include "Action.h"

2.2.

class Menu {
public:
Menu(std::vector<Funct1on*>. std::vector<Action^>):
Function* SelectObjectO const:
Action'^ SelectAct1on(Funct1on*) const;
private:
1nt Selectltemdnt) const;
std::vector<Funct1on*> pObj;
std::vector<Act1on*> pAct;
}: ///////////////////////////////////////////////////////////
// Menu.cpp
#1nclude <1ostream>
#1nclude "Menu.h"
using namespace std:
Menu::Menu(vector<Funct1on*> _pObj. vector<Act1on*> _pAct)
: pObj(_pObj). pAct(_pAct) {
pObj.push_back(0); // 'Exit'
}
Function* Menu::SelectObjectO const {
// Task2_l

Action* Menu::SelectAct1on(Funct1on* pObj) const {


Int nitem = pAct.slzeO;
cout "======================================\n"
cout "Select one of the following Act1ons:\n";
for (Int 1 = 0; 1 < nltem; ++1) {
cout 1 + 1 ". ";
cout pAct[1]->GetName() endl;
}
Int Item = Selectltem(nltem);
return pAct[1tem - 1];
Int Menu::Selectltemdnt nltem) const {
// Task2_l
}
///////////////////////////////////////////////////////////
// Maln.cpp
#1nclude <1ostream>
#1nclude "Function.h"
#1nclude "Exp.h"
#1nclude "Line.h"
#1nclude "Action.h"
#1nclude "Calculation.h"
#1nclude "Tabulation.h"
#1nclude "AnyActlon.h"

87

88

2.

#1nclude "Menu.h"
using namespace std:
Function* pObjs[] = { &f_exp. &fjine };
vector<Function*> funcLisKpObjs, pObjs + sizeof(pObjs)/sizeof(Function*)):
Action* pActs[] = { &calculation. &tabulation, &any_action };
vector<Action*> operList(pActs. pActs + sizeof(pActs) / sizeof(Action*));
int mainO {
Menu menu (fundi St. operList):
while (Function* pObj = menu.SelectObjectO) {
Action* pAct = menu.SelectAction(pObj);
pAct->Operate(pObj):

cout "Bye!\n";
return 0;
}
//
Task2_2
//////////////////////////////////////////////////////////

:
: :SetCoeff() , ,
;
, ,
. f_exp.
,
- .
,
, ,
.

2.3.

, :
(SymbString) (HexString),
.
:
, . SymbStrin

2.3.

89

, HexStiing
.
( main) :
, , ( ),
(
HexString), (
HexString). ,
.

UML, {Activity Diagram),
.
UML -
.
, UML {Activity).
, ,
,
.
.
.
, -,
.
, , -, /
, -, ^
.
, . 2.10
. ,
, .

, .
, ,
, . ,
:
1) ( ,
, , );
2) ;
3) .
,
. ,
: ThreeLevelSwitch,
DoubleSwitch?

mainO.

90

2.

. ,
, , , ^

^ Exit

f AddObject ^

meleteObjecT)

/Select0bject(): Object*^

--rSelectAction(Object*): Action*]

-/Action*pAct-> Operate()j

. 2.10. 2.3

: (),
, ,
.
switch,
DoubleSwitch,
,
.
. : SymbString HexString
.
,
( ,
,
). DoubleSwitch , , ,
.

2.3.

91

AString,
SymbString HexString, Action,
ShowStr, ShowDec, ShowBin.
, , Menu,
SelectObjectO SelectActionO,
SelectJobO. , ,
( ShowStr, ShowDec ShowBin),
, , std: :vector<Action*> pAct.
, 2.2,

. , .
?
. :
. , mainO,
,
! ? ,
mainO^

, ,
, .
Factory,
AString. std::vector
<AString*> pObj : AddObjectC )
DeleteObjectO.

. :
///////////////////////////////////////////////////////////
/ / Task2_3
///////////////////////////////////////////////////////////
/ / AString.h
#ifndef ASTRING_H
#define ASTRING_H
#include <string>

class AString {
public:
virtual -AStringO {}
,
virtual const std::string& GetNameO const = 0:
virtual const std::string8i GetValO const = 0;

, ,
.
.

92

2.
virtual 1nt GetSlzeO const = 0;

}:
#end1f //ASTRINGJ
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

II SymbString.h
#1nclude <str1ng>
#1nclude "AString.h"
class SymbString : public AString {
public:
SymbStr1ng(std:iStrlng _name) : name(_name) {}
SymbStr1ng(std::str1ng _name. std::str1ng _val) :
name(_name). val(_val) {}
const std::str1ng& GetNameO const { return name; }
const std::str1ng& GetValO const { return val; }
Int GetSlzeO const { return val.slzeO; }
private:
std::string name;
std::string val;
};

III iiiiii I mill


II HexStrlng.h

III III II iiiii

mil II11 III

IIIIIIIIIIIIIIII11

#1nclude <str1ng>
#1nclude "AString.h"
const std::str1ng alph = "0123456789ABCDEF";
bool IsHexStrVaKstd: :str1ng);
class HexStrIng : public AString {
public:
HexStr1ng(std: :string _name) : name(_name) {}
HexStr1ng(std: :str1ng. std::str1ng);
const std::str1ng& GetNameO const { return name; }
const std::str1ng& GetValO const { return val: }
Int GetSlzeO const { return val.sizeO; }
private:

std::string name;
std::string val;
}:
///////////////////////////////////////////////////////////
// HexStrIng.cpp
#1nclude <1ostream>
#1nclude "HexStrlng.h"
using namespace std;
bool IsHexStrVal(string _str) {
for (Int 1 = 0; 1 < str.slzeO; ++1)

2.3.

i f (-1 == alph.find_first_of(_str[i3))
return false;
return true;

HexString;:HexStr1ng(string _name, string _val) ;


name(_name) {
i f (IsHexStrVal(_val))
val = _val;
}
lllllllllllllIIlllllllIIIIIIIIIIIIIIIIIIIIIIIIIIlllllllllll

II Action.h
#ifndef ACTION_H
#define ACTION_H
#include "AString.h"

class Action {
public;
virtual -ActionO {}
virtual void Operate(AString^) = 0;
virtual const std;;str1ng& GetNameO const = 0;
protected;
long GetDecimaKAString'^ pObj) const:

#endif /* ACTION_H */
lllllllllllllllllllllllllllllllllIIIIIIIIIIIIIIIIIIIIIIIIII

II Action.cpp
#1nclude <1ostream>
#include "Action.h"
#include "HexString.h"
using namespace std:
long Action:;GetDecimal(AString^ pObj) const {
i f (dynamic_cast<HexString^>(pObj)) {
long dest;
string source = pObj->Get\/al ;
sscanf(source.c_str(). "^IX". &dest);
return dest;
}
else {

cout "Action not supported." endl;


return -1;
///////////////////////////////////////////////////////////
// ShowStr.h
#include "Action.h"

93

94
class ShowStr : public Action {
public:
ShowStr0 : nameC'Show string value") {}
void Operate(AString"^):
const std::strings GetNameO const { return name: }
private:
std::string name: //
}:
extern ShowStr show_str:
///////////////////////////////////////////////////////////
// ShowStr.cpp
#include <iostream>
#include "ShowStr.h"
using namespace std:
void ShowStr::Operate(AString* pObj) {
cout pObj->GetName() ": ":
cout pObj->GetVal() endl:
cin.getO:
}

//
ShowStr show_str;
lllllllllllllllllllllllllllllllllllllllllllllllllllll

II ShowDec.h
#include "Action.h"
class ShowDec : public Action {
public:
ShowDecO : name("Show decimal value") {}
void Operate!AString*):
const std::string& GetNameO const { return name: }
private:
s t d : : s t r i n g name:
/ /
}:

extern ShowDec show_dec:


/////////////////////////////////////////////////////
// ShowDec.cpp
#include <iostream>
#include "ShowDec.h"
#include "HexString.h"
using namespace std:
void ShowDec::Operate(AString* pObj) {
cout pObj->GetName() ": ":
long decVal = GetDecimal(pObj):
if (decVal != -1)
cout GetDecimal(pObj):
cout endl:
Cin.getO:

2.

2.3.

//
ShowDec show_dec;
llllllllllllinillllllllllllllllllllinilllllllllllll

I I ShowBi'n.h
#1nclude "Action.h"
class ShowBIn : public Action {
public:
ShowBinO : nameC'Show binary value") {}
void OperateCAString*):
const std::string& GetNameO const { return name; }
private:
s t d : : s t r i n g GetBinaryCAString*) const:
s t d : : s t r i n g name;
/ /
}:

extern ShowBin show_bin;


/////////////////////////////////////////////////////

// ShowBin.cpp
#include <iostream>
#include "ShowBin.h"
#include "ShowDec.h"
#include "AString.h"
using namespace std:
void ShowBin::Operate(AString* pObj) {
cout pObj->GetName() ": ";
cout GetBinary(pObj) endl:
cin.getO;
}
string ShowBin::GetBinary(AString* pObj) const {
i n t nBinDigit = 4 * pObj->GetSize();
char* binStr = new char[nBinDigit + 1];
for ( i n t = 0; < nBinDigit: ++k) binStr[k] = '0'
binStr[nBinDigit] = 0;
long decVal = GetDecimal(pObj);
i f (-1 == decVal)
return s t r i n g ( " " ) :
i n t i = nBinDigit - 1;
while (decVal > 0) {
b i n S t r [ i - - ] = 48 + (decVal % 2);
decVal = 1:
}

string temp(binStr):
delete [] binStr;
return temp;
}
//
ShowBin show bin;

95

96

2.

IlllllllllllUltllllllHlllllllllllllllllllllllllllll

I I Factory.h
#ifndef FACTORY_H
#define FACTORYJ
#include <vector>
#include "AString.h"
class Factory {
friend class Menu;
public:
Factory0 {}
void AddObjectO;
void DeleteObjectO;
private:
std::vector<AStr1ng*> pObj:
#endif //FACTORY_H
lllllll

III II11IIIIII

inn III IIII III III III III

I I Factory.cpp
#include <iostream>
#include "Factory.h"
#include "Menu.h"
#include "SymbString.h"
#include "HexString.h"
using namespace std;
#define mX_LEN_STR 100
void Factory::AddObjectO {
cout "

\n";

cout "Select object type:\n";


cout "1. Symbolic string" endl;
cout "2. Hexadecimal string" endl;
int item = Menu::SelectItem(2);
string name;
cout "Enter object name: ";
cin name;
cin.getO;
cout "Enter object value: ";
char buf[MAX_LEN_STR];
cin.getline(buf. MAX_LEN_STR);
string value = buf;
AString* pNewObj;
switch (item) {
case 1:

2.3.

pNewObj = new SymbString(name. value);


break;
case 2:
i f (lIsHexStrVal(value)) {
cout "Error!" endl;
return;
}

pNewObj = new HexStr1ng(name. value);


break;
}
pObj.push_back(pNewObj);
cout "Object added." endl;
void Factory;;DeleteObject {
1nt nitem = pObj.slzeO;
if (!nltem) {
cout "There are no objects." endl;
cin.getO;
return;
}
cout "
\n";
cout "Delete one of the following Object:\n";
for (int 1 = 0; 1 < nItem; ++1)
cout 1 + 1 ". " pObj[1]->GetName()
endl;
1nt item = Menu;:SelectItem(nItem);
string objName = pObj[1tem - l]->GetName();
pObj.erase(pObj.begin() + item - 1);
cout "Object " ObjName " deleted." endl;
Cin.getO;
}
/////////////////////////////////////////////////////
// Menu.h
finclude <vector>
#include "AString.h"
#1nclude "Action.h"
#include "Factory.h"
typedef enum { AddObj, Del Obj. WorkWithObj. Exit } JobMode;
class Menu {
public;
MenuCstd;;vector<Action*>);
JobMode
SelectJobO const;
AString* SelectObject(const Factory&) const;
Action*
SelectActionCconst AString*) const;
static int Selectltem(int);
private;
std;;vector<Action*> pAct;
}:

97

98

2.

IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII
II Menu.cpp

#1nclude <1ostream>
#include "AString.h"
#1nclude "SymbStrlng.h"
#include "HexString.h"
#include "Menu.h"
using namespace std:
Menu::Menu(vector<Act1on^> _pAct) : pAct(_pAct) {}
JobMode Menu::SelectJob() const {
cout "======================================\n"
cout "Select one of the following job modes:\n"
cout "1. Add object" endl;
cout "2. Delete object" endl;
cout "3. Work with object" endl;
cout "4. Exit" endl;
int item = Selectltem(4);
return (JobMode)(item - 1);
AString* Menu::SelectObject(const Factory& fctry) const
int nitem = fctry.pObj.size();
if (Inltem) {
cout "There are no objects." endl:
cin.getO;
return 0;
}
cout

"

.\n";

cout "Select one of the following Object:\n";


for (int i = 0; i < nItem; ++i) {
cout i + 1 ". ";
cout fctry.pObj[i]->GetName() endl:
}
int item = Selectltem(nltem);
return fctry.pObj[item - 1];
Action^ Menu::SelectAction(const AString* pObj) const
if (!pObj) return 0;
int nItem = pAct.sizeO;
cout "
\n";
cout "Select one of the following Actions:\n":
for (int i = 0; i < nItem; ++i) {
cout i + 1 ". ";
cout pAct[i]->GetName() endl;
}
int item = Selectltem(nltem);
return pAct[item - 1]; .

2.3.
I'nt Menu::SelectItemdnt nitem) {
// Task2_l
}
/////////////////////////////////////////////////////
// Main.cpp
#1nclude <1ostream>
#include "AString.h"
#1nclude "SymbString.h"
#1nclude "HexString.h"
#include "Action.h"
#include "ShowStr.h"
#1nclude "ShowDec.h"
#1nclude "ShowBin.h"
#1nclude "Factory.h"
#1nclude "Menu.h"
using namespace std;
Action* pActs[] = { &show_str. &show_dec. &show_bin };
vector<Action*> actionList(pActs.
pActs + sizeof(pActs)/sizeof(Action*));
int mainO {
Factory factory;
Menu , menu(actionList);
JobMode jobMode;
while ((jobMode = menu.SelectJobO) != Exit ) {
switch (jobMode) {
case AddObj: factory.AddObjectO;
break;
case DelObj: factory.DeleteObjectO;
break;
case WorkWithObj;
AString* pObj = menu.SelectObject(factory);
Action* pAct = menu.SelectAction(pObj);
if (pAct)
pAct->Operate(pObj);
break;
}
cin.getO;

cout "Bye!\n";.
return 0;
}
//
Task2_3
//////////////////////////////////////////////////////////

99

100

2.

HexString.cpp IsHexStrVal (string _str),


, _str .
f1nd_first_of() string,
, , alph.
HexString.h
. , fincl_first_of()
- 1 . IsHexStrVal ()
HexString, val
, AddObjectO Factory,
.

Action GetDecimal (AString* pObj),



pObj .
? , ShowDec::
Operate , ShowBin: :GetBinary()

.

Action: :GetDecimal ()
,
RTTI Run-Time Information. , (
) ,
. ,
AString.
,
. ,

dynamic_cast, .
, : <HexString*>,
( pObj
HexString), ,
.

ShowBin: :GetBinary() decVal


, while
binStr, '' '
. decVal
decVal % 2 ASCH
(ANSI), , ( 1) 48.
decVaV .
, ,
. ( .)

2.3.

101

Menu SelectltemO . ?
, .

Menu, Factory.
, SelectltemO
, ,
Menu::.
Factory: :AdclObject() vector
<AString*> pObj push_back() vector.
Factory: :DeleteObject() erase() vector.
. 1 tern ,
vector,
.1() + item - 1, beginO ,
.
.
1. .
,
.
2. C++ ,
.
.
3.
: )
, )

. , ,

.
4. ,
: , , ().

UML.
5. ,
,
,
.
6.
. 2.1 2.2
: Switch DoubleSwUch,
,

.

102

2.

1 - 2 0
, : 1 2,
.
( )
( ).
( main)
(): , ,
( ).
Factory., ,
.

(, , . .)
.

1 - 1 0
. 2.1 2.2
.
2 . 1 .

SymbString

( )

BinString

( )^

OctString

( )

DecString

( )

HexString

( )

2.2. ()
()

ShowB1n()

ShowOctO

ShowDecO

ShowHex()

operator +(& si. & s2)^

SymbString si s2;

.
1 2.

103

()

operator -(& s i . & s2)

SymbString s2
si, ,
si s2;
si;


:
, SymbString.
2.3 .
2.3. 1-10

()

SymbString

BinString

ShowOctO. ShowDecO.ShowHexO

SymbString

BinString

operator +(&, T&)

SymbString

BinString

operator -(T&. T&)

SymbString

OctString

operator +(T&. T&)

SymbString

OctString

operator -(T&. T&)

SymbString

DecString

ShowBinO. ShowOctO. ShowHexO

SymbString

DecString

operator +(T&. T&)

SymbString

DecString

operator -(T&. TS)

SymbString

HexString

operator +(T&. T&)

10

SymbString

HexString

operator -(T&. T&)

1 1 - 2 0
. 2.4 2.5
.
2.4.

Triangle

Quadrate

Rectangle

Tetragon

Pentagon

104

2.

2.5. ()
()

MoveO

Compare(T& obi. & 2)

obi ob2 no

IsIntersect(T& obi. & 2)

obi 2
( )

IsInclucle(T& obi. & 2)

2 obi

2.6 .
2.6. 11-20

()

Triangle

Quadrate

MoveO

Compare(T&. T&)

12

Quadrate

Pentagon

MoveO

IsIntersect(T&. T&)

13

Triangle

Rectangle

MoveO

Compare(T&. T&)

14

Triangle

Rectangle

MoveO

IsIntersect(T&. T&)

15

Rectangle

Pentagon

MoveO

IsInclude(T&. T&)

16

Triangle

Tetragon

MoveO

Compare(T&. T&)

17

Triangle

Tetragon

MoveO

IsIntersect(T&. T&)

18

Triangle

Tetragon

MoveO

IsInclude(T&. T&)

19

Triangle

Pentagon

MoveO

Compare(T&. T&)

Triangle

Pentagon

MoveO

IsIntersect(T&. T&)

20

3 .

: . 211-230.


, , C++
,
. C++

. ,
.

(template instantiation).
, , . 1.2
Point,
double. ,

, int.
, ,
short unsigned char. Point
?
, C++ ,
.

106

3. .


(, ) :
template <_> class _ { /'^ ... */ };

, Point
:
template <class > class Point {
public:
P o l n t d _x = 0. T _y = 0) : x(_x). y(_y) {}
void ShowO const {
cout " (" X ". " " ) "
}:
private:
T X.

endl;

y:

}:

, ?
template <class > , ,
. class
, , .
.
, . ,
class
typename, :
template < typename > class Point { / * ... */ }:

, , ,
^

.
, .
ShowO:
/ / ShowO
template <cTass > class Point {
public:
Po1nt(T _x = 0, T _y = 0) : x(_x). y(_y) {}
void ShowO const:
private:
T X.

y:

}:
template <class T> void Polnt<T>::ShowO const {
cout " (" X ". " " ) " endl;

, , . :
, ,
: template <class > ...

107

template <class >,


,
Show():
Point::, Point<T>::,
, ( )^



, ,
.
^ , .
, , :
Po1nt<1nt> anyPo1nt(l3. -5):


, new, :
Po1nt<clouble>* pOtherPoint = new Po1nt<clouble>(9.99. 3.33):

,
.



.
,
.

, Point.h,
#1 1 ude.
, ,
, #ifndef
( . , . 153).
Point:
/////////////////////////////////////////////////
/ / Point.h
#ifndef POINT_H
#define POINT_H
template <class T> class Point {

Ha (
), , - ,
.

108

3. .

public:
Po1nt(T _ = 0. _ = 0) : (_). (_) {}
void ShowO const:
private:
X. :

template <class > void Po1nt<T>::ShowO const {


cout " (" X ". " " ) " endl;
}
#end1f /^ POINT_H ^/
/////////////////////////////////////////////////
// Main.cpp
#1nclude <iostream>
#1nclude "Point.h"
using namespace std:
int mainO {
Po1nt<double> p i ;
Point<double> p2(7.32. -2.6);
pl.ShowO; p2.ShowO;
Po1nt<int> p3(13. 15);
Point<short> p4(17. 21);
p3.Show(); p4.ShowO;
return 0;
i

III
// 2
// 3
// 4

Point mainO:
1 2 Point
double, 3 Point int,
4 short.
,
^ (STL),
, ,
, , . . ,
, vector.
,

.



, int^. . , .
C++ -,
, .

109

,
, .
,
. , ,
:
template <class . 1nt n> class Array { / * . . . * /

};

,
Array<Po1nt. 20> ;

20 Point.

^:
void f l O { cout
void f2() { cout

" I am f l O . " endl: }


" I am f 2 ( ) . " endl; }

template<vo1d (*pf)()> struct A { void ShowO { p f O ; } };


Int maInO {
A<&fl> aa

aa. ShowO
A<&f2> ab
ab. ShowO
return 0;

// ; I am flO.
// ; I am f2().

.
^.
, . ,
STL :
template <class Key. class , class Compare = less<Key> >
class map { / * . . ."^Z } ;

, ,
, . 1
>.
, -

' :
#1nclude <1ostream>
using namespace std;

Ho , , .
^ , .

110

3. .

,
^


. ,
, < ()
,
, -, .
,
:
template <> class _ <__> { / * ... */ };
:

//
template <class > class Sample {
bool Less(T) const: /^...*/ }:
// char^^
template <> class Sample<char*> {
bool Less(char*) const: Z'^...*/ };

,
. :
/ /
template <class T l . class 2> class Pair { / * . . . ^ / }:
/ / , 2 1nt
template <class 1> class Pair <1, 1nt> { /-^..
}:

;
.
, - .
:
/ /
template <class > bool Sample<T>::Less(T ob) const { / * . . . ^ / }:
/ /
void Sample<char'^>: :Less(char* ob) const { / * . . . * / }:

' , Visual C++ 6.0 : fatal error...: end offile found before the
left angle-bracket '<'at '...\main.cpp(...)' was matched.

111



, ,
operator(). , ,
, , . :
#1nclude <1ostream>
using namespace std:
struct LessThan {
bool operatorO (const i n t x, const 1nt y) {
return X < y;
}

int mainO {
LessThan I t ;
i n t a = 5. b = 9:
i f ( l t ( a . b))
cout a

// 1

// 2
" less than " b

endl:

if (LessThan()(a. b))
// 3
cout a " less than " b endl;
return 0:
}

LessThan ^ operatorO.
, 1, It . , ,
. if ( 2)
operatorO, .
i f ( 3)
.
LessThanO LessThan,
. LessThanO (. )
operatorO . ,
i f , .
, , : LessThan
, if ( < )? .
,
.
, struct ,
.

112

3. .

.
PairSelect,
, .
(), .
class Compare.
: LessThan ( ) GreaterThan (
).
, ,
LessThanO GreaterThanO
,
class Compare.
:
template <class > struct LessThan {
bool operatorO (const T& x. const T& y) {
return X < y;

template <class T> struct GreaterThan {


bool operatorO (const T8i x. const T& y) {
return X > y;

template <class T. class Compare>


class PairSelect {
public:
Pa1rSelect(const T& x, const T8i y) : a(x). b(y) {}
void OutSelectO const {
cout (Compare()(a. b) ? a : b) endl:
}
private:
T a. b:
}:
Int mainO {
Pa1rSelect<1nt, LessThan<1nt> > psl(13. 9):
psl.OutSelectO:
/ / : 9
Pa1rSelect<double. GreaterThan<double> > ps2(13.8. 9.2);
ps2.OutSelectO;
/ / : 13.8
return 0;
}

Compare()(a. b)
OutSelectO, PairSelect
. , psl, -

3.1.

113

PairSelect LessThan<1nt>.
, ps2, GreaterThan<double>.




, .
,
, .

,
, ,
.
, , .
,
, , .

.

,
. ,
, :
. ,
, . ,
:
S p a r s e A r r sa(lOOOOOO);

1 000 000 ,
. ,
100 ,
.

: .
, , .

3 . 1 .


. .
,
,

114

3. .

. ,
.
,
.
. mainQ
.
,
.
, , ,
.
,
: .

. ,
?
, , :
template, <1 ass DataT> class SAJtem {
public:
SA_1tem(long 1, DataT d) : indexd), 1nfo(d) {}
long index;
DataT info;
};

,

? ,
.

(eco)^
. ,
, l i s t STL.
- STL 6,
vector 2; ,
list,
.
l i s t STL
,
.
<list>.
, .

,
.

3.1.

115

push_back().
l1st<T>::Iterator.
ao^ .
.
.
, .
11 st ,
: beg1n() , endO
, .
, end
!=,
< .
11 st :
#1nclude <1ostream>
#1nclude <l1st>
using namespace std;

1nt mainO {
I1st<char> vl;
vl.push_bacl<( 'A')
vl.push_back('B')
vl.push_back('C)
I1st<char>: :1terator 1 = vl.beginO;
list<char>: :iterator n = vl.endO;
for (1; 1 != n; ++1)
cout *1 ' ; // ,
// 1
cout end!:
return 0:
}

,
, , ,
.
, :
///////////////////////////////////////////////////////////
/ / Task3_l

IIIIII III 11111 III IIIIIIIIII III nil mil

SparseArr.h
#1fndef SPARSE_ARR_H
#def1ne SPARSE_ARR_H
#1nclude <l1st>

6.

116

3. .

template <class DataT> class SAJtem {


public:
SAJtemO : index(-l). info(DataT()) {}

SA_item(long i. DataT d) : index(i). info(d)


long index;
DataT info;

template <class T> class SparseArr {


public:
SparseArr(long len) : length(len)
T& operator [](long ind);
void ShowCconst char*);
private:
std::list<SA_item<T> > ;
long length;

template <class T>


void SparseArr<T>::Show(const char* title) (
cout "===== " title " =====\n";
list<SA_item<T> >::Uerator i = arr.beginO;
list<SA_item<T> > : : i t e r a t o r n = arr.endO;
for ( i ; i != n; ++i)

cout i->index "\t" i->info endl

template <class T>


T& SparseArr<T>::operator[](long ind) {
if ((ind < 0) II (ind > length - D ) {
cerr "Error of index: " ind endl;
SA_item<T> temp;
return temp.info;
}
list<SA_item<T> > : : i t e r a t o r i = arr.beginO;
list<SA_item<T> > : : i t e r a t o r n = arr.endO;
for ( i ; i != n; ++i)
i f (ind == i->index)

return i->info; //
// ,
arr.push_back(SA_item<T>(ind. ) ) ;
, i = arr.endO;
return (--i)->info;

3.1.

#end1f

117

/ ^ SPARSE_ARR_H ^ /

IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

Maln.cpp

#1nclude <1ostream>
#1nclude <str1ng>
#1nclude "SparseArr.h"
using namespace std;
1nt malnO {
SparseArr<double> sal(2000000);
sal[127649] = 1 . 1 :
sal[38225] = 1.2;
sal[2004056] = 1.3;
sal[1999999] = 1.4;
sal.ShowC'sal"):

// 1
// 2
// 3
// 4
// 5
// 6

cout "sal[38225] = " sal[38225] endl:


sal[38225] = sal[93]:
cout "After the modification of sal:\n";
sal.Show("sal"):

// 7
// 8
// 9
// 10

SparseArr<str1ng> sa2(1000):
sa2[333] = "Nick":
sa2[222] = "Peter";
sa2[444] = "Ann":
sa2.Show("sa2");
sa2[222] = sa2[555];
sa2.Show("sa2");
return 0;

// 11
// 12
// 13
// 14
// 15
// 16
// 17

//

Task3_l

llllllllllllllllllllllllllllllllllllllllllllllllllllllllll

arr SparseArr,
list, SA_1tem<T>,
. ,
SparseArr.

operator[]() ,
Ind .

, , c^vv^,
,
. :
temp SA_1tem()
info.
ostream,
. cout, 11,
.

118

3. .

SA_item
, ,
.
:
, - 1 . ,
. , ;
.

. ,
exitO
. , ,
: ,
. .
, for
.
info .
:
.push_back(SA_1tem<T>(1ncl. ) ) :

info ,
. arr.endO,
() , .
,
-1.
info .
Show(), cout
( ) .
ma1n() SparseArr.
sal 2 000 000
double. .

sal[127649] = 1 ;

sal.operator[]( 127649).
,
, 127649 0.0 ( double
). Info
0.0,
1.1. 3 5 ,
4 .
7
cout. 8
sal[38225] 0.

119

,
. ( sal)
:
Error of index: 2004056
===== sal =====

127649
38225
1999999

1.1
1.2
1.4

sal[38225] = 1.2
After the modification of sal:
===== sal =====

127649
1.1
38225
0
1999999 1.4
93
0
Bo sa2 1000
string. .
:
===== sa2 =====

333 Nick
222 Peter
444 Ann
===== sa2 =====
333 Nick
222
444 Ann
555



( ),
, (
)? , ,
:

, ;


, .

,

. , -

1 20

3. .

.
: , operator[]()
SparseArr info .
, ,
:
?

( STL).
, , , ,
.
C++
(exception). ,
. ,
- (,
). ,

.


, :
try.

throw try , .
try
catch.
,
try:
try {

//
}

throw, , throw
. , throw,
.
,
.

catch:
catch (/* . . . V ) {

//

121

:
catch
catch
//
//
}
catch

() { / / }
( info) {

info
(...)

{ / / }

,
. ,
, , try-
.
,
throw .
,
.


throw ,
C++ :
throw ,
, ;
;
, ,
.
? :
try {
throw ;
}
catch () {
// ?
}

, :
;
;

.
:
class {
public:
{ cout "Constructor of A\n"; }
- { cout "Destructor of A\n": }

1 22

3. .

class Error { } ;
class ErrorOfA : public Error { } ;
void fooO {
A a:

throw 1;
cout "This message is never printed" endl;
int mainO {
try {
fooO:
throw ErrorOfAO;
}
catchdnt)
{ cerr
catch(ErrorOfA) { cerr
catch(Error)
{ cerr
return 0;

"Catch of 1nt\n"; }
"Catch of ErrorOfA\n"; }
"Catch of Error\n"; }

:
Constructor of A
Destructor of A
Catch of Int

, throw 1
fooO. C++
1 .
fooO , mainO.
( !) , foo()^
!
maInO
Catch of int. , throw
ErrorOfAO .
try .
throw ErrorOfAO :
Catch of ErrorOfA

, ErrorOfA . ,
( )
. catch (ErrorOfA).
:
Catch of Error

123


, ,
std: :term1nate(). terminateO ,
, ,
, ,
. terminateO abortO.
, ,
:
int mainO {
throw 5:
return 0;
}

/ /

(Windows 2000 Professional Visual Studio 6.0)



(. 3.1).
Microsoft &^

0bug Errorj

^^

. 3 - 1 . ( AbortSample)

( ) abort
. set_term1nate(). :
void SoftAbort() { .
cerr "Program is terminated."
exitd);

endl;

i n t mainO {
set_termi nate(SoftAbort);
throw 5;
return 0;

,
.

124

3. .

.
,
(, , 1nt ),
.
(, ErrorOfA)
throw ,
^


.
. ,
:
/ /
class MathError { / * . . . * / } ;
/ /
class Overflow : public MathError { / * . . . * / } :
/ / " "
class ZeroDivide : public MathError { / * . . . * / };
// ...


ErrProcessO, ErrProcessO,
,
try catch,
:
try {
/ / MathError, Overflow. ZeroDivide. . . .
}

catch (MathError& me) {


me.ErrProcessO //
}
catch
MathError, ,
ErrProcessO,
.
,

. , ,
, ,
,
.

1 25


,
.
throw. :
void Funcdnt ) throw (Fool. Foo2):

, Func
Fool, Foo2 , 1 , .
,
.
,
.
,
,
? std: :unexpected(),
^
, ,
std: :term1nate().
unexpected () ,
, .
set_unexpected().
throwO, ,
.
,
, ,
.
,
( )
.

, .
, typedef
. :
typedef 1nt (*PF)() throw(A):

/ /



(, , ),
. , .

1 26

3. .

( ), ,
, :
class Vect {
public:
Vect(char):
-VectO { delete [] p: }
1nt& operator [] (int 1) { return p[1]: }
void PrIntO:
private:
1nt* p;
char size;

Vect::Vect(char n) : s1ze(n) {
p = new 1nt[s1ze]:
if (!p) {
cerr "Error of Vect constructor" endl;
return:
}
for (int 1 = 0: 1 < size: ++1) p[1] = intO:
void Vect::Pr1nt() {
for (1nt 1 = 0: 1 < size; ++1)
cout p[1] " ":
cout endl:

1nt mainO {
Vect a(3):
a[0] = 0: a[l] = 1: a[2] = 2:
a.PrintO:
Vect al(200):
al[10] = 5:
al.PrintO:
return 0:
}

.
Vect,
1 nt
( ).
, , ,
256. ()
. -

1 27

! ,
, , .
Vect char size,
, char ,
0...255.
ma1n() .
, , :
12
Error of Vect constructor

(
)^ ,
al[10] = 5.
- . ,
. , Error of Vect
constructor al.
, new
. 200,
, ^?
.
... , ,
. , , [1],
24-25 , char
signed char,
. char
-128...+127.
, .
200? , 8.
8 , 11001000.
? , , ?.. ,
-1001000.
. ,

.
. ,
, .
-56. ?
, , ' , .
^ , ,
,
.

128

3. .

size -56, ,
.
, . ... ,
.
, new,
, , .
cout
. - !
(
) .
char unsigned char^
. ,
new^.
. ,
, ,
.
,
(),
, (,
).
^.

:
Vect:iVectCchar ) :.size(n) {
= new 1nt[s1ze];
1f (!p)
throw "ErrVectConstr";
for (1nt 1 = 0: 1 < size; ++1) p[1] = i n t O ;
}

mainO
:
1nt mainO {
try {
Vect a(3):

a[0] = 0: a[l] = 1: a[2] = 2:


a.PrintO;
^ .
^ new
.
^ , !

129

Vect al(200):
alClO] = 5:
al.PrintO;
}
catch (char^ msg) {
cerr "Error: " msg

endl;

}
return 0;
}

, const char^
1 .
.
.


, , , ?1
,
, terminateO.
, ,,
. 3.1, . .
: ,
,
] ,
:
1. throw.
2.
,
,
, DestroyC),
try/catch:
::Destroy {

// ,
}

::~() {
try { Destroy : }
catchC.) { /* ... */ }
}

, .
Tasl<3_l,

.

130

3. .

,
, .

3.2.
( )
Vect
(). ,
,
. :
, ;
, ;
,
;

, ;

, ;

, .

.
.
main() .
( )

, , ,
(, , . .).
,
new,
.
^ f 1 rst, , , "^ 1 ast.
, size
, . 3.2.

first

v[0]

v[l]

v[size() - 1]

last

. 3.2. v

Vect
, ,
std: .vector STL (, -

3.2. ( )

131

, ).
:

void insertd'*' _. const & _) _;

void push_back(const & _) ;

void pop_back() ;

'^ beginO ;

^ end , ;

size_t sizeO ^

std: :vectorl
, ,
STL ( 6).
, ,
,
.
Vect, ,
std:: vector.
, ,
.
,
( markName), .
,
,
.
.

.
: ,
,
. ,
, , new
. , ,
, , ,
, .

VectError. VectRangeErr
, VectPopErr
.
,
.
^ std; :s1ze_t unsigned int.
^ , iterator, std::vector,
*, .

132

3. .

IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

I I Task3_2
IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

I I VectError.h
#1fndef _VECT_ERROR_
#def1ne _VECT_ERROR_
#1nclude <1ostream>
#def1ne DEBUG
class VectError {
public:
VectError {}
virtual void ErrMsgO const {
std::cerr ".Error with Vect object.\n";
}

void ContlnueO const {


#1fdef DEBUG
std::cerr "Debug: program Is being continued.\n";
#else
throw;
#end1f
}
}:
class VectRangeErr : public VectError {
public:
VectRangeErrdnt _m1n. Int _max, 1nt_actual) :
m1n(_m1n). max(_max). actual(_actual) {}
void ErrMsgO const {
std::cerr "Error of Index: ":
std::cerr "possible range: " min " - "
max ", ";
std::cerr "actual Index: " actual std::endl;
ContlnueO:
}
private:
Int min. max;
Int actual;
}:
class VectPopErr : public VectError {
public:
void ErrMsgO const {
std::cerr "Error of pop\n";
ContlnueO;

3.2. ( )

#end1f /* _VECT_ERROR_ */

llllllllllllllllllllllllllillllllllllllllllllllllllllllllll
II Vect.h
#1fndef _VECT__
#def1ne JECT_
#1nclude <1ostream>
#1nclude <string>
#1nclude "VectError.h"

// Template class Vect


tempiate<class T> class Vect {
public:
e x p l i c i t VectO
: f i r s t ( O ) . last(O) {}
e x p l i c i t \/ect(size_t _n. const T& _v = TO) {
Allocate(_n):
for (size_t i = 0 : i < _n: ++i)
* ( f i r s t + i ) = _v:
}

Vect(const Vect8():
//
Vect& operator =(const Vect&): //
-VectO {
#ifdef DEBUG
cout "Destructor of " markName endl:
#endif
DestroyO:
first = 0. last = 0:

//
void markCstd::string& name) { markName = name: }
//
std::string markO const { return markName: }
size_t sizeO const: //
* beginO const { return first: } // 1-
* endO const { return last: }
// .
//
T8i operator[](size_t i):
//
void insertCT^ _. const & _):
// _
void push_back(const & _):
//
void pop_back():
//
void showO const:
// cout
protected:
void Allocate(size_t _n) {
f i r s t = new T [_n '^ sizeof(T)]:
last = f i r s t + n:

1 33

134

3. .

void Destroy {
for (* = first; != last; ++)
delete [] first;

->~();

* first; // 1-
'^ last: // ,
std::string markName;

//
tempiate<class >
Vect<T>::Vect(const Vect& other) {
size_t n = other.sizeO;
Allocate(n);
for (size_t i = 0 ; i < n; ++i)
*(first + i) = ^(other.first + i);
markName = stringC'Copy of ") + other.markName;
#ifdef DEBUG
cout "Copy constructor: " markName endl;
#endif

//
tempiate<class T>
Vect<T>& Vect<T>;;operator =(const \/ect& other)
if (this == &other) return nhis;
DestroyO:
size_t n = other.SizeO;
Allocate(n);
for (size_t i = 0 ; i < n; ++i)
^(first + i) = *(other.first + i);
return 4his;
}
//
tempiate<class T>
size_t \/ect<T>::SizeO const {
if (first > last)
throw VectErrorO;
return (0 == first ? 0 : last - first);

//
tempiate<class T>
T& Vect<T>::operator[](size_t i) {
if(i < 0 II i > (SizeO - 1) )

3.2. ( )

throw VectRangeErrCO. last - f i r s t - 1. 1):


return (*(f1rst + 1 ) ) ;

}
// _ _
tempiate<class >
void \/ect<T>: .-Insert(* _P. const T& _x) {
s1ze_t n = sizeO + 1: //
* new_f1rst = new T [n '^ sizeof(T)];
T* new_last = new_f1rst + n;
s1ze_t offset = _P - first;
for (s1ze_t 1 = 0; 1 < offset; ++1)
*(new_f1rst + 1) = ^(flrst + 1 ) ;
'^(new_f1rst + offset) = _x;
for (1 = offset; 1 < n; ++1)
*(new_f1rst + 1 + 1) = *(f1rst + 1 ) ;
DestroyO;
first = new_f1rst;
last = new last;
//
tempiate<class >
void Vect<T>:;push_back(const T& _x)
1f (IslzeO) {
Allocated);
*f1rst = _x;
}
else 1nsert(end(), x ) ;
//
tempiate<class >
void Vect<T>::pop_back() {
Ifdast == first)
throw VectPopErrO;
T* p = endO - 1;
p->~T();
last-;
}
// cout
tempiate<class T>
void Vect<T>;;show() const {
cout "\n===== Contents of " markName "=====" endl;

1 35

136

3. .

size_t = sizeO:
for (s1ze_t 1 = 0 ; 1 < n; ++1)
cout * ( f i r s t + i ) " "
cout endl;
}
#endif / * _VECT_ * /

///////////////////////////////////////////////////////////
11 Main.cpp
#include "Vect.h"
finclude <iostream>
#include <string>
using namespace std:
tempiate<class T> void SomeFunction(Vect<T> v) {
std::cout "Reversive output for " v.markO
size_t n = v.sizeO;
for (int i = n - 1; i >= 0: -i)
std::cout v[i] " ";
std::cout endl;
int mainO {
try {
string initStr[5] = {"first", "second", "third"
Vect<int> v K l O ) ; vl.mark(string("vl"));
size_t n = v l . s i z e O ;
for ( i n t i = 0; i < n; ++i)

vl[i] = i+1:
vl.showO:
SomeFunction(vl);
try
Vect<string> v2(5):
v2.mark(string("v2"));
size_t n = v2.size():
for ( i n t 1 = 0: i < n; ++i)
v2[i] = i n i t S t r [ i ]
v2.show();
v2.insert(v2.begin()
v2.show();

cout v2[6] endl


v2.push_back("Add_l")
v2.push_back("Add_2")
v2.push_back("Add_3")
v2.show():
v2.pop_back();

3. "After third");

endl:

"fourth", " f i f t h " } ;

3.2. ( )

137

v2.pop_back();
v2.show();

}
catch (VectError& vre) { vre.ErrMsgO: }
try {
Vect<1nt> v3;
v3.mark(str1ng("v3"));
v3.push_back(41):
v3.push_back(42);
v3.push_back(43):
v3.show():
Vect<1nt> v4;
v4.mark(str1ng("v4")):
v4 = v3:
v4.show():
v3.pop_back();
v3.pop_back():
vS.showO:

v3.pop_back():
v3.pop_back();

}
catch (VectError& vre) { vre.ErrMsgO; }
}
catch (...) { cerr "Epilogue: error of Main().\n": }
return 0;
}
//

Task3_2

//////////////////////////////////////////////////////////
.
VectError.h .
VectError .
ErrMsgO,
(
).
Cont1nue(),
. .

: #def1ne DEBUG.
DEBUG ,
, .
ContinueO , :

138

3. .

Debug: program is being


continued, ;
( throw)
, ,
.

VectRangeErr VectPopErr
ErrMsgO .
Continue . ,
VectRangeErr min, max actual,
ErrMsgO ,
.

Vect. h Vect.
.

AllocateO PI DestroyO^ , new [],
, , ,

. Destroy ()
~() ,
delete.
, for
!= last, < last.
STL, ,
(, )
,
.
last. != last
.

!, markName.
.
( )
.
operator[]() (
1 f) , - (,
).
, , VectRangeErr.

: ,
.
, .

3.2. ( )

1 39

size
first last. - ,
first , last? ,
. -
^
,
. ,
, VectError.
insert
_ _.
.
^;
new_first, new_last.
, ,
_.

first, offset ,
_^1 new_first + offset
_.
, new_fi rst + offset + 1. .
, (Destroy),
first last .
push_back() _
insert .
, ,
_. insertO
, endO.
_() ,
. first = last = 0. ,
, , , , , ,
VectPopErr.
,
~(), last ^.
: if _(),
VectPopErr,
first > last.
,
: , ,
.
, , , .
, ,
. ,
5.
.

140

3. .

Maln.cpp
SomeFunctionO ma1n().
SomeFunctionO
cout.
Vect .
mainO Vect.
: try
try. !
try
v2, ! , .
try v3,
.
, catch
VectError,
VectRangeErr VectPopErr,
ErrMsgO
! , ErrMsgO
ContinueO,
.
! Cont1nue()
. , ContinueO
. , ,
try catch(...) .
, , .
.

. #def1ne DEBUG
. !
.
.
1.
.
2.
() .
3.
.
4.
.
5.
: -
.

141

6.
(, 4>).
, ( )
,
.
7. 11
,
.
8. 1^ : ) ~
try; )
throw try
, ; )
try catch.
9. , throw,
.
,
. ,

.
10. .
, ,
.


,
, .
, .
, ^
, std: .vector.
, ,
. 3.1.
( , , , ) .
(. 114-127), [2] ( 9).
3 . 1 .


Vect
List

142

3. .

Stack
1
Queue
Deque



(
)
( ;
)
<:

Set
SparseArray

, ,
1 ,
! new.

.
mainO ,
, . 1nt, double, s t d : : s t r i n g .
. 3.2.
3.2.

1
2
3
4
5
6
7
8
9
10

12

Vect
List
Stack
Stack
Stack
Stack
Stack
BinaryTree
Queue
Queue
Queue
Deque

Vect
List
std:: list
Vect

13
14

Deque

List

Deque

std:: 11st

15
16

Set

Set

Vect

17
18

Set
Set

std:: vector

19

Set

std:: list

20

SparseArray

List

std: :list

Vect
List
std::: vector
std:::11st

List

: . 265-280.


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

, .
C++ Enter.

'\',
.
C++ /
( /), (
/).
- .
, ,
, . .

144

4.

C++ ,
1os streambuf. 1os
,
/. streambuf
,
.
: 1os , streambuf.


, / (/),
. 1 stream,
~ ostream.
1os. piepapxnn 1 ostream,
1 stream ostream
/.


/ ++

C++, ISO/IEC 14882 (1998),
.
, <1ostream>, ,
using namespace std;,
std.
#1nclude <1ostream>, ,
,
.h, : #1nclude <1 ostream.h >^,
, , ,
^.


/
#1nclude <1ostream>
:
1 1 stream, ;
cout ostream, '^.
using namespace std; .
, string.
, ostream: clog
,
.

145

. 1 cout
.
/ :
' '
(, ) ^; ' '
.
, ostream
ostream& operator(short):
ostream& operator(int);
ostream& operator(double):
// . . .
, ,
i n t X = 5;
cout ;

, ostream,
int. , ostream&
operator(1nt) ostream.
cout .operator(x), 5.
, , int
double, ostream
.
, ostream
, ios.
cin,
: .
,
ios,
/. ,
. istream ostream
iomanip.
. 4.1 ^.
4 . 1 .

endl

ios
-

dec

flags(ios: :dec)

,
- C++.
.
. 271-273.

146

4.

4.1 ()

ios

hex

flagsdos: :hex)

Oct

flagsdos: :oct)

setprec1s1on(n)

prec1s1on(n)

setw(n)

widthCn)

setfi11(c)

f1ll(c)

,
:
cout.flagsdos: :hex);

cout

cout hex ;
,
.
setpreclsion(n)
prec1s1on(n),
. ,
los: :x_prec1s1on ( ).
,
, :
los::scientific ( , );
ios::fixed ( ).
(,
flags ), x_prec1sion .
, ,
, x_precision .
,
, .
setw(n) width(n):
,
.
(
) ( ).
iomanip.
:
1) , (endl,
ends) (flush);

147

2) , 1os, (dec, hex, oct);


3) .

, 4.1.
, ios ,
/, .
/ . 4.2^
4 . 2 . / ios

get
get(c)
get(buf. num.
I1m='\n')

getl1ne(buf. num.
I1m='\n')
peek

read(buf. num)
gcountO
rdbufO
put(c)
wr1te(buf. num)

EOF,


, 11
( '\'), num-1
.
buf, .
11
, 11
( buf )
( )
, ; EOF,

num !! buf
,

streambuf, !!


num buf


/ 0++ /
, .
,
, scanf () printf ()
.
,
-
. .
. . 273.

148

4.


cout.
-
, , .
1os state,
() ,
. 4.3.
4.3.

10S:

ios:
1os:
1os:

goodbit
eofbit
fall bit
badbit

rdstateO,
int. ,
:
1nt eofO , eofbit:
int fall () ,
/ ( ).
badbit, fail bit;
int bad ,
/ ( badbit);
int good , .
,
fail bit, ,
, void clear(int = 0).
1(),
.
state,
.
4.2.


,
C++
MyClass, .
obj MyClass cin obj; cout
obj. , ?
. 4.3, | ().

4.1. , /

149

MyClass. ,
-
, . /
/.
, .
.
1 streams operator (1stream& 1s. MyClass& obj)

1 s , obj ,
. 1s.
:
ostream& operator (ostream& os. MyClassS obj)

OS , obj ,
. os.
,
(MyClass obj). , ,
-, obj, , MyClass .
4.2.
.
/
Visual C++ 6.0 1.
Cyrlstream
CyrOstream. .

4 . 1 .
,
/ ^

: Cyrlstream CyrOstream, Cin Cou


( ) cin cout.
Cyrlstream CyrOstream
istream ostream . Cyrlstream
ASC
ANSI, CyrOstream
CyrlOS.h,
CyrlOS.cpp.
:
CyrlOS.h, CyrlOS.cp;
Win(lows-poe.

150

4.

, cin / cout /
, #include CyrlOS.h.
: , ,
, , / ?

. ,
.


, . ,
. ,
, ,
. ^ IDE Microsoft Visual
Studio 6.0 (Microsoft Visual C++ 6.0).

C++, ] , ,
, .
CyrOstream. ?
, , ,
- ,
ostream8( operator (const char* s);
ostream. .
? .
, ,
ostream.
. .
, ,
.
,
,
. , .

Microsoft Visual C++ 6.0


. :
Insert/Remove Breakpoint / ^;
Go 11[ ;
Step Over ./1 (
, );
Step Into (
, );
Stop Debugging .

IDE Visual C++ 6.0,


.

4.1. , /

151

SearchlOS, SearchlOS.cpp
:
//////////////////////////////////////////////////////////
/ / SearchlOS.cpp
#1nclude <1ostream>
using namespace std;

int ma1n() {
cout " C++!":
cout encll:
return 0;
}

// 1
// 2

.
1 Go.
.
STEP INTO. ~ ! ostream

tempiate<class _. class _Tr> Inline bas1c_ostream<_E. _Tr>8( _cdecl operator
(bas1c_ostream<_E. _Tr>& _0. const _E '^_X) { ... }

Ho ?
ostream& operator (const chaf^ s)!
, !
template? , ostream ( )
bas1c_ostream, ostream!
:
(short, 1nt . .) ,
. .
, ,
, , cdecl,
Microsoft
C++.
bas1c_ostream, ostream? ,
,
typedef bas1c_ostream<char, char_tra1ts<char> > ostream;

iosfwd.
.
Step Over.
2 mainO. Step Into
ostream
_Myt& operator(_Myt& (__cdecl ^_F)(_Myt&))

{ return ( ( * J ) ( n h 1 s ) ) : }

152

4.

, _F
- endl (), ostream.
_Myt?
typedef basic_ostream<_E. _Tr> _Myt;

. Step Over
return 0;.
- :
- ? C++!

. .
cout -
. Stop Debugging.
CyrOstream.
? ,
, . ,
.
11
. , , basicostream
? ostream.
:
e x p l i c i t basic_ostream(basic_streambuf<_E. _Tr> *_S. bool _Isstd = false,
bool _Doinit = true) { ... }
basic_ostream(_Uninitializeci) { ... }

, . ,
, CyrOstream ,
. ,
~ ?.. , ,
cout! cout cout? ,
iostream.. , :
_CRTIMP2 istream cin(_Noinit);
_CRTIMP2 ostream cout(_Noinit);
He _CRTIMP2
^ C++, Microsoft^. Noinit.
? , - . ,
xstddef ^ :
enum _Uninitializeci {_Noinit}:

, _Noinit _Uninitializeci. ,
cout
^ : Idefine _CRTIMP2 dec 1 spec(dl 1 export) xstddef.
^ C++
.

4.1. , /

1 53

bas1c_ostream. ,
.
const char*,
, , , -
, .
, ! .
Task4_la :
///////////////////////////////////////////////////////////
/ / Task4__la
///////////////////////////////////////////////////////////
/ / CyrlOS.h
#1fndef CYR_IOS_H
#def1ne CYR_IOS_H
#1nclude <1ostrearn>
#1nclude <1oman1p>
#1nclude <string>
#1nclude <windows.h>
using namespace std:
#def1ne MAX_STR_LEN 4096
/ / CyrOstream
class CyrOstream : public ostream {
public:
CyrOstream(_Uninitialized n o j n i t ) : ostream(no_init) {}

CyrOstream& operator (const char*):


private:
char buf [MAX STR LEN]:

extern CyrOstream Cout;


#endif /* CYR_IOS_H */
#ifndef CYR_IOS_IMPLEMENTATION
// 1
#define cout Cout
// 2
#endif
// 3
///////////////////////////////////////////////////////////
// CyrlOS.cpp
#define CYR_IOS_IMPLEMENTATION
// 4
#include "CyrlOS.h"
// CyrOstream
CyrOstream& CyrOstream: :operator (const char* s) {
int n = strlen(s);
strncpy(buf_. s. n); buf_[n] = 0;

1 54

4.

CharToOem(buf_, buf_);
cout buf_;
return 4his;
}
//
CyrOstream Cout(_No1n1t);
// 5
//////////////////////////////////////////////////////////
// Task4_la.cpp
#1nclude "CyrlOS.h"
int mainO {
cout " C++!":
cout eridl;
return 0;

//
// 7

//
Task4_la
//////////////////////////////////////////////////////////

.
CyrlOS.h.
no_1nit
CyrOstream.
private buf_ _
STR_LEN,
.
1, 2, 3 Cout cout
, CYR_IOS_IMPLEMENTATION.
( 4) ,
CyrlOS.cpp. , CyrlOS.cpp
cout, Cout.
CyrlOS.cpp.
const char'^ s .
CharToOem buf_ ANSI
ASCII, cout.
4 Cout.
. .
-
error: binary ' ' : no operator defined which takes a right-hand operand of type "

7. ,
, - ' ' endl.
! _Myt&
operator(_Myt& ( cdecl *_F)(_Myt&)), SearchlOS?
,
C++.

4.1. , /

1 55

.
,
,
() ,
!


,
!
, - ,
est ream, CyrOstream.
. CyrlOS.h
:
CyrOstream& operator (_Myt& (_cdecl * _f)(_Myt&));

, SearchlOS,
endl. :
CyrOstream& operator d n t n) { cout n; return 4h1s; }
CyrOstream& operator (double f ) { cout f: return 4 h i s ; }

, 1 nt doubl ,
,
. CyrlOS.cpp
:
CyrOstream& CyrOstream::operator (_Myt& (__cdecl * _f)(_Myt&)) {
cout _f:
return 4h1s;
}

()
, -
cout.
, , ma1n() :
double = 372.141526:
cout endl;

( )
:
C++!
372.142
,
^ .
Mos: :x_prec1s1on .

156

4.

.
(. ),
~ hex.
mainO ,
:
int X = 1024:
cout " = " X endl:
cout "x(hex) = ":
cout hex:
cout X endl:

,
:
error: binary ' ' : no operator defined which takes a right-hand operand of type ' " .

cout hex.
Ho , :
ostream, ,
. , ,
. ,

SearchlOS? mainO ,
cout hex,
:
_Myt& operator(ios_base& (_cdecl *_F)(ios_base&)) { . . . }

Task4_la .
CyrOstream ( CyrlOS.h) :
CyrOstream& operator (ios_base& (__cdecl * _f)(ios_base& ));

a CyrlOS.cpp :
CyrOstream& CyrOstream::operator (
ios_base& (_cdecl * _f)(ios_base& )) {
cout _f:
return 4 h i s :
}

:
C++!
X = 1024
x(hex) = 400

( ),
.
.
: setw(int), .
mainO :

4.1. , /

1 57

double =372.141526:
cout setwOO) encll;

:
C++!
, Access
Violation ^
IMCCTO ,
:
cout setwOO);
cout endl;
:
C++!
372.142
' , - - ,
setw(30) :
!
, ,
CyrOstream. ?
,
ios cout. ! ,
, CyrlOS.h ,
cout Cout? , ,
setwOO),
x_w1dth ios Cout!..
CyrOstream
cout.
, cout ,
, , endl.
. ,
iomanip iomanip.cpp. -
, , ,
SearchlOS.
mainO ( SearchlOS.) :
cout setwOO):
cout endl:


cout setwOO):
( ).

158

4.

,

bas1c_ostream<.>& operator( ... )

, -
tempiate<class _, class _Tr. class _Tni> Inline bas1c_ostream<_E, _Tr>& _cclecl
operator(bas1c_ostream<_E. _Tr>& _0. const _Smanip<_Tm>& _M) { ... }

, ,
! , -
, .
Task4_la.
CyrOstream ( CyrlOS.h)
:
friend CyrOstreamS operator (CyrOstream8(. const _Smanip<1nt>8():

CyrlOS.cpp ,
cout:
CyrOstream& operator (CyrOstreamS os,
const _Smanip<int>& m) {
cout m;
return os;
}

:
C++!
372.142
Press any key for continue.

To, ! !
. , ostream
string.
( SearchlOS),
,
-
tempiate<class _. class _Tr. class _A> inline
basic_ostreain<_E. _Tr>& __cdecl operator(basic_ostream<_E, _Tr>8i _0, const
basic_string<_E. _Tr. _A>& _X) { ... }.

string.

string, CyrOstream.h
-
tempiate<class _. class _Tr. class _A> inline
CyrOstream& operator (CyrOstream& os. const basic_string<_E. _Tr. _A>8( _X) { ... }

4.1. , /

1 59

, 1os ostream ,
, , CyrOstream.
, ,

.
:
/,
, . ,
:
friend ostream& operator

(ostream& out, MyClass& ob):

Cout CyrOstream,
' ' MyClass ostream
CyrOstream.
#clef1ne ostream CyrOstream :
#ifndef CYR_IOS_IMPLEMENTATION
#def1ne cout Cout
#def1ne ostream CyrOstream
#end1f

CyrOstream .
Task4_lb. Cyrlstream
.
IIIIIIIIIIIIII
III IIIIIIIIII
II Task4_lb
IIIIIIIIIIIIIIIlllllllllllllllnil
II CyrlOS.h
#1fndef CYR_IOS_H
#def1ne CYR_IOS_H

III III III II III 1111 III


II III II

IIIlllllllllllllll

#1nclude <1ostream>
#1nclude <1oman1p>
#include <str1ng>
#1nclude <w1ndows.h>
using namespace std;
#def1ne MAX_STR_LEN 4096
///////////////////////////////////////////////////////////
// CyrOstream
class CyrOstream : public ostream {
public:
CyrOstream(_Uninitialized no_init) : ostream(no_init) {}
CyrOstream& operator (_Myt& (_cdecl ^ _f)(_Myt&)):
CyrOstream& operator (ios_base& (___cdecl * _f)(ios_base& )):
CyrOstream& operator (short n) { cout n; return 4his; }
CyrOstream& o^erd^tor (unsigned short n) {
cout n: return 4his; }

1 60
CyrOstream&
CyrOstream&
cout
CyrOstream&
CyrOstream&
cout
CyrOstream&
CyrOstream&
CyrOstream&
cout
CyrOstream&
cout

4.
operator (int n) { cout n; return 4h1s; }
operator (unsigned int n) {
n: return 4h1s; }
operator (long n) { cout n: return 4h1s; }
operator (unsigned long n) {
n: return 4his; }
operator (float f) { cout f: return 4his; }
operator (double f) { cout f: return 4his; }
operator (long double f) {
f; return 4his: }
operator (const void* v) {
v; return 4his; }

CyrOstreani& operator (const char*);


CyrOstream& operator (const unsigned char* s) {
operator ((const char*)s); return *this; }
CyrOstream& operator (const signed char* s) {
operator ((const char*)s); return *this; }
CyrOstream& operator (char);
CyrOstream& operator (unsigned char);
CyrOstream& operator (signed char c) {
operator ((char)c); return *this; }
CyrOstream8i put(char);
CyrOstreain& write(const char*, int);
CyrOstream& write(const unsigned char* s. int len) {
write((const char*)s, len); return *this; }
// ios
long setfdong IFlags) { return cout.setf(lFlags); }
void unsetfdong IFlags) { cout.unsetf(lFlags); }
char fill (char cFill) { return cout.filKcFill); }
char fill { return cout.fillO; }
int precision(int np) { return cout.precision(np); }
int precisionO const { return cout.precisionO; }
int width(int nw) { return cout.width(nw); }
.int widthO const { return cout.widthO; }
int rdstateO const { return cout.rdstateO; }
long flagsO const { return cout.flagsO; }
long flags(long _1) { return cout.flags(_l); }
streambuf* rdbufO const { return cout.rdbufO; }
//
friend CyrOstream& operator (CyrOstreain&,
const _Smanip<int>&);
private:
char buf_[MAX_STR-LEN];
}:
////////////////////////////////
// string
tempiate<class _E, class Tr. class A> inline

4.1. , /

CyrOstream& operator (CyrOstream& os,


const basic_str1ng<_E. _Tr. _A>& _X) (
string temp(__X);

unsigned char symb[2];


symb[l] = 0;
for (int i = 0; i < temp.sizeO; i++) {
symb[0] = temp.at(i);
if (symb[0] > 191)
CharToOem((const char^)symb. (char*)syfnb);
cout symb;
}
return OS;
}
///////////////////////////////////////////////////////////
// Cyrlstream
class Cyrlstream : public istream {
public:
CyrIstream(_Uninitialized nojnit) : istreani(no_init) {}
Cyrlstream& operator (ios_base& (_cdecl * _f)(ios_base& )):
Cyrlstream& operator (char*);
Cyrlstream& operator (unsigned char* s) {
operator ((char*)s): return 4his: }
Cyrlstream& operator (signed char* s) {
operator ((char*)s); return 4his; }
Cyrlstream& operator (char& c);
Cyrlstream& operator (unsigned char8( c) {
operator ((char&)c); return 4his; }
Cyrlstream& operator (signed char& c) {
operator ((char&)c); return *this; }
Cyrlstream& operator
Cyrlstream& operator
cin n; return
Cyrlstream8( operator
Cyrlstream& operator
cin n; return
Cyrlstream& operator
Cyrlstream& operator
cin n; return
Cyrlstream& operator
CyrlstreamS operator
Cyrlstream& operator
cin f; return

(short& n) { cin n; return 4his: }


(unsigned short& n) {
*this; }
(int8( n) { cin n; return *this; }
(unsigned int& n) {
*this; }
(long& n) { cin n; return *this: }
(unsigned long8( n) {
*this: }
(float& f) { cin f; return *this: }
(double& f) { cin f; return *this: }
(long doubled f) {
*this; }

int getO { return cin.getO; }


Cyrlstream& get(char&);

161

I 62

4.

Cyrlstreani& get(char*. 1nt, char='\n');


Cyrlstream& get(uns1gned char^. 1nt, char ='\n'):
Cyrlstream& getl1ne(char*. 1nt. char='\n'):
Cyrlstream& getl1ne(uns1gned char^ pch. int nCount.
char delim ='\n') {
getline((char*)pch, nCount. delim): return nhis: }
Cyrlstream& read(char^. 1nt):
Cyrlstream8i read(uns1gned char^ pch. int nCount) {
read((char*)pch. nCount); return 4hl5; }
Cyrlstream& Ignorednt nCount = 1. 1nt delim = EOF) {
c1n.1gnore(nCount, delim); return 4his; }
int peek() { return cm.peekO; }
1nt gcountO const { return dn.gcountO; }
Cyrlstream& putback(char ch) { cln.putback(ch); return 4h1s; }
// ios
void cleardnt nState = 0) { cln.clear(nState); }
long setfdong IFlags) { return cin.setfdFlags); }
void unsetfdong IFlags) { dn.unsetfdFlags); }
int rdstateO const { return dn.rdstateO: }
long flags const { return d n d H a g s O ; }
streambuf^ rdbufO const { return cm.rdbufO; }
//
friend Cyrlstream& operator (CyrIstream&.
const _Smanip<int>&);
private:
char buf_[MAX_STR_LFN];
}:
lllllllllllllllllllllllllllllIII

II string
tempiate<class _E. class _Tr. class _A> inline
Cyrlstream& operator (CyrIstream8( is.
basic_string<_E. _Tr. _A>& _X) {
string temp;
cin temp;
unsigned int n = temp.sized;
char* buf = new char[n+l];
temp.copy(buf. n); buf[n] = 0;
OemToCharCbuf. (char*)buf);
_X = string(buf);
delete [] buf;
return is;
}

///////////////////////////////////////////////////////////
extern Cyrlstream Cin;
extern CyrOstream Cout;
#endif /* CYR_IOS_H */
#ifndef CYR_IOS_IMPLEMENTATION
#define cin Cin

4.1, , /

#def1ne cout Cout


#def1ne 1 stream Cyrlstream
#def1ne ostream CyrOstream
#end1f
// CyrlOS.h
///////////////////////////////////////////////////////////
// CyrlOS.cpp
#define CYR_IOS_IMPLEMENTATION
#1nclude "CyrlOS.h"
///////////////////////////////////////////////////////////
// CyrOstream
CyrOstream& CyrOstream:-.operator (
_Myt& (_cdecl "^ _f)(_Myt&)) {
cout f; return 4 h 1 s ;

CyrOstream& CyrOstream::operator (
1os_base& (_cdecl ^ _f)(1os_base& ))
cout f: return 4h1s;

CyrOstream& CyrOstream::operator (const char'^ s)


int n = strlen(s):
strhcpy(buf_, s. n): buf_[n] = 0:
CharToOem(buf_. buf_);
cout buf_:
return *th1s:

CyrOstream& CyrOstream::operator (char c) {


bufJO] = c; bufjl] = 0:
CharToOem(buf_. buf_):
cout buf_:
return 4 h 1 s :

CyrOstream& CyrOstream::operator (unsigned char c) {


unsigned char buf[2]:
buf[0] = c: bufCl] = 0;
If (c > 191)
CharToOem( (const char*)buf. (char'^)buf):
cout buf:
return 4 h 1 s ;

CyrOstream& CyrOstream::put(char c) {
buf_[0] = c: buf_[l] = 0:
CharToOem(buf . buf ):

163

164

4.

cout.put(buf_[0]):
return *th1s:

CyrOstreain& CyrOstream: :wr1te(const char* s, 1nt len) {


1nt n = strlen(s);
strncpy(buf_. s. n); buf_[n] = 0;
CharToOem(buf_. buf_):
cout.wr1te(buf_. len):
return 4h1s:
}
CyrOstream& operator (CyrOstream& os. const _Sman1p<1nt>& m)
cout m:
return os;
}

///////////////////////////////////////////////////////////
// Cyrlstream
Cyrlstream& Cyrlstream: :operator (
1os_base& (__cdecl * _f)(1os_base& )) {
c1n _f: return *th1s;
}
Cyrlstream& Cyrlstream::operator (char* s) {
string temp:
cin temp;
unsigned int n = temp.sizeO:
temp.copy(buf_. n); buf_[n] = 0;
OemToChar(buf_. buf_);
strncpy (s. buf_. n + 1);
return 4his;
Cyrlstream& Cyrlstream::operator (char& c)
cin buf_[0];
bufjl] = 0;
OemToChar(buf_. buf_):
= bufJO];
return *this;
Cyrlstream& Cyrlstream::get(char& symb) {
cin.get(buf_[0]);
bufjl] = 0;
OemToChar(buf_. buf_):
symb = buf_[0];
return *this;

Cyrlstream& Cyrlstream::get(char* pch. int nCount. char delim) {


cin.get(pch, nCount, delim);

4.1. , /

OemToCharCpch. pch);
return *th1s;

Cyrlstream& Cyrlstream::get(uns1gned char* pch,


int nCount. char delim) {
cin.get((char*)pch, nCount. delim);
OemToChar((const char^)pch. (char*)pch);
return 4 h i s ;

Cyrlstream& Cyrlstream;;getline(char* pch. int nCount. char delim) {


cin.getlineCpch. nCount, delim);
OemToCharCpch. pch);
return 4his;
}

CyrlstreamS Cyrlstream;;read(char* pch. int nCount) {


cin.read(buf_. nCount);
bufJnCount] = 0;
OemToChar(buf_. buf_);
for(int i = 0; i < nCount; i++)
pch[i] = buf_[i];
return 4his;

Cyrlstream& operator (CyrIstream& is. const _Smanip<int>& m) {


cin m; return is;
}
//////////////////////////////////////////////////////////
//
Cyrlstream Cin(_Noinit);
CyrOstream Cout(_Noinit);
// CyrlOS.cpp
///////////////////////////////////////////////////////////
// Task4_lc.cpp
#include "CyrlOS.h"
int mainO {
// CyrOstream
char str[] = "++!\n";
cout " ";
cout.put( ' ;
cout.write(str, strlen(str));
double = 372.141526;
cout.width(20);
cout endl;

1 65

166

4.

c o u t . f l l l C . );
cout.w1dth(20);
cout endl;
cout.precision(10);
cout.w1dth(20);
cout endl:
return 0:
//

Task4_lb


string, , ,
- string.
string -, ,
.
, (, OemToCharO)
string, ,
-.

, CyrOstream& operator (unsigned char), a


string CharToOemO
, , 191.
, ,
ANSI 128-191,
192-255.

ma1n() ,
CyrOstream. ^:
C++!
372.142
372.142
372.141526

Cyrlstream .

,
/ , ,
.

4.2.

,
100
( ) .
, -, ,
, .

4.2.

1 67

:
;
;
.
: ,
.
/
.
, , ,
,
DBase. DBase ( )
,
.
Man. ,
DBase has Man.
,
.
DBase. , :
.
\
Man. , DBase

Man, .
Man* .
, ImtlnpuK)
! SearchPayNotLess()
, .

ShowO, .
Man. ,
, :
char* pName , ;
1nt come_year ;
double pay .
,
. (
) GetPay(). , Man
,
In1tlnput() DBase,
, ShowO DBase.
.
.

168

4.

,
. -
,
. 1
.
;
.
Man:
1stream& operator (1stream& i n . Man& obj) {
//
in obj.come_year;
1n obj.pay;
return i n ;
}

in obj.come_year;
- ,
.
.
.
GetlntO
GetDoubleO,
. .
,
.
, ,
, DBase. h, DBase. , Man. h, Man. cpp,
GetFunc.h, GetFunc.cpp Main.cpp:
///////////////////////////////////////////////////////////
/ / Task4_2
///////////////////////////////////////////////////////////
/ / DBase.h
class DBase {
public:
DBasednt):
-DBaseO:
void I n i t l n p u t O :
void ShowO;

void SearchPayNotLess(double);
private:
Man* pMan;
int nRecords;
}:
///////////////////////////////////////////////////////////
// DBase.cpp
#include "Man.h"
#include "DBase.h"

4.2.

DBase::DBase(1nt nRec) : nRecords(nRec).


pManCnew Man[nRec]) {}
DBase:-DBaseO { 1f (pMan) delete [ ] pMan; }

void DBase::In1tInput() {
for (int 1 = 0; 1 < nRecords; 1++)
c1n *(pMan + 1 ) ;

III

void DBase::Show() {
cout "================================" endl:
cout " :" endl;
for (1nt 1 = 0; 1 < nRecords: 1++)
cout *(pMan + 1);
.
// 2
void DBase::SearchPayNotLess(double anyPay) {
bool not_found = true;
for (int 1 = 0; 1 < nRecords; 1++)
1f ((pMan + 1)->GetPay() >= anyPay) {
cout *(pMan + 1 ) ;
not_found = false;
}

if (not_found) cout " ." endl;


}
///////////////////////////////////////////////////////////
// Man.h
#include <iostream>
#1nclude <ioman1p>
using namespace std;
//finclude "CyrlOS.h"

/ / for Visual C++ 6.0

const int l_name = 30;


class Man {
public:
Man(int IName = 30);
-ManO;

double GetPayO const;


// ()
friend istreams operator (istream&, Man&);
// ()
friend ostream& operator (ostream&. Man&);
private:
char* pName;
int come_year;
double pay;
}:

1 69

1 70

4.

IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIII

II .
#1nclude "Man.h"
linclude "GetFunc.h"
Man::Man(1nt IName) { pName = new char[lName + 1]: }
Man::~Man() { if (pName) delete [] pName; }
double Man::GetPay() const { return pay; }
// ()
1stream& operator (1stream& in. Man& ob) {
cout "\ " endl:
cout " .. <Enter> <Enter>":
cout " <Enter>:" endl;
1n.getl1ne(ob.pName. l_name);
ob.come_year = Getlntdn):
// 3
ob.pay = GetDoubledn);
// 4
return in;
}

// ()
ostream& operator (ostreani& out, Man& ob) {
out setw(30) setiosflagsdos: :left);
out ob.pName " ";
out ob.come_year " ";
out ob.pay endl;
return out;
}
///////////////////////////////////////////////////////////
// GetFunc.h
1nt Getlnt(1stream&);
//
double GetDouble(istream8i);
//
///////////////////////////////////////////////////////////
// GetFunc.cpp
#include "Man.h"
#include "GetFunc.h"
//

1nt Getlnt(1stream& 1n) {
1nt value;
while (true) {
in value;
// 5
if (in.peekO == '\n') {
// 6
in.getO:
// 7
break;
}
else {
cout " ( ):
endl;
// 8

4.2.

in.clearO:
while (in.getO != ' ) { } :

171

// 9
/ / 10

}
}
return value;
}

//

double GetDouble(1streani& in) {
double value;
while (true) {
in value;
if (in.peekO == '\n') {
in.getO;
break;
}
else {
cout " ( ):" endl;
in.clearO;
while (in.getO != '\n') {};
return value;
}
///////////////////////////////////////////////////////////
// Main.cpp
#include "Man.h"
#include "DBase.h"
#include "GetFunc.h"
int mainO {
const int nRecord = 1 0 ;
double any_pay;
DBase dBase(nRecord);
dBase.InitlnputO;
dBase. ShowO;
cout
cout
cout
cout

" ." endl;


"=================================================" endl;
" , ." endl:
" -1." endl:

while (true) {
cout "\ -1: ";
_ = GetDouble(cin);
if (any_pay == -1) break;
dBase.SearchPayNotLess(any_pay);
}
return 0;
}
///////////////////////////////////////////////////////////

172

4.

.
ImtlnputO Man
, ^( + 1),
, + 1 ( 1).

Show() 2.
( .)
3 4, Get I n t o
GetDouble(),
.
GetlntO GetDoubleO GetFunc.cpp.
.
while .
5.
streambuf, 1,
, '\',
' \ ' . 6
, (). 1 ,
7 ' \',
wh11 val .

, :
8 , ;
in ( 9);
while
, '\' ( 10). while
.
GetDoubleO .
maInO ( Maln.cpp) .

.
, 1 1.1
^
, ,
. ma1n():
Maln.cpp Taskl_l Task4_2
,
.
.
1.
. C++ : 1.1
, 4.2 .

2.

3.
4.
5.

6.

173

, ^ -
, .
- .
-
, .

.

.

. /
, get clear.

,
.

1
1. STUDENT, :
;
;
( ).
PI
STUDENT.
2. , :
,
STUDENT;
;
,
, 4.0;
, .

2
1. STUDENT, :
;
;
( ).

174

4.


STUDENT.
2. , :
,
STUDENT;
;
,
4 5;
, .

3
1. STUDENT, :
;
;
( ).

STUDENT.
2. , :
,
STUDENT; ;
,
2;
, .

4
1. AEROFLOT, :
;
;
.

AEROFLOT.
2. , :
,
AEROFLOT;
;
,
, ,
;
, ;

175

5
1. AEROFLOT, :
;
;
.

AEROFLOT.
2. , :
,
AEROFLOT;
;
,
, ;
, .

6
1. WORKER, :
;
;
.

WORKER.
2. , :
,
WORKER; ;
,
, ;
, .

7
1. TRAIN, :
;
;
.

TRAIN.
2. , :
,
TRAIN;
;

176

4.

,
;
, .

8
1. TRAIN, :
;
;
.

TRAIN.
2. , :
,
TRAIN;
;
, ,
;
, .

9
1. TRAIN, :
;
;
.

TRAIN.
2. , :
,
TRAIN; ;
,
;
, .

10
1. MARSH, :
;
;
.

177


MARSH.
2. , :
,
MARSH; ;
,
;
,
.

11
1. MARSH, :
;
;
.

MARSH.
2. , :
,
MARSH; ;
,
, ;
,
.

12
1. NOTE, :
, ;
;
( ).

NOTE.
2. , :
,
NOTE; ;
,
;
, .

178

4.

13
1. NOTE, :
, ;
;
( ).

NOTE.
2. , :
,
NOTE; ;
,
, ;
, .

14
1. NOTE, :
, ;
;
( ).

NOTE.
2. , :
,
NOTE;
;
, ;
, .

15
1. ZNAK, :
, ;
;
( ).

ZNAK.
2. , :
,
ZNAK; ;

179

, ;
, .

16
1. ZNAK, :
, ;
;
( 13 ).

ZNAK.
2. , :
,
ZNAK; ;
, ,
;
, .

17
1. ZNAK, :
, ;
;
( ).

ZNAK.
2. , :
,
ZNAK; ;
, ,
;
, 11 .

18
1. PRICE, :
;
, ;
.

PRICE.

180

4.

2. , :
,
PRICE;
;
,
;
, ! .

19
1. PRICE, :
;
, ;
CTOPiMOCTb .

PRICE.
2. , :
, 13
PRICE;
;
, ,
;
, .

20
1. ORDER, :
;
;
.

ORDER.
2. , :
,
ORDER;
;
,
, ;
,
.

5

.
string
: . 280-294.


C++
, . 5.1.
5 . 1 .

1fStream

bas1c_1fstream

bas1c__1 stream

ofstream

bas1c_ofstream

bas1c__ostream

fstream

basic fstream

basic iostream

1 stream,
ostream Iostream ,
, , ,
. . , ,
/,
, FILE*.

<fstream>.

182

5. . string

( );

(/);

,
.
,
:
1fstreani(const char^ name. 1nt mode = 1os: 1n):
ofstreamCconst char* name, 1nt mode = ios: out I 1os:itrunc);
fstreamCconst char* name. 1nt mode = 1os::in | 1os::out);

.
, ,
( |) . 5.2.
5.2. mode

lOS:

in

1os: out
1os: ate
1os: app
ios: trunc
10S:

binary

1os: nocreate^
ios: noreplace^


71


,
(
)
, ] (
)
,

,
.
open , ,
.

:
//
ofstream flogC'flog.txt");
ofstream foutl. fout2;
.

183

foutl.openC'testl". 1os::app);
fout2.open("test2", 1os::binary);
//
1f St ream flnplC'data.txt");
/ /
fstream myfile;
myf1le.open("mf.dat");

name (
), , ,
, :
ifstream f1npl("D:\\VCwork\\Taskl\\data.txt"):

- (,

),
() , .
, , :
ifstream finplC'data.txt");
i f (Ifinpl) {

cerr " data.txt ." endl:


throw " ":

, :
, 1,
~ , cout.
,
.
eof , ,
, ^
/
, ,
.
,
.
,
.
, .
, closeO.
, C++
] ,
.

184

5. . string

.
:
/ / .
#1nclude <1ostream>
#1nclude <fstream>
using namespace std:
void errorCconst char* t e x t l . const char* text2 = "") {
cerr t e x t l ' ' text2 endl;
exitd):

i n t maindnt argc, char* argv[]) {


i f (argc != 3) error(" ");
ifstream from(argv[l]); / /
i f (!from) error(" :". a r g v [ l ] ) ;
ofstream to(argv[2]); / /
i f (!to) error(" :". argv[2]);

char ch;
while (from.getCch)) {
to.put(ch);
if (!to) (" ( ).");
}
cout " " argv[l] " " argv[2] " ." endl;
return 0;
}


( ):
// .
#include <iostream>
#include <fstream>
using namespace std;
// error - .
// ...
int main(int argc. char^ argv[]) {
if (argc != 2) error(" );
ifstream tfile(argv[l]); //
if (Itfile) error(" :". argv[l]);
char buf[1024];

1 85

while ( I t f i l e . e o f O ) {
tf1le.getl1ne(buf. slzeof(buf)):
cout buf endl:

}
return 0:
}

,
1024 .
buf .


! Istringstream, ostringstream
stringstream, istream, ostream
iostream .
<sstream>.
.
,
, . ,
strO, string
:
string s t r O const;
void str(const string& s);

sscanfO sprintfO
, ,
/. , sprintf ()
, .
ostringstream.

, ,
Line N:, / N :
/ / AdvType.cpp
#include <iostream>
#include <iomanip>
^include <fstream>
#include <sstream>
using namespace std;
/ / error - .
// ...
int main(int argc, char* argv[]) {
i f (argc != 2) error(" .");

186

5. . string

ifstream t f 1 l e ( a r g v [ l ] ) ;
i f ( I t f i l e ) error(" :". a r g v [ l ] ) ;
1nt n = 0:
char buf[1024]:
while ( ! t f 1 l e . e o f ( ) ) {
n++:
tfile.getl1ne(buf, slzeof(buf));
ostringstream l i n e ;
line "Line " setwO) n
cout l l n e . s t r O :

": " buf

endl;

}
return 0:

string
string
,
-^ string
.
string^
,
, ,
. , new
delete,
.
, string
, , -.
: string -
. ,
, , ,
. . C++ string
,
.
string,
<str1ng>.
string
. , std s1ze_type, ' char, .
^ str1 ng bas1 c_str1 ng
typedef bas1c_str1ng<char> string:.

187

string

unsigned Int. string


npos, ,
, .
OxFFFF...FFFF,
Int - 1 .
string 1 .
^*
stringO;

/ / ' string

str1ng(const char*); / / , -

:
str1ng& operator=(const str1ng8( s t r ) ;
str1ng& operator=(const char* s); / / -
str1ng& operator=(char ):
/ /

. 5.3 string .
5.3. string

>

>=

=
+
!=

[]

<

+=

<=

.
, .

at(s1ze_type ), ,
- s^:
cout s.at(2);
s.at(5) = 'W;

/ / 2-
/ / 5- 11

, .
atO, , ,
, out_of_range.
. 5.4
string.
^ string . ( ).
^ .

188

5. . string

5.4. [ string

size_type size const:

s1ze_typG length const;

To , size

1nsert(size_type posl. const str1ng&


str);

str ,
posl

replace(s1ze_type posl. s1ze_type nl.


const str1ng& str):

1 , posl
, str

string substr(s1ze_type pos=0.


s1ze_type n=npos) const:

,
pos

s1ze_type f1nd(const str1ng& str.


s1ze_type pos=0) const:

str
,
pos. ,
npos,

s1ze_type find(char c, s1ze_type


pos=0) const:

,
pos.
npos,

s1ze_type rf1nd(const str1ng& str.


s1ze_type pos=0) const:

str,
pos^

s1ze_type rf1nd(char c. s1ze_type


pos=0) const:

71 ,
pos^

s1ze_type f1nd_f1rst_of(const string^


str. s1ze_type pos=0) const:


str, pos^

s1ze_type f1ndJast_of(const string&


str. s1ze_type pos=0) const:


str, pos^

swap(str1ng& str):


str

erase(s1ze_type pos=0.
size_type n=npos):

, pes

const char* s t r O const:

-,
.
-

s1ze_type copy(char'^ s. s1ze_type n.


s1ze_type pos=0) const:

s
, pos.
-
.

find . ,
,

, findO.

5.1.

189

. , ,
: , , , D, , F, G, .
, .
, .
:
char GetColumnO {
string goodChar = "ABCDEFGH";
char symb;

cout " : ";


while (1) {
cin symb:
if (-1 == goodChar.find(symb)) {
cout ". :\n":
continue:
}
return symb:
}

1
, find ,
,
goodChar.
.

5 . 1 .

, ,
. , .
^.
-
, ^, .
,
' \ t ' ' \ ' .
( )
word string.
,
, ,
curvvord string. ,
string ,
, curword,
.
^ ( 5.2),
: 80 .
^ : , , , .

190

5. . string

,
.

bool equal(const str1ng& cw. const str1ng& w):

true, cw
W , false .
, :
;
w ( ),
count.
:
/ / Main.cpp

#include <fstream>
#1nclucle <str1ng>
#1nclude "CyrlOS.h" // for Visual C++ 6.0^
using namespace std;
bool equal(const str1ng& cw. const strings w) {
char punctC] = {'.'. ','. '?', '!'};
If (cw == w) return true:
for (Int 1=0; 1 < slzeof(punct); ++1)
If (cw == w + punct[1]) return true:
return false;

Int maInO {
string word, curword:
cout " : ";
cin word;
Ifstream fInC'Inflle.txt", 1os: :1n|1os: :nocreate);
If (!f1n) { cout " ." endl; return 1;
Int count = 0;
while (Ifln.eofO) {
fin curword;
I f (equal(curword. word)) count++;
}
cout " : " count
return 0;

endl;

^ 1, 1.1
/ .

5.2.

191

equal , ,
w
.

5.2.

,
^.
, ,
. ,

.
, .

, .
, C++,
.
, ,
word string,
sentence ostrlngstream, , ,
.
, , ,
f 1 word. ,
fin .
- sentence
fin, seekgO.
- isLimitO.
:
, '.', '!', '?';
, cout,
sentence .
:
#include <fstreani>
#1nclude <s^/b^eam>
#1nclude <stnng>
#1nclude "CyrlOS.h" / / for Visual C++ 6.0
using namespace std;
bool 1sL1m1t(char c) {
char I1m[] = {' ' . ' \ t " .

'\n'};

( 5.3).

192

5. . string

for (1nt 1 = 0: 1 < s1zeof(l1m); ++1)


if ( == I1m[1]) return true;
return false:

1nt mainO {
Ifstream f1n("inf1le.txt". 1os::1n|1os::nocreate):
if (!f1n) { cout " ." endl: return 1:
int count = 0 :
string word:
ostringstream sentence;
whiledfin.eofO) {
char symb:
while(isLiniit(symb = fin.peekO)) {
sentence symb:
if (symb == '\n') break:
fin.seekgd, ios: :cur);

fin word:
sentence word:
char last = word[word.size() - 1]:
if ((last '.') II (last == '!')) {
sentence.str(""): //
continue:
}
if (last == '?) {
cout sentence.strO:
sentence.str(""):
count++:
if (!count) cout " .":
cout endl:
return 0:
}

. He
i nfi 1 . txt.
.
1. C++
ifstream, of stream, f stream.
2. : ,
, (/),
.
3. , .

193

4. / ,
, .
5. ,
.
6. istrlngstream, ostringstream, strlngstream
.
. ,
, .
7. string C++
.
, .

1
,
.

2
,
, .

3
,
, .

4
,
, .

5
, ,
.

6
, 1
, .

194

5. . string

7
, ,
, .

8
,
, , .

9
,
, .

10
,
,
.

11
,
, .

12
,
, ,
.

13
,
, ,
, .

14
, ,
9 , , ..., ,
.

15
, ,
, .

195

16
,
, .

17
, ,
,
.

18
,
.

19
,
, , .

20
,
, .

: . 295-368.

STL
STL^ :
.
, .
,
, .
. ;
,
.
, , , . .
,
, , , . .
. ,
STL .
:
, .
:
, first, last,
.

. Standard Template Library.

STL

1 97

: . ,
, ,
.

STL :
.

.
(vector), (list)
(deque). (
), (stack), (queue)
(priority_queue).
, C++
. ,
,
, .
( new), -
.

, 2.

. , ,
, :
vector<1nt> aVect;
11st<Man> department:

/ / aVect ( Int)
/ / department Man

.
.
: ! (),
(multlmap), (set), (multiset)
(bUset).

, , ,
value ,
. , :
template <class > * F1nd(T* ^, 1nt . const 8( value) {
for d n t 1 = 0: 1 < : ++1)
1f (ar[1] == value) return &ar[1]:
return 0;

198

6.

,
. for :
for ( i n t 1 = 0; 1 < : ++1)
i f ('^(ar + 1) == value) return ar + 1;

. ,
,
,
,
.
,
,
! , , :
,
.
,
.
STL ,
, , .
STL Iterator,
. , vect,
, , typedef
* iterator. list
iterator, .
, , :
: , * ,
.
.
(== !=).

(++) (++) .
,

_::, :
vector<int>:[iterator i t e r l ;
1i st<Man>::i terator i t e r 2 :


. , i ,
for (i = 0 : i < n; ++i)

:
for (i = f i r s t ; i != last: ++i)

STL

1 99

f 1 rst , ,
last , ,
. <
!=, < >
.
begInO
endO, first last .
, STL :
, , ,
.
(Inputlterator) STL
, ,
Gin.
(Outputlterator)
, ,
cout.
(Forwardlterator)
, ,
.
{Bidirectionallterator)
, ,
(
).
{RandomAccessIterator)
( )
.
,
,
( ,
1).
, , ,
.
FindO,
. STL
:
template <class Inputlterator. class >
Inputlterator findCInputlterator f i r s t . Inputlterator last, const T& value):


, . ,
, reverse_iterator.
- .

200

6.


. 6.1 , typedef
.
6 . 1 . , STL

value_type
s1ze_type^
iterator
constiterator
reference
constreference
keytype
key_compare


, . .

( )

(
)
( )
( )

. 6.2 .
6.2. ,

(==)
(! =)
(=)
clear
insert
erase
s1ze_type s1ze() const
s1ze_type max_s1ze() const
bool emptyO const
iterator beginO

true false






true,
(
)

iterator end

(
)

reverse_iterator beginO


( )

reverse iterator endO


( )

unsigned int.

STL

201

,
(). ,
<algor1thni>.
. 6.3 STL^
6.3. STL

accumulate

count

count_1 f

equal

f 111

f 1 nd

f1nd_f1rst_of

f 1 nd_i f

for_each

merge

remove

replace

search

sort

swap

transform


[ f i r s t , last)^, f i r s t
, , l a s t ,
.
,
int arr[7] = {15. 2. 19. -3. 28. 6. 8};
sort:
sort(arr. arr + 7);
^ . .
2 [. ) , , b
.

202

6.

int"^ .
.

(vector), ( l i s t )
^ (deque).
,
:
#1nclucie <vector>
#1nclude <l1st>
#1nclude <deque>
using namespace std;

, ,
.

[] at^
, , .
.
, .
.
: ,
.
.
: ,
- -1 .
{) ,
.
( ,
).
.
1. :
vector<1nt> vecl;
I1st<str1ng> U s t l :

2.
:
vector<str1ng> vecl(lOO):
l1st<double> listl(20);
at ,
, ,
out_of_range.

203

3.
:
vector<str1ng> vecKlOO. "Hello!");
deque<1nt> declOOO. -1);

4.
[first, last) :
1nt [7] = {15. 2. 19. -3. 28, 6. 8}:
vector<1nt> v K a r r . + 7);
I1st<int> lst(vl.beg() + 2. v l . e n d ( ) ) ; i

'

5.
:
vector<1nt> v l ;
/ / v l
vector<1nt> v2(vl);

6.
push_back() _().
, ( )
push_front() pop_front(). ,
_() pop_f ront() .
, front ,
back .
,
, . 6.4.
6.4. insert() erase()

Insertdterator position,
const & value)
Insertdterator position.
size_type n. const T& value)
template <class Inputlter>
void insert(iterator position.
Inputlter f i r s t . Inputlter last)

value ,
position
value,
position
,
first last,
position

erase(iterator position)

,
position

eraseCiterator f i r s t ,
iterator last)

,
first last

, Microsoft Visual C++ .


,

deque<int> dec(vl.beg(). vl.endO)

204

6.

6 . 1 .
.
.
,
:
#1nclude <1ostreaiTi>
#1nclude <fstream>
#1nclude <vector>
#include <algor1thm>
using namespace std;

1nt ma1n() {
ifStream in ("inpnum.txt"):
if (!in) { cerr "File not found\n": exit(l); }
vector<int> v;
int x;
while (in x) v.push_bacl<(x):
sortCv.beginO. v.endO);
vector<int>::const_iterator i :
for ( i = v.beginO; i != v.endO: ++i)
cout * i " ";
return 0;
}


vector deque list.
,
.
,
swapO, emptyO, backO, pop_back():
#include <iostream>
#include <vector>
using namespace std:

int mainO {
double arr[] = {1.1. 2.2. 3.3. 4.4 };
int n = sizeof(arr)/sizeof(double):
//
vector<double> vKarr. arr + n);
vector<double> v2: //
vl.swap(v2): // vl v2
while (!v2.empty()) {
cout v2.back() ' ': //

6.1.

v2.pop_back();

205

//

}
return 0:
}

:
4.4 3.3 2.2 1.1

print()

, ,
. ,
:
template <cldss > void pr1nt(T& cont) {
typename T: :constJterator p = cont.beginO:
1f (cont.emptyO)
cout "Container is empty.";
for (p; p != cont.endO: ++p)
cout *p ' ' ;
cout endl;
}

typename,
. , STL , ::iterator
, C++ .
typename '^ .
print ,
, , , :
#include <iostream>
#include <deque>
using namespace std;
/* ... print ... */
int mainO {
deque<int> dec;
print(dec); // Container is empty
dec.push_back(4): print(dec): / / 4
dec.push_frent(3);
dec.push_back(5):
dec.push_front(2);
dec.push_back(6):
dec.push_front(l):
return 0;

print(dec): / / 3 4
print(dec); / / 3 4 5
print(dec): / / 2 3 4 5
print(dec); / / 2 3 4 5 6
print(dec); / / 1 2 3 4 5 6

Microsoft Visual C++ 6.0 typename


.

206

6.


-- ,
,
,
.

stack ( <stack>)
template <class . class Container = cleque<T> >
class stack { / * ... * / }:

Container -.
deque. ,
-,
, . . 6.5
, stack -.
6.5. stack

stack

pushO

push_back()

pop

pop_back()

topO

backO

empty

empty

sIzeO

sizeO


,
,
. , () .
, topO.

^:
i n t mainO {
ifstream in

("inpnum.txt");

stack<int> s;
int x;
while (in x) s.push(x);
while (Is.emptyO) {
cout s.topO
s.popO:

' ':

#include using
namespace std, , .

6.1.

207

r e t u r n 0;

stacl1nt> s (
). -
, :
stack<1nt. I1st<1nt> > s;^

queue ( <queue>) ,
(
) . vector - ,
.
, .
, . 6.6.
6.6. queue

queue

pushO

push_back()

pop

pop_front()

front

front

backO

backO

empty

empty

sizeO

s1ze()


priority_queue ( <queue>)
, queue,
( ), .
,
.

. ,
, <.
:
i n t mainO {
p r i o r i t y _ q u e u e < i n t > P;
P.push(17); P.push(5): P.push(400):
P.push(2500); P . p u s h ( l ) ;
while (IP.emptyO) {
cout P.topO ' ' ;
P.popO:

He > > !

208

6.

return 0;

:
2500 400 17 5 1


.
<algor1thm> print , .

count find
count ( )
, . f 1 nd
.
, ,
end(). .
1nt mainO {
1nt drrl] = {1. 2. 3. 4. 5. 2. 6. 2. 7};
int n = slzeof(arr) / sizeofdnt);
vector<1nt> vKarr. arr + n);
int value = 2 ;
//
int how_much = count(vl.beg1n(), vl.endO, value):
cout how_much endl; // : 3
I1st<1nt> loc_l1st:
//
vector<1nt>: :1terator location = vl.beginO:
while (1) {
location = finddocation. vl.endO. value):
if (location == vl.endO) break:
1 oc_liSt.push_back(location - vl.beginO):
location++:
}
print(loc_list):
return 0:

/ / : 1 5 7

vl,
. count
value, . while
, .
, find ( location)
,
^ . location
, .
, , .

6.1.

209

, , -,
location
l o c l i s t . -, location
,
( )
. , break
.

countjf findjf
count_1f f1nci_1f count find ,
.
, bool.
,

bool I'sMyValuednt ) { return (( > 2) && ( < 5)); }

count
1nt how_much = count_1f(vl.begin(), vl.endO, isMyValue):

TO , ,
, .
, f 1 nd
location = f i n d j f (location. vl.endO .isMyValue);

l o c l i s t : 2 3
( vl, , isMyValue).

for__each

[fist. last). ,
, 1
( , ).
, .
.
, for_each
.
void InchToCmCdouble inch) {
cout (inch * 2.54) ' ' ;
}
i n t mainO {
double inchesC] = {0.5, 1.0. 1.5. 2.0. 2.5};
for_each(inches, inches + 5, InchToCm):
return 0:
}

210

6.

search
.
search,
[firstl. lastl) [f1rst2. Iast2). :
i n t iTiainO {

int [] = {11. 77. 33. 11. 22. 33. 11. 22. 55};
1nt pattern[] = { 11. 22. 33 };
1nt* ptr = search(arr, + 9, pattern, pattern + 3);
if (ptr == arr + 9)
cout "Pattern not found" endl:
else
cout "Found at position " (ptr - arr) endl:
I1st<1nt> lst(arr. arr + 9):
11st<i nt>::1terator 1 found:
ifound = searchdst.beginO. Ist.endO. pattern, pattern + 3):
if (ifound == Ist.endO)
cout

"Pattern not found"

endl:

else

cout "Found." endl:


return 0:
}
:
Found at position 3
Found.

,
+ - .
pattern
1st.

sort
.
,
, , ,
. 1 ist sort(),
.
sort :
tempiate<class RandomAccessIt> void sort(RandomAccessIt f i r s t . RandomAccessIt last):
tempiate<class RandomAccessIt> void sort(RandomAccessIt f i r s t . RandomAccessIt last.
Compare comp):

[first,
last), <,

6.1.

211

^. ,
. :
1nt mainO {
double [] = {2.2. 0.0, 4.4, 1.1. 3.3, 1.1};
vector<double> v K a r r . + 6);
sort(vl.beg1n(), vl.endO);
pr1nt(vl):
return 0;
}

:
1.1 1.1 2.2 3.3 4.4
sort
.
, ,
bool.
^. .


3 ,
,
. ,
operatorO.

, C++.
bool, (. 6.7).
6.7.

( )
equal_to

!=

not_equal_to

>

greater

<

less

>=

greater_equal

<=

less_equal

, , : equal_to<1nt>().
, sort
vl. sort :
sort(vl.beg1n(). vl.endO. greater<double>()):

* , .
^ . count_1 f f 1 nd_1 f.

212

6.

.
,
.
,
, ( ) ,
sort.
sort
men, Man. Man
operator<(),
name. ,
Less Age,
age.
class Man {
public:
Man (string _name, int _age) :
name(_name). age(_age) {}
// ,
bool operator< (const Man& m) const {
return name < m.name;
}
friend ostream& operator (ostream&. const Man8i):
friend struct LessAge;
private:
string name;
int age;
}:
ostream& operator(ostream& os. const ManS m) {
return OS endl m.name ",\t age: " m.age;
}

//
struct LessAge {
bool operatorO (const Man& a. const Man8( b) {
return a.age < b.age;
}

}:
int mainO {
Man dvl] = {
ManC'Mary Poppins". 36),
Man("Count Basie". 70),
ManC'Duke Ellington". 90).
Man("Joy Amore". 18)
}:
int size = sizeof(ar) / sizeof(Man);
vector<Man> men(ar. ar + size);

6.1.

213

/ / ( )
sort(men.beg1n(). men.endO);
print(men);

//
sortCmen.beginO. men.endO. LessAgeO);
prlnt(men):
return 0:


(reverse_1terator)
. ,
vector<double> vl,
:
vector<double>::reverse_1terator r 1 :
r1 = vl.rbeginO:
while ( r i != vl.rendO)
cout ^r1++ ' ' :

,
.



, , , , , :
1nt mainO {

int [4] = {10. 20. 30. 40};


vector<1nt> v(a. a + 4);
I1st<1nt> L(4):
/ / 4
copy(v.beg1n(), v.endO, L.beginO);
print(L);
return 0:
}

copy , ,
. , 1 - - 1 -
-^ / ,
.
front_1nserter(), backJnserterO, inserterO
,
.
.

214

6.

.
int malnO {

int [4] = {40. 30. 20. 10}:


vector<1nt> va(a. a + 4):
int b[3] = {80. 90. 100};
vector<1nt> vb(b. b + 3);
int c[3] = {50. 60. 70}:
vector<1nt> vc(c. + 3):
list<1nt> L:

//

copy(va.begin(). va.endO.
printd):
copy(vb.beg1n(), vb.endO.
pr1nt(L):
I1st<1nt>::iterator from =
advanceCfrom. 4):
copy(vc.begin(). vc.endO.
printd):
return 0:

front_inserter(L)):
back_1nserter(L)):
L.beginO;
i n s e r t e r d . from)):

:
10 20 30 40
10 20 30 40 80 90 100
10 20 30 40 50 60 70 80 90 100
:
() va
L, front_inserter
va
.
vb L
back_inserter,
.
vc from
L, .
from,
, 4 advanceO.

merge
merge
,
. ,
b :

215

1nt ma1n() {
int arr[5] = {2. 3. 8. 20. 25}:
vector<1nt> a(arr. + 5);
int b[6] = (7. 9. 23. 28. 30. 33};
list<int> c;
//
merge(a.beg1n(). a.endO. b, b + 6. back_1nserter(c));
pr1nt(c);
return 0;
}

:
2 3 7 8 9 20 23 25 28 30 33


. ,
. ,
.
STL:
(set) , ,
. ,
Man,
name. ,
int, .
() ,
, ,
, .
3.1 ( ).
, (
). (multiset)
(multlmap) ,
.

. ,
.

:
, :
C++ ,
.

216

6.

template <class Key, class Compare = less<Key> >


class set{ / * ... V };

, set<int> si
,
less<1nt>.
set<MyClass> s2, MyClass
operator<().
set
<set>.
set:
set<1nt>
1nt [5]
set<1nt>'
set<1nt>

setl;
/ /
= { 1. 2. 3. 4. 5 }:
set2(a. + 5):
/ /
set3(set2):
/ /

Insert ,
erase .
, . 6.2.
count ,
. ,
, count ,
, 1.
,
, - .
.
includes !
. true ,
[first2. Iast2) [firstl. lastl).
set_1ntersect1on ,
, ,
, .
set_un1on ,
,
.
:
1nt ma1n() {
const i n t N = 5:

string sl[N] = {"Bill", "Jessica". "Ben". "Mary". "Monica"};


string s2[N] = {"Sju". "Monica"."John"."Bill"."Sju"};
typedef set<string> SetS;
Sets A(sl. si + N):
Sets B(s2. s2 + N);
print(A); print(B);

217

Sets prod, sum:


set_1ntersect1on(A.beg1n(). A.endO. B.beginO. B.endO.
1nserter(prod. prod.begInO)):
prlnt(prod);
set_un1on(A.beg1n(). A.endO, B.beginO. B.endO.
inserter(sum. sum.beginO));
prlnt(sum);
if (includes(A.begin(). A.endO. prod.beginO. prod.endO))
cout "Yes" end!;
else cout "No" endl;
return 0;
}

:
Ben B i n Jessica Mary Monica
B i l l John Monica Sju
B i l l Monica
Ben B i l l Jessica John Mary Monica Sju
Yes

Microsoft Visual C++ 6.0,


fpragma
warning (disable:4786),
255 ^

pair,
<utility> :
template <class T l , class 2> struct pair{
Tl f i r s t ;
T2 second:
pair(const T1& X. const T2& y ) :

1, Visual C++ 6.0


, paccMOTpeiuioro
86 (!) , 1 11:
warning 4786: 'std::_Tree<std::hasic_string<char, std::char_traits<char>,
std::allocato7'<char> >, std::basic_stnng<char, std::char_traits<char>, std::allocator<char> >,
std::set<std::basic_stnng<char, std::char_traits<char>, std::allocato?'<char> >,
std::less<std::hasic_stnng<char, std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::hasic_stnng<char, std::charjraits<char>, std::allocator<char> > > >::_Kfn,
std::less<std:-.basic_stnng<char, std::char_traits<char>, std::allocator<char> > >,
std::allocator<std::basic_stnng<chai% std::char_traits<char>, std::allocator<char> > > >':
identifier was tiiAncated to '255' characters in the debug infotmation

218

6.

1 , .
f 1 rst, second.
==, !=, <, >, <=, >= pair.
: ,
, :
template <class Key. class . class Compare = less<Key> >
class map {
public:
typedef pair <const Key. T> value_type:
e x p l i c i t map(const Compared comp = CompareO):
map(const value_type* f i r s t , const value_type* last.
const Compare& comp = CompareO):
mapCconst map <Key. T. Compare>& x):

, value_type
Key .
.
, [f i rst. 1 ast).
.
[]:
& operator[](const Key & ):

,
.

<>.

6.2.


. prose. txt,
freq_map.txt.
#include <iostream>
#include <fstream>
#include <iomanip>
#include <map>
#include <set>
#include <string>
using namespace std:
int mainO {
char punct[6] = { ' . ' .

'.'.

'?'. '!'.

':'.

':'}:

6.2.

219

set<char> punctuat1on(punct, punct + 6);


ifstream i n ( " p r o s e . t x t " ) ;

if (!1n) { cerr "File not found\n"; exitd); }


map<str1ng. 1nt> wordCount:
string s;
while (in s) {
int n = s.sizeO:
if (punctuation.count(s[n - 1]))
s.erase(n - 1. n):
++wordCount[s]:
}
ofstream out("freq_map.txt"):
map<str1ng, 1nt>::const_iterator i t = wordCount.beginO:
for ( i t ; i t != wordCount.endO; ++1t)
out setw(20) l e f t i t - > f i r s t
setw(4) right it->second endl;
return 0:
}

wordCount map<str1ng. int>,



.
while :
s .
s.
count ,
s punctuation, ,
. ,
( eraseO).
++wordCount[s].
wordCount,
. wordCount[s]
, ,
s .
. ,
? ,
int ,
. ,
.
wordCount,
freq_map.txt
.
,
. , ,
map- , pai ,
map-. pai ,

220

6.

it
1t->f1rst, 1t->second.
, ,
, , ,
, STL.

6.3.
,
: . 7 :
) ; )
.
, , .

: , 10x10 .

10 : (
), ( ), ( ),
( ).
( ).

,
.

.

(1, 5 . .). ,
, :

;
()
();
, (
) .

, .
,
( ,
1).

,

. ,
, . 6.1.

..
,

221

6.3.

^ . ()
, ,
, X ?1 () .
,
.
.

..--^

^C:^VCwtc\Tjd<$ltllSii
31. '
F6
; ! -
: ^.. -

i 2 3 4 5 6 7 8 9

.
.
D .

F .
G .

I .
J .

:|
.

.
. .

19

/! |51
1 2 3 4 5 6 7 8 9 1
fi
.. --. .
X
. .
X
.. . . . .
D X
.

. . ..
F . ...X ... .
G . . . . .....
... ... . .

'/.. :

. 6 . 1 . i-ro (i = 31)

! ,
, , / .
, : (User),
, (Robot).
: UserNavy (
) Robot Navy ( ). ,
, FlreOffO ( )
,

,
. , , ,
( ), . .
( ) Navy,
UserNavy RobotNavy.
, Ship,
,
, , ,
.

Rect,
. , ^,
^ 176 86 (MS DOS).
^ .

222

6.

,
^
( ) (
),
Cell.
, (
, ).
Space,
, ,
Navy.
. 6.2 ,
.
Space
+$u_fire: Cell
+$r_fire: Cell
+$u_state: CurrentState
+$r_state: CurrentState

Navy
#ship[10]:Ship
#ownField: Field
#enem yField: Field
+AllocShlp(indShip: int, nDeck: int, name: std::strlng)
+Show()

10

UserNavy

RobotNavy

+Allocation()
+FireOff()
+ResultAnalys()
+GetFire()

+Allocation()
+FireOff()
+ResultAnalys()
+GetFire()

Ship
#place: Rect
#name: std::string
#nDeck: int
#nLiveDeck: int
1

Cell
+row int
+col: int

Rect
+lt: Cell
+rb: Cell

. 6.2. 6.3

.
///////////////////////////////////////////////////////////
/ / Task6_3

left-top
right-bottom

223

6.3.

.
linillllllllllllllllllllllllllllUIIIIIIIIIIIIIIIIIIIIIIII
II Task6_3
llllllllllllllllllllllllllllllinilllllllllllllllllllllllll
II Ship.h
#ifndef SHIP_H
#def1ne SHIP H
#1nclude <set>
#1nclude <map>
#include <str1ng>
//#1nclude "CyrlOS.h"

#def1ne N 10
struct Cell:
typedef std::set<Cell> Cell Set;

// for Visual C++ 6.0


//
// (N * N )

//

// ()
struct Cell {
Celldnt _ = 0. int _ = 0) : row(_r). 1(_) {}
bool InSet(const CellSet&) const;
// //
// CellSet
bool operator<(const Cell&) const;
1nt row;
//
1nt col;
//

// ( "")
struct Rect {
Recto {}
Rect(Cell J t . Cell _rb) : It(Jt). rb(_rb) { FillCsetO; }
void FillCsetO;
// cset
//
bool Intersect(const CellSet& cs) const; //
//
// cs
Cell It;

// left-top-
Cell rb;
// rlght-bottom-
CellSet cset;
// ,
//
// Ship ( )
class Ship {
friend class UserNavy;
friend class RobotNavy;

224

6.

public:
ShipO : nDeckCO), nLlveDeck(O) {}
Shipdnt, std::str1ng, Rect):
protected:
Rect place;
//
std::str1ng name:
//
1nt nDeck;
//
1nt nLiveDeck;
//
}:
#end1f /* SHIP_H */
///////////////////////////////////////////////////////////
// Ship.cpp
#1nclude <str1ng>
#1nclude <algor1thm>
#1nclude "Ship.h"
using namespace std;
///////////////////////////////////////////////////////////
// Cell
bool Cell;;InSet(const CellSet& cs) const {
return (cs.count(Cell(row, col)) > 0);
}
bool Cell::operator<(const Cell& c) const {
return ((row < crow) || ((row == crow) && (col < c . c o l ) ) ) ;
}

///////////////////////////////////////////////////////////
// Rect
void Rect::F1llCset() {
for (1nt 1 = It.row; 1 <= rb.row: 1++)
for (int j = It.col; j <= rb.col; j++)
cset.1nsert(Cell(1, j));
}
bool Rect;:Intersect(const CellSet& cs) const {
Cell Set common_cell;
set_1ntersect1on(cset.beg1n(). cset.endO. cs.beginO. cs.endO.
inserter(common_cell. common_cell .beginO));
return (common_cell .sizeO > 0);
}
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllll

II Ship
Ship::Shipdnt _nDeck, string _name. Rect _place) ;

place(_place). name(_name), nDeck(_nDeck). nLiveDeck(_nDeck) {}


Nlllllllllllllllllllllllllllllllllllllllllllllllllllllllll

II Navy.h
#include "Ship.h"
#define DECK 176
// -
#define DAMAGE 'X' // -
#define MISS 'o'
// ,

225

6.3.
typedef unsigned char F1eld[N][Nl:
typedef std::map<Cell. 1nt> ShipMap:

//
//
// " - "
//

enum CurrentState { Miss. Damage. Kill


// Space -
//
struct Space {
public:
static Cell u_fire;
static Cell r_fire;
static CurrentState u_state;
static CurrentState r_state;
static int step;

//
// ()
II
//

// Navy
class Navy : public Space {
public:
NavyO;
//
// ownField
// enemyField
//
int GetlntO;
bool IsLiveO { return (nLiveShip > 0) // ?
Rect Shell(Rect) const; /* "
( ) */
//
void AddToVetoSet(Rect);
// vetoSet.
protected:
//
Ship shipClO];
//
Field ownField;
Field enemyField; //
// " - "
ShipMap shipMap;
// ""
Cell Set vetoSet;
Cell Set crushSet; // ""
//
int nLiveShip;
}:
void AllocShipCint, i n t .
void ShowO const;

std::string);

// UserNavy
class UserNavy : public Navy
public:
UserNavyO { AllocationO
void AllocationO;
void FireOffO;
void ResultAnalysO;
void GetFireO;
void FillDeadZone(Rect r. F1eld&);
}:

// no
//
// ""
//
//

226

6.

// RobotNavy
class RobotNavy : public Navy
public:
RobotNavyO;
void AllocatlonO:
void FIreOffO:
// no
void ResultAnalysO;
//
void GetFlreO;
// ""
private:
bool IsCrushContlnue; //
bool upEmpty;
//
// ""
///////////////////////////////////////////////////////////
// Navy.cpp
#1nclude
#1nclude
#1nclude
#1nclude
#1nclude

<1ostream>
<cstdl1b>
<t1me.h>
<algor1thni>
"Navy.h"

using namespace std:


Cell Space::u_f1re
Cell Space::r_f1re
CurrentState Space u_state = Miss:
CurrentState Space r state = Miss:
Int Space::step = 1
// gap(n) n
string gapdnt n) { return str1ng(n, ' ' ) : }
///////////////////////////////////////////////////////////
// Navy
Navy::Navy() : nLlveShlp(lO) {

// ""
for (Int 1 = 0: 1 < N: 1++)
for (Int j = 0: j < N: j++) {
ownF1eld[1][j] = '.';
enemyF1eld[1][j] = '.':

Rect Navy::Shell(Rect r) const {


Rect sh(r):
sh.lt.row = (-sh.lt.row < 0)? 0 :
sh.lt.col = (-sh.lt.col < 0) ? 0 :
sh.rb.row = (++sh.rb.row > (N -D )
sh.rb.col = (++sh.rb.col > (N -D )
return sh:

sh.lt.row:
sh.lt.col:
? (N - 1) sh.rb.row
? (N - 1) sh.rb.col

6.3.
void Navy::AddToVetoSet(Rect ) {
for (1nt 1 = .It.row; 1 <= r.rb.row; 1++)
for (1nt j = r . I t . c o l ; j <= r . r b . c o l ; j++)
vetoSet.1nsert(Cell(1. j ) ) ;
}

void Navy::AllocSh1p(1nt 1ndSh1p. int nDeck. string name) {


int 1. j;
Cell It. rb;
//
// ""
// vetoSet
whiled) {
It.row = randO ^ (N + 1 - nDeck);
I t . c o l = rb.col = randO % N;
rb.row = It.row + nDeck - 1;
i f ( I R e c t d t . rb).Intersect(vetoSet)) break;
}

//
ship[indSh1p] = ShipCnDeck. name. Rectdt. rb));
// ( DECK).
//
for (i = It.row; 1 <= rb.row; i++)
for (j = It.col; j <= rb.col; j++) {
ownField[i][j] = DECK;
shipMap[Cell(i.j)] = indShip;
}
// vetoSet
//
AddToVetoSet(Shell (Rectdt. rb)));

void Navy::$how() const {


char rowNameClO] = {'A'. 'B'. ' C . 'D'. 'E'. 'F'. '6*. 'H'. T . 'J']
string colName("l 2 3 4 5 6 7 8 9 10");
int i. j;
cout "
\n";
cout gap(3) " " gap(18) " " endl;
cout gap(3) colName gap(6) colName endl;
for (i = 0 ; i < N; i++) {
// Own
string line = gapd) + rowName[i];
for (j = 0; j < N; j++)
line += gapd) + (char)ownField[i][j];
// Enemy
line += gap(5) + rowName[i];
for (j = 0; j < N; j++)

227

228

6.

+= gap(l) + (char)eneniyF1eld[i][j];
cout line endl;
cout endl:
cout "====

cout step ". "

=\n":
" :

step++;

}
1nt Navy:: Get Into {
1nt value:
while (true) {
cin value:
if ('\n' == cin.peekO) { cin.getO: break: }
else {
cout " ( ):" endl:
cin.clearO:
while (Cin.getO != ' \ n ' ) { } :

return value:
///////////////////////////////////////////////////////////
// UserNavy
void UserNavy::Allocation() {
srand((unsigned)time(NULL)):
AllocShip(0. 4. " ''"):
AllocShipd, 3. " ''")
AllocShip(2, 3. " ''")
AllocShip(3. 2. " ''")
AllocShip(4, 2, " ''")
AllocSh1p(5, 2. " ''"):
AllocShip(6. 1. " ''"):
AllocSh1p(7, 1. " ''"):
AllocShip(8. 1. " ''"):
AllocShip(9, 1. " '" ):
vetoSet.clearO:

void UserNavy::FillDeadZone(Rect ^ Fields fieId) {


int i. J:
Reel: si1 = Shell(r):
for (i = sh.lt.row. j = sh.lt col: j <= sh rb.col: J-^+)
if (sh.lt.row < r It.row) field[- ][j] =- ' ' .
for (1 = sh.rb.row. j = sh.lt col: j <= sh rb col: j++)
if (sh.rb.row > r rb.row) field[- ][j] = ' '.
for (
J = sh.lt.col. i = sh.lt row: i <= sh rb row: i++)
i f (sh.lt.col < r.It.col) f i e l d [ i ] [ j ]

6.3.
for (j = sh.rb.col. 1 = sh.lt.row: 1 <= sh.rb.row; 1++)
1f (sh.rb.col > r.rb.col) f1eld[1][j] = ' ';
void UserNavy::F1reOff() {
string capltaljetter = "ABCDEFGHIJ";
string small_letter = "abcdefghlj";
unsigned char rowName; // (A. . ... . J)
Int colName;
// (1. 2
10)
Int row;
// (, 1
9)
1nt col:
// (0. 1
9)
bool success = false;
while (!success) {
cin rowName;
row = cap1tal__letter.f1nd(rowName):
If (-1 == row) row = small_letter.f1nd(rowName);
If (-1 == row) { cout ". .\"; continue;
col Name = GetlntO;
col = col Name - 1;
If ((col < 0) li (col > 9)) {
cout ". ."; continue;
}
success = true;
}
u_f1re = Cell(row. col);
}

void UserNavy:;ResultAnalys() {
// r_state -
// u_f1re
sw1tch(r_state) {
case Miss;
enemyF1eld[u_f1re.row][u_f1re.col] = MISS;
break;
case Damage:
enemyF1eld[u_f1re.row][u_f1re.col] = DAMAGE;
crushSet.1nsert(u_f1re);
break;
cdse Kill:
enemyF1eld[u_f1re.row][u_f1re.col] = DAMAGE;
crushSet.1nsert(u_f1 re);
Rect k i l l ;
k i l l . I t = ^crushSet.beglnO;
k l l l . r b = ^(-crushSet.endO);

// ""
F1llDeadZone(k1ll. enemyFleld);
crushSet.clearO;
}

229

230

6.

void UserNavy::GetF1re() {
/ / - r_f1re
string c a p U a l J e t t e r = "ABCDEFGHIJ":
char rowName = cap1tal_letter[r_f1re.row];
1nt col Name = r_f1re.col + 1;
cout ' : " rowName colName
i f (DECK == ownF1eld[r_f1re.row][r_fire.col]) {

endl;

cout "'^^^ ! ^*^";


ownField[r_f1re.row][r_f1re.col] = DAMAGE;

u_state = Damage:
// , r_f1re
i n t ind = sh1pMap[r_f1re]:
sh1p[1nd].nL1veDeck-:
i f (!sh1p[1nd].nL1veDeck) {
u_state = K i l l :

cout gap(6) "0 ! " ship[ind].name


nLiveShip-:
Rect k i l l = shipCind].place:
FillDeadZone(kill. ownField):

else {
u_state = Miss;
cout "**^ ! ***":
ownField[r 1nre.row][r_fire.col] = MISS:
}
cout endl:

1
///////////////////////////////////////////////////////////
// RobotNavy
RobotNavy::RobotNavy() {
AllocationO:
isCrushContinue = false;
upEmpty = false
}
void RobotNavy::Allocation0 {
AllocSh^ p(0. 4. " ''"):
AllocSh" p(l. 3. " ''"):
AllocSh^ p(2. 3. " '*");
AllocShi p(3. 2. " '");
AllocShi p(4. 2. " ''");
AllocSh! p(5. 2. " ''");
AllocShi p(6. 1. " ''");
AllocShi p(7. 1. " ''");
AllocShi p(8. 1. " ''");
AllocShip(9. 1. " ''");
vetoSet. clearO:

6.3.
void RobotNavy::F1reOff() {
Cell . cUp;
1f (!1sCrushCont1nue) {
//
wh1le(l) {
crow = randO % N;
.col = randO % N:
1f (!c.InSet(vetoSet)) break;
}
}
else {
/ / ""
= clip = r_f1re:
clip, row-;
i f (dupEmpty) && crow && (!cUp. InSet(vetoSet)))
.row-;

else {
= ^(-crushSet.endO);
.row++;

r_f1re = c;

vetoSet.insert(r fire);

void RobotNavy:;ResultAnalys() {
// u_state -
// r_fire
switch(u__state) {
case Miss:
if (isCrushContinue) upEmpty = true;
break;
case Damage:
isCrushContinue = true;
crushSet.insert(r_fire);
break;
case Kill:
isCrushContinue = false;
upEmpty = false;
crushSet.i nsert(r_fi re);
Rect kill;
k i l l . I t = ^crushSet.beginO;
k i l l . r b = ^(-crushSet.endO);

AddToVetoSet(Shell(kill));
crushSet.clearO;
}
}

231

232

6.

void RobotNavy::GetF1re() {
/ / - u_f1re
1f (DECK == ownF1eld[u_f1re.row][u_f1re.col]) {

cout "*** ! '^^^";


r_state = Damage;
// , u_f1re
1nt 1nd = sh1pMap[u_f1re];
sh1p[1nd].nL1veDecl<-;
if (!sh1p[1nd].nL1veDeck) {
r_state = Kill;
cout gap(6) " " sh1p[1nd].name " !!!'
nLiveShIp-:
else {
r_state = Miss:
cout "*^^ ! ***";
}
cout endl:
}
//////////////////////////////////////////////////////////
// Main.cpp
#1nclude <1ostreafn>
#1nclude "Navy.h"
using namespace std;
int mainO {
//
UserNavy userNavy;
RobotNavy robotNavy;
userNavy. ShowO;
while (userNavy.IsLiveO && robotNavy.IsLiveO) {
//
if (Space::u_state != Miss) {
cout "...: <Enter>" endl;
cin.getO;
}
else {
userNavy.FireOff;
robotNavy. GetFireO;
userNavy.ResultAnalysO;
if (!robotNavy.IsLiveO) {
userNavy. ShowO;
break;

//
if (Space::r_state != Miss)

233
cout " : ..." endl;
else {
robotNavy.FlreOffO;
userNavy.GetFlreO;
pobotNavy.ResultAnalysO:
}
userNavy.ShowO:

if (userNavy.IsLiveO)
cout "\n:-))) ! !!! :-)))" endl;
else {
cout "\n:-((( . ." endl:
cout ":-((( , !!!" endl;
}
cin.getO;
return 0;
}
//
Task6_3
//////////////////////////////////////////////////////////

,
:
cset set<Cel 1> Rect;
vetoSet crushSet set<Cell> Navy;

shipMap map<Cell. int> Navy.


,
(
).
.
1. ,
.
2. STL ,
.
3. STL ,
, .
4. , , STL!

1
-
1 stack STL.

234

6.

,
(
).
.

2
, ,
stack STL.
, .
, . .
, , .
, .
.

3
,
.
: ,
, .
:
;
;
, ;
.
.
list STL.

4
.
: ,
, .

:

( );
: ;
, ,
, ;

235

: ;
, ,
, ;
, , ,
.
11 st.

5
.
: , ,
, .

:
;
;
;
.
11st.

6
.
: , ,
, .

:
, ;
;
, ;
, .
multimap,
.

7
.
,
- (, ,
), , .

multimap.

236

6.

8
.
: ()
. : , , ,
.

:
;
:

10%
, ;
.
list.

9

.

. : , ,
.

:
(
);
;
;
,
.
vector.

10
- - .
.

:
( ).
:
-;
-.

237

.
.
.

11
, ^ -
: ().
STL.

12
, - 15.
.
: ( )
( ).
STL.

13
,
.
: , ,
, .

:
.
( )
:
(70);
(15);
,
1 (10);
(5).
.
. /.
prior1ty_
queue STL.
< () ,
.
.

238

6.

14
.
: ,
, .

:
(
);
: ;
, ,
, ;
: ;
, ,
, ;
, , ,
, ;
, , ,
, .

, .

15
.
: , ,
, .

:
;
;
;
, ;
, .
multlmap,
.

16
.
: , ,
, .

239


:
, ;
;
, ;
, .
vector.

17
.
,
- (, ,
), , .
11st.

18
.
,
: () .
: , , , .

:
;
:

10%
, ;
.
set.

19

.

. : , ,
.

:
(
);

240

6.

;
;
,
.
set.

20
- - .
.
.
:
( ).
:
-;
-.
.
.
set.

-
, , \
. ,

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

.
()

,
.
' ,
, .

242


[7].
: , .
,
,
.
. 1 .

()

()

, , , ,
. . .1
. ,
,

, [7], [10] [15].
[7] ,
, , ,
, .

,
.
. ,
.
,
.
,
. ,
, .

.

243

,
,
, . ,
- ,
, , .



,
, .

, . ,

( ) ( ).
, , ,
, , , .
(Factory Method) .71
, .
( ),
.

.
,
.
:
, ;

, , , ;

, ,
.

.
(Abstract Factory)
, , ,
.
,
-,
,
. ,
.

244

,
PIX . , :
, ,
;

, ;

;
,
, .
(Singleton) ,
, .
, .
, ,
,
, .
Instance,
.
.
^
, . Singleton
,
.
,
, ,
.
(Prototype)
- .
(,
, ).
, . ,
.
, :
,
. ,
.
:
.
,
-;
.

.

245

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

. ,
.
, .
,
, ,
.


,
.
.
.
,
,
.
(Adapter)
, . ,
- .
(
, ),
( ,
).
,
, ,
,
,
.
(Decorator) .

.

246

,
. ,
.
, .
,
.
, ,
, .
(Proxy)
. :

, ;
(
, );
(
);
.
(,
,

,
).

. , ,
.
(Composite)
-.
, . . 255.
(Bridge) ,
.
.

.
: ,
.
, ,
.
.
.
.

,
.

247

(Flyweight)
.
,
. .
.

, , . .
,
. -
, .
! ,
. ,
.
,
>
, , .
, .
, ,
.
( -
,
).
(Facade)
.
, .
, ,
, ,
. ,
, .
, .
.
, .
,
,
.


1

.
.
.

248

,
, .
,
: , , -
, ,
,
, -.
.
(Interpreter)
, ,
.
,
.
, .
,
. ,
, ,
.
(Template Method)
, .
,
, - ,
. ,
, .

. ,
.
(Iterator)
, .
,
(), -,
.
,
.
, , , STL OWL.
(Command) ,
, ,
.
, , ,
, . .
Command.
- .
.

249

(Observer) -,
! .

1 . ,
.
: .
,
. ,
, .

, .
(Visitor) ,
. ,
, .
:

,
;
, ,
, ,
. ,
.
,
;
, , ,
.
. .1.
:
Visitor () Visit ConcreteElement .
, Visit.
, .
,
.
ConcreteVisitor ( ) ,
Visitor. ,
. ConcreteVisitor

. ,
.

250

Visitor

Client

VisitConcreteElementA(ConcreteElementA)
VisitConcreteElementB(ConcreteElementB)

ConcreteVisitorl

ConcreteVisitor2

VisitConcreteElementA(ConcreteElementA)
VlsitConcret8ElementB(ConcreteEIementB)

VisitConcreteElementA(ConcreteElementA)
VisitConcreteElementB(ConcreteElementB)

>4

ObjectStructure

>^

Element
Accept(Visitor)

ConcreteEiementA

ConcreteElementB

Accept(Visitor v)
OperationAO

Accept(Visitor v)
OperationBO

V->VisitConcreteElementA(this)

V->VisitConcreteElementB(this

. . 1 .

Element () Accept,
.
ConcreteElement ( ) Accept,
.

ObjectStructure ( ):

;
;
(. ),
, .
, ,
ConcreteVlsitor, , .
,
.
, .
:
1. :
. ,
,
.

251

2. ,
.
Visitor.
, , ,
.
3. ,
, ,
.
, ConcretGElement
:
Visitor,
ConcreteVisitor.
, ,
, : ,
, ,
. , Visitor ,
ConcreteElement .
, .
(Mediator) ,
, .
,
. , ,
.
.

.
,
.
, ,
,
, . .
(State)
. ,
.
,
.
, , .
, .
,

,
. .

252

, ,
,
.
(Strategy) ,
. ,
. . 252.
(Memento) , ,
,
.
,
~ , ,

. , -.
,

. .
(Chain of Responsibility)
. -
, , ,
.
, ,
,
;
, , ; ,
, .
:
;
(, ,
).

(Strategy)
,
. :
, .
, ;
. ,
,
, . ,
.
,
.
;

253

(Strategy)

, .
,
;
,
.
.
. .2.
Context

strategy
>

Strategy
Algorithm InterfaceQ

Context InterfacEO

ConcreteStrategyA

ConcreteStrategyB

ConcreteStrategyC

Algorithm lnterface()

Algorithm lnterface()

Algorithm lnterface()

. . 2 .

:
Strategy ()
. Context
, ConcreteStrategy;
ConcreteStrategy ( ) Strategy.
1, , Strategy;
Context () ConcreteStrategy.
Strategy ,
Strategy .
, Context
Strategy, .

, .
Strategy , :
template <class AStrategy> class Context {
void OperationO { theStrategy.DoAlgorlthmO; }
// ...
private:
AStrategy theStrategy;
// ...
class MyStrategy {
public:
void DoAlgorithmO:
}:

// ...
Context<MyStrategy> aContext:

254

,
Object Windows Library Borland
. ,
, ,
.
()
Validator ().
.
( )
, RangeValidator
. ,
, Validator.
, Val idator,

1 .
,
. (
, , ).
#include "iostream"
using namespace std;
//
//

class Validator {

public:
virtual bool validate(char ^ text) = 0: // .
//
class RangeValidator : public Validator
public:
RangeValidatorO;
bool validateCchar * text);

//

class FilterValidator : public Validator {


public:
FilterValidatorO:
bool validate(char ^ text);

//

class InputLine { //
public:
InputLine(Validator * ) ;
void checklnputO; ^
protected:
Validator * validator;
char textClOO];

//
// ,

(Composite)

255

RangeValidator::RangeVal1dator() {
cout "RangeValidator created" endl;
bool RangeValidator::validate(char * text){
cout "RangeValidator working under the text " text endl
return true:
FilterValidator::FilterValidator(){
cout "FilterValidator created" endl;
bool FilterValidator::validate(char * text){
cout "FilterValidator working under the text " text endl:
return true:
InputLine::InputL1ne(Validator * _validator) {
validator = _validator: //
void InputLine::checklnput(){
cout "checklnput working " endl:
validator -> validate(text):
// ,
}
// ,
int mainO {
// :
InputLine * rangelnputLine = new InputLine(new RangeValidator):
InputLine ^ filterlnputLine = new InputLineCnew FilterValidator):
II...

// :
rangeInputLine->checkInput():
filterInputLine->checkInput():
return 0:
}


RangeValidator FilterValidator.

(Composite)
.
, .
-, ,
,
.

256

. ..
Client

Component

P<-

OperationQ
Add(Component)
Remove(Component)
GetChild(int)

Leaf

Composite

OperationO

OperationO
^_
Add(Component)
Remove(Component)
GetChild(int)

f> g
g.OperationO

. ..

.
Component ():
;
,
;
;

(
).
Leaf ( , ):
;
.
Composite ( , ):
, ;
-;

Component.
Client ():
Component.
Component,
, . ,
(,
) ,
.
Leaf
, Composite .
, , .

(Composite)

257

Client Component
.
Leaf, .
Composite,
, ,
.
,
.
-
: ,
, , . .

.

(Parser),
. Value
( Leaf), ,

. DoubleOperand ( Composite).
Expression Component.
getValueO,
.

, ,
ClientExpression.
/ / expr.h
class Expression {
public:

virtual double getValueO = 0:


}:
class DoubleOperand: public Expression {
protected:
Expression* el;
Expression* e2:
public:
DoubleOperandCExpression* el. Expression* e2): el(el). e2(e2) {}
virtual double getValueO = 0:
}:
class Addition: public DoubleOperand {
public:
Addition(Expression* el, Expression* e2): DoubleOperand(el. e2) {}
virtual double getValueO { return el->getValue() + e2->getValue(); }
}:

258

class Subtraction: public DoubleOperand {


public:

Subtraction(Expression* el, Expression^ e2): DoubleOperand(el. e2) {}


virtual double getValueO { return el->getValue() - e2->get\/alue(); }
}:
class Multiplication: public DoubleOperand {
public:
Multiplication(Expression* el. Expression^ e2): DoubleOperand(el. e2) {}
virtual double getValueO { return el->getValue() * e2->getValue(); }
class Division: public DoubleOperand {
public:
Division(Express1on* el, Expression^ e2): DoubleOperand(el. e2) {}
virtual double getValueO (return el->getValue() / e2->getValueO; }
class Value: public Expression {
private:
double v;
public:
Value(double v): v(v) {}
virtual double getValueO { return v; }
// client.h
#include <string>
#include "expr.h"
using namespace std;
class ClientExpression {
private:
// expression
Expression* vl, v2, v3, v4, v5;
Expression* add. sub. mul. div. result;
string
expression;
public:
ClientExpressionO;
-ClientExpressionO;
double getValueO;
string getStringO { return expression; } .
// client.cpp
#include "client.h"
01i entExpressi on::01i entExpressi on()
vl = new Value(5);
v2 = new Value(lOO);

(Composite).

v3 = new Value(3):
v4 = new \/alue(4):
v5 = new Value(2):
mul = new Mult1pl1cat1on(v4, v5);
d1v = new D1v1s1on(v2, v3);

add = new Add1t1on(vl. d1v);


sub = new Subtract1on(add. mul);
result = sub;
expression = "5 + 100 / 3 - 4 ^ ^

ClientExpresslon::-ClientExpresslon {
delete vl; delete v2; delete v3; delete v4; delete v5;
delete add; delete sub; delete mul; delete div;

double ClientExpresslon::getValue()
return result->getValue();

// main.cpp
#include <iostream>
#include "client.h"
using namespace std;
int mainO {
ClientExpresslon e;
cout "expression: " e.getStringO " = " e.getValueO endl
return 0;

259


1. . /-^-^. . .:
, 2001 - 460 .
2. ., . C/C++. :
. ~ .: , 2002 - 240 .
3. . C++: . .: , 2000 320 .
4. . -
C++. - .: , 1998 - 560 .
5. . C++. -- .: , 1999 .991 .
6. , C++. .:
, 1997 - 304 .
7. ., ., ., . -
. . .: , 2001 368 .
8. . C++. C++ In-Depth. . 4.
.: , 2002 400 .
9. . C++ 21 . .:
, 2000 - 816 .
10. . .
. ~ .: , 2003 144 .
11. ., My . C++. C++ In-Depth.
. 2. .: , 2002 384 .
12. . C++. . .: ,
2003 - 860 .
13. . - C++.
Computer Science. 4- . ~ .: , 2003 928 .
14. . STL C++. .: , 1999 240 .
15. ., . . . .:
, 2002 ~ 288 .
16. . C++. C++ In-Depth.
. 3. .: , 2002 336 .

abortO, 122
at, string, 187

eofbit, ios, 148


erase, 203,216
erase, string, 188

back, 203,204
back_inserter, , 213
bad, ios, 148
badbit, ios, 148

c_str, string, 188


catch, 120
cin, 144
clear, ios, 148
close, 183
const, 24
copy, string, 188
copy, , 213
count, 216
count, , 208
count_if, , 209
cout, 144

fail, ios, 148


failbit, ios, 148
find, string, 188
find, , 208
find_first_of, string, 188
find_if, , 209
find_last_of, string, 188
flush, 146
for_each, , 209
front, 203
front_inserter, , 213
fstream, 181

gcount, ios, 147


get, ios, 147
getline, ios, 147
good, ios, 148
goodbit, ios, 148

H
dec, , 145
deque, 202

hex, , 146

I
empty, 204
endl, , 145
ends, 146
eof, ios, 148

ifstream, 181
includes, , 216
insert, 203,216
insert, string, 188
inserter, , 213

262
iomanip, 145
ios, 144, 146
iostream, 144
istream, 144
istringstream, 185

L
length, string, 188
list, 202

M
map, 215,217
merge, , 214
multimap, 215
multiset, 215

oct, , 146
ofstream, 181
open, 182
ostream, 144
ostringstream, 185
out_of_range, string, 187

search, , 210
set, 215, 216
set_intersection, , 216
set_terminate(), 123
set_union, , 216
setfill, 146
setprecision, 146
setw, 146
size, string, 188
sort, , 210
sstream, 185
stack, 206
state, 148
static, 32
STL, 196
streambuf, 144
string, 73, 186
stringstream, 185
substr, string, 188
swap, 204
swap, string, 188

template, 106
terminateO, 122
throw, 120
top, 206
try, 120
typename, 106, 205

pair, 217
peek, ios, 147
pop, 206
pop_back, 203
pop_front, 203
priority_queue, 207
private, 15, 59
protected, 15, 59
pubhc, 15,59
push_back, 203
push_front, 203
put, ios, 147

vector, 74,202
virtual, 63

queue, 207

R
rdbuf, ios, 147
rdstateO, 148
read, ios, 147
replace, string, 188
rfind, string, 188
RTTI, 102

unexpected(), 125
using, 81

w
write, ios, 147

/ , 23, 27

3
, 24

263

, 196, 197
, 213
, 199
, 199
, 199
, 213
, 198

, 198
, 198
, 199
, 199

, 14
(), 18
, 17
, 27
, 15
, 15
, 24
, 17
, 28
, 18
, 15
, 19
, , 19
, 18

, 24
, 29
, 30
, 31
, 15
, 32
, 15

/, 145
, 146
, 146
, 147
, 144
, 145
, 145

, 148
, 144
, 144

, 196
, 197
(deque), 202

back, 203,204
begin, 199
count, 216
empty, 204
end, 199
erase, 205, 216
front, 203
insert, 205,216
pop_back, 203, 204
pop_front, 203
push_back, 203
push_front, 203
swap, 204
, 200
(set), 215
(multiset), 215
(queue), 207

(priority_queue), 207
, 197
(), 215, 218
(list), 202
(stack), 206
, 200

, 205
, 13

, 14
, 14

, 58
, 59
, 63
, 64
, 62

, 60
, 59
6130
, 59
, 59
, 59
, 59
, 61
, 59

264
()
, 64
, 59
, 59

, 196, 201
, 119
try, 120
, 129
, 125
, 123
, 122
catch, 120
throw, 120
, 121
, 124
, 15

, 67
, 66
(), 6S
, 68
, 67

, 241

, 247
, 243
, 245
, 143
, 209
, 211

, 196
string, 186
, 187
at(), 187
, 187
, 185
str(), 185
, 185


UML, 65
, 89
, 65

, 181
, 182
close(), 183
(), 182
, 211

, 105
, 105, 107

, 110
, 106
, 107
, 108
, 110
, 241
Doubles witch, 81
Switch, 71

,

C++. -

.
.
.
.

. , .
.

05784 07.09.01.
09.03.06. 70x100/16. . . . 21,93.
. 3500. 575
, 196105, -, . , . 67.
005-93, 2;
95 3005 .

190005, -, ., 29.