You are on page 1of 200

C++

c 20042015 , stamatis@materials.
Copyright

uoc.gr

LaTEX2.
c , (
).

10 2015.

http://www.materials.uoc.gr/el/undergrad/courses/ETY215

1
1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

1
1
4

2
2.1 . . . . . . . . . . . . . . .
2.1.1 . . . . . . . . . . . . .
2.1.2 . . . . . . . . . . . .
2.2 . . . . . . . . . .
2.2.1 . . . . . . . . .
2.2.2 . . . . . . .
2.2.3
2.2.4 . . . . . . . .
2.2.5 . . . . . .
2.2.6 void . . . . . . . . . . . . . .
2.2.7 Enumeration . . . . . . . . .
2.3 . . . . . . . . . . .
2.4 . . .
2.5 . . . . . . . .
2.5.1 typedef . . . . . . . . . . . .
2.5.2 . . . . . .
2.5.3
2.5.4 . . . . . . . . . . . .
2.6 . . . . . . . . . . . .
2.6.1 . . . . . . . . . . . .
2.6.2 (struct) . . . . . . . . .
2.7 . . . . . . . . .
2.7.1 . . . . . . . . .
2.8 (namespace) . . . .
2.9 (streams) . . . . . . . . . . . .
2.9.1 . . . . . . . . .
2.9.2 Strings . . . . . . . . . .
i

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

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

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

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

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

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

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

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

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

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

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

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

5
5
5
6
7
7
7
9
9
11
11
12
12
14
16
16
16
17
18
19
19
22
23
28
29
31
31
32

ii

2.9.3 . . . . . . . . . . . . . . . .

33

2.9.4 . . . . . . . . . . . . . . . . . . . . . . .

35

2.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

36

43

3.1 . . . . . . . . . . . . . . . . . . . . . . . . .

43

3.1.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43

3.1.2 ?: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

44

3.1.3 switch . . . . . . . . . . . . . . . . . . . . . . . . . . .

45

3.1.4 goto . . . . . . . . . . . . . . . . . . . . . . . . . . . .

47

3.1.5 assert()

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

47

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

48

3.2.1 while . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

3.2.2 do while . . . . . . . . . . . . . . . . . . . . . . . . . .

48

3.2

3.2.3 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

48

3.2.4 continue . . . . . . . . . . . . . . . . . . . . . . . . . .

49

3.2.5 break

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

50

3.3 . . . . . . . . . . . . . . . . . . . . . .

50

3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

50

59

4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

59

4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

60

4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

61

4.4 . . . . . . . . . . . . . . . . .

65

4.4.1 . . . . . . . . . . . . . . . . . . .

65

4.4.2 . . . . . . . . . . . . . . . . . . . . . . . . .

67

4.4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . .

67

4.4.4 . . . . . . . . . . . . . . . . . . . . .

71

4.4.5 . . . . . . . . . . . . . . . . . . .

74

4.5 main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

76

4.6 overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . .

77

4.7 template . . . . . . . . . . . . . . . . . . . . . .

78

4.7.1 . . . . . . . . . . . . . . . . . . . . . . . .

80

4.8 inline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

81

4.9 . . . . . . . . . . . . . . . . . . . . . . . .

81

4.10 C++ . . . . . . . . . . . . . . .

82

4.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

84

4.11.1 . . . . . . . . . .

84

4.11.2 . . . . . . . . . . . . . . . . . . . . . . . . . .

86


5 Standard Library
5.1 . .
5.1.1 (Pair) . . . . . . . . . .
5.1.2 . . . . .
5.1.3 ,
5.2 (containers) . . . . . . . . .
5.2.1 . . . . . . . . . . . .
5.2.2 Iterators . . . . . . . . . . . . .
5.2.3 vector . . . . . . . . . . . . . .
5.2.4 deque . . . . . . . . . . . . . .
5.2.5 list . . . . . . . . . . . . . . . .
5.2.6 set multiset . . . . . . . . .
5.2.7 map multimap . . . . . . .
5.3 (algorithms) . . . . . . . .
5.4 . . . . . . . . . . . . . . . .

iii

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

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

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

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

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

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

97
98
98
99
100
101
101
106
109
115
117
122
126
130
141

6
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.1.1 . . . . . . . . . . . . . . . . .
6.1.2 (encapsulation) . . . . . . . . . . . . . . .
6.1.3 . . . . . . . . . . .
6.2 . . . . . . . . . . . . . . . . . . . . . . . . .
6.2.1 . .
6.2.2 (ConstructorsCopy constructor) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2.3 (Destructor) . . . . . . . . . . . . . . . .
6.2.4 (assignment operator) . . . . . . . .
6.2.5 . . . . . . . . . . . . . . . . . . . . . .
6.3 template . . . . . . . . . . . . . . . . . . . . . . . . .
6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

145
145
145
147
149
151
152

. . . !

163

155
158
158
159
160
161

Fortran C
167
.1 C . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
.2 Fortran . . . . . . . . . . . . . . . . . . . . . . . 169

173

185

189

190

iv


ISO C++,
, .
C++ , , ,
Fortran C. (
) C++ .

- C++,
Standard 1998,
, ,

.
, C++ C , STL ,
..
C++ 1 ( ).

http://www.dmst.aueb.gr/dds/faq/academic.html#oo

vi


.
, ,
.
, ,
, , .
(Fortran, C, C++) ,
, , ( ) .

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

1.1

:
. C++
1

1.

,
:

#include <iostream>
/*
main:
Takes no arguments.
Prompts for a real number and prints its square.
Returns 0.
*/
int
main() {
double a;

// Declare a real variable

// Print text on screen


std::cout << "Give a number: ";
std::cin >> a; // Get value from keyboard
// Print text on screen
std::cout << "Square of input is ";
std::cout << a*a;

// Print result

std::cout << \n;

// Change line

return 0; // Successful exit from program.


}
:
C++ , , . Standard Library (STL) ( 5), (directives) #include . , #include <iostream>,
, ,
.
#include ( )
C++.
/* */ //
(2.1.1).
int main() {...} (4.5)
C++: main, (int,
2.2.4), , ,
.
( ) {} () .

1.1.


C++.
, , (return 0;) ,
} ( 0).1 0 main() .
.
,
main(). main()
.
double a;
() 15 a (2.2.5).
C++ ,
compiler, .
std::cin std::cout , , standard input ()
standard output () . (<<), () ,
( ) std::cout ( ). , (>>) std::cin (
) . , ,
standard header <iostream> (2.9). ,
, C++ format
/ .
. , ,
..
(2.9.4).
(") , C-style string. \n ( ),
. ()
( , (\))
(character literal, 2.2.2).
(*)
.
(;)
(, ,
).
( #) ;.
1
main() .

1.

C++
, .
C++ .
( ). , ,
(+=, ==, <<,
/*, //,. . . ). , , //
.
( )
#.

1.2

1. , .2
2. . +,-,*,/
( ). .
3. C++ ;

#include <iostream>
main(){std::cout << Hello World!\n}
4. C++ ;
5. C++ ;

include iostream.h
Main();
{
Double x,y,z;
cout < "Enter two numbers ";
cin >> a >> b
cout << The numbers in reverse order are << b,a;
}

2
compiler
.


2.1
2.1.1

C++ . compiler

// ,
/* */ .
/* */
tab, .
.
:

// This is a comment
int j; // Here is a declaration
/* Let us make
an ugly multi-line
comment.
/
*

, , ,
.
. ,
: compiler

5

2.

#if 0
.....
#endif
,
( ). ,
#
.

2.1.2

, , , . C++
(az,AZ), (09), underscore
(_). .
C++ ,
. underscore (_)
compiler
. ,
C++ (Keywords, 2.1) , , , .
:
:
ena lathos onoma, pali_latho$, 1234qwer, delete, .onoma+
:
timi, value12, ena_onoma_me_poly_megalo_mikos, sqrt, Delete

C++ Keywords
and
bool
compl
do
export
goto
namespace
or_eq
return
struct
try
using
xor

and_eq
break
const
double
extern
if
new
private
short
switch
typedef
virtual
xor_eq

asm
case
const_cast
dynamic_cast
false
inline
not
protected
signed
template
typeid
void

auto
catch
continue
else
float
int
not_eq
public
sizeof
this
typename
volatile

bitand
char
default
enum
for
long
operator
register
static
throw
union
wchar_t

2.1: C++.

bitor
class
delete
explicit
friend
mutable
or
reinterpret_cast
static_cast
true
unsigned
while

2.2.

2.2

C++
:

2.2.1

(bool)
(.. /, /,. . . ). , .. a, :

bool a;
true false. , a
, (4.4),
( 6) namespace (2.8), (global)
false.

:

bool a = true;
, ,

bool a(true);
bool , , , . ,
true 1 false 0. , true 0
false. , (4.3)
true false.

2.2.2

(char) .. c,
:

char c;
, ,
ASCII.

char c = a;
, ,

2.

char c(a);
c
, a.
() (") C-style string1
char.
. 2.2,
( ) . ..

char
char
char
char

newline(\n);
bell(\a);
alpha(\141); // alpha = a in ASCII
Alpha(\x61); // Alpha = a in ASCII

C-style
string.
:

std::cout <<
"This\nis\na\ntest\n\nShe said, \"How are you?\"\n";

This
is
a
test
She said, "How are you?"
char , namespace
, ,
.
(\0, 0 ASCII),
0 ( 48 ASCII).
,
int ( ) .
, , char signed unsigned.

array of const char.

2.2.


\?
\
\"
\\
\a
\b
\f
\n
\r
\t
\v
\xhhh
\ooo
\0




Carriage return
tab
tab
hhh
ooo

2.2: .

2.2.3

C++ wchar_t

256 . ..
256
.. ASCII.

2.2.4

(.. int) :

int i;
, namespace,
i 0, .
(.. 10)

int i = 10;
, ,

int i(10);

. int
16 bits,
h

15
15
2 , 2
= [32768, 32768) .

2.

10

std::numeric_limits<int>::min()

std::numeric_limits<int>::max()
header <limits>:

#include <limits>
#include <iostream>
int
main() {
std::cout
std::cout
std::cout
std::cout

<<
<<
<<
<<

std::numeric_limits<int>::min();
\n;
std::numeric_limits<int>::max();
\n;

return 0;
}
C++ , short int, int long int,
16, 16, 32 bits . ,
short int int
long int.
, char,
sizeof() , 2.7.1.
signed () unsigned.
, int. C++ int
int
.


, 0, .
, + . 0 ( x X)
07. 0x 0X,
( ,
, af AF).
long int L l
:
12L, 0xBABEL, -665l

2.2.

11

U u unsigned int,

unsigned long int.

2.2.5

C++ :
(float), (double) (long double).
float
double long double.
float
std::numeric_limits<float>::digits10

std::numeric_limits<float>::min()

std::numeric_limits<float>::max()
header <limits>.
. std::numeric_limits<>::min()
.
, double, .

, (
) double.
. e
E, , 10
e/E :
2.034,

0.23,

.44,

23.,

2e4

( 0.0002),

2.3E2 ( 230.0) .

F f float L l
long double.

2.2.6 void
void
. ,

2.

12

. void* ( void) .

.

2.2.7 Enumeration
Enumeration ()
. ..

enum Color {RED, GREEN, BLUE};


, Color, : RED, GREEN, BLUE.
:

Color c(RED);
switch
(3.1.3), compiler . ,
(4.4).

:
0. RED 0,
GREEN 1 BLUE 2.
,

1 :

enum Color {RED, GREEN=5, BLUE};


// RED = 0, GREEN = 5, BLUE = 6
.
, enum .
:

Color d(2);

2.3

// Error


C++ template class (6.3),

.
C++
header <complex>

#include <complex>

2.3.

13

.
(.. z) , double :

std::complex<double> z;

// z = 0.0 + 0.0 i

, double
(int, float, long double,. . . ).
, 0, ,
STL.

:

std::complex<double> z1(3.41);
// z1 = 3.41 + 0.0i

// or z1 = 3.41;

std::complex<double> z2(3.0,2.0);
// z2 = 3.0 + 2.0i
std::complex<double> z3(z2);
// z3 = z2

// or z3 = z2;

std::complex<double> z4(std::polar(2.0));
// z4 = 2.0 exp(0.0i)
std::complex<double> z5(std::polar(2.0,0.75));
// z5 = 2.0 exp(0.75i)
std::polar() (magnitude)
(phase angle) ( rad) .
+,-,*,/ +=,-=,*=,/= (2.7)
,
. ,
C++ (4.1) ,
. std::abs()
. , std::norm() std::arg()
z = + i

std::abs(z) = 2 + 2 ,
std::norm(z) = zz * 2 + 2 ,
std::arg(z) = arctan( / ).

, std::conj() .
, ,
.

2.

14

z
, std::real(z) std::imag(z),
std::complex<>, z.real()
z.imag().
,
compiler:

std::complex<double> z(3.0,1.0);
// z = 3.0 + 1.0i
z = std::complex<double>(z.real(), 3.7);
// z = 3.0 + 3.7i
z = std::complex<double>(2.3, std::imag(z));
// z = 2.3 + 3.7i
z = 5.0; // or z = std::complex<double>(5.0);
// z = 5.0 + 0.0i
z = std::complex<double>(-1.0, 2.0);
// z = -1.0 + 2.0i
<<
(,)
>>
:
(,)
()

, , typedef (2.5.1).

2.4

C++
( 2.3). -

==
>
>=

!=
<
<=

2.3: C++.
true false. .. 3.0>2.0 true

2.4.

15

2!=1+1 false. . ,
, (==, ) (!=, ). ,
.
C++ !
(NOT), && (AND), || (OR). ,
, not, and or .
&& ||
! :
!
:
! (4 > 3) false.
! (4 < 3) true.

&& true true.
false:
(4 > 3) && (3.0 > 2.0) true
(4 < 3) && (3.0 > 2.0) false
|| true true,
false:
(4 > 3) || (3.0 < 2.0) true
(4 < 3) || (3.0 < 2.0) false
C++, bool:

bool a(3==2);
bool b = ( (i > 0) && (i < max) );
C++:
(short-circuit
evaluation). ..

(i < 0) || (i > max)


i < 0 true
, . ,

(i < 0) && (i > max)

2.

16

i >= 0 false
i > max.
.

2.5

2.5.1 typedef
, . , ,
typedef. , .. std::complex<double>
complex
:

typedef std::complex<double> complex;


:

complex z;
typedef
: .
double. ,
double float. ,
real

typedef double real;


float
:

typedef float real;


typedef C++ template functions (4.7).

2.5.2


,
compiler , ,

.
const
( ) :

2.5.

17

double const pi(3.141592653589793);


int
const maximum(100);
const
.
.
(.. , )

.

2.5.3

block block
. .
( ) , ,
. , ,
namespace ( global) ,
0 ( ). ,
static (4.9),
compiler .
C++
, C:

int a = 3;
2.3,
(
C++)
. C++
,

std::complex<double> z(1.0,2.0); // z = 1.0 + 2.0 i


:

int b = 4;
int b(4);
, (.. int) (.. std::complex<double>), :

2.

18

int c = int(3);

// c = 3

std::complex<double> z = std::complex<double>(3.0, 2.0);


// z = 3.0 + 2.0i
int d = int();
// d gets default integer value, 0.
std::complex<double> y = std::complex<double>();
// y gets the default value specified
// in complex<> class, 0.0 + 0.0i.

templates (4.7,6.3).

.

int a;
int b;

int a,b;


. ..

int * a,b;
( ), a, , b.
.

2.5.4

, , , 2 } block
.
.
(global) ,
(4.4), ( 6) namespace (2.8),
(
#include).
,
. ,
2

, .

2.6.

19

, .
3
.
block . ..

#include <iostream>
int
main()
{
double x(3.2);
{

// begin block A

// begin block B
int x(5);
std::cout << x;
// prints 5

// end

block B

std::cout << x;
// prints 3.2
return 0;
}

// end

block A

x block x block x
x. block x x.
.

2.6

, , .
(array) ( ) (struct)
, (class).

2.6.1


.. ,
( array)
365 .

2.

20

, , ,
.
C++ :
[_];
_ , .
containers STL, 5.
temperature
365
( int):

double temperature[365];
int const N(155);
int telephone[N];
telephone
.
, .. temperature, 0 D 1
D . , , 0.
..

temperature[0]
temperature[1]
temperature[2]
temperature[3]
temperature[4]
//.........

=
=
=
=
=

14.0;
14.5;
15.5;
13.0;
15.0;

int i(3);
std::cout
std::cout
std::cout
std::cout
std::cout

<<
<<
<<
<<
<<

"The Temperature on ";


i+1;
// Notice the increment
" day was: ";
temperature[i];
\n;

(index) ,
0 D1 compiler
( !).

( )
.
compiler
.
, , ,
0 ( ):

2.6.

21

int primes[5] = {1,2,3,5,7};


int digits[] = {0,1,2,3,4,5,6,7,8,9};

// size is 10

char alphabet[5] = {a, b, c, d, e, f};


int a[5] = {12, 5, 4};

// Error

// a == {12,5,4,0,0}

( )
C Fortran
. (
) C C++
( ) .
C++ :
[__1][__2];
.
6 8

, -

int a[6][8];
.. (3,2) a[3][2].
, :

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


,
, .
, , , (row-major order).
Fortran (column-major order). , C C++
Fortran.
, , , column-major order
:
[Aij ] N 1 N 2,
C++ N 1 N 2.
Ai,j a[i+ N1*j].
[Aijk ] N 1 N 2
N 3, N 1 N 2 N 3.
Ai,j,k a[i + N1 * (j + N2 * k)].
.

2.

22

C ,

Fortran , , .
, C++ . , Standard
Library (STL)
.
std::vector<> header <vector>: v, 30 .. double

std::vector<double> v(30);
. ,
:
:

#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N; // get dimension
std::vector<double> v(N);
// v[0], v[1], ..., v[N-1]
}
, v C++.
std::vector<> 5.

2.6.2

(struct)

.. . , , , ,
, .
,
.
C++ std::string header <string>.
,
, :

2.7.

23

struct ChemicalElement {
double mass;
int Z; // atomic number
std::string name;
std::string symbol;
};
(;) }. (
) C++
};.3
ChemicalElement struct , ,
( ) .
. ChemicalElement
:

ChemicalElement oxygen;

, , ..

ChemicalElement hydrogen = {1.008, 1, "Hydrogen", "H"};


(.)
(.) :

oxygen.name = "Oxygen";
oxygen.mass = 15.99494;
oxygen.Z = 8;
oxygen.symbol = "O";
std::cout
std::cout
std::cout
std::cout
std::cout

<<
<<
<<
<<
<<

"The mass of element ";


oxygen.name;
" is ";
oxygen.mass;
\n;

(struct) C
C++ 6.
.

2.7

C C++
:

2.

24

+,-: a
.
+,-,*: a,b , .
/ a,b: a/b.
/,%
.
. std::pow() header <cmath>
( 4.1).
C++
(=): a = a + b; a+=b;.
(+=, -=, *=, /=, %=)
=. ,
a
.
C++ ++ -- (
) .
, .. b = ++a + c; 1
a, a
. , .. b = a++ + c;
1 a .
( 1) --.

b = --a + c;

a = a-1;
b = a + c;

b = a-- + c;

b = a + c;
a = a-1;
++ -- , , ,
,
.
2.4 . ,

2.7.

25

. .
( ) compiler
. .. a--b
(a--)b ( ) a-(-b). .

compiler ( , )
. .. int
double int double
. int ( bool char) int
, .
: .. bool
char;
, (
) .
, .. .

. ,
( )
.5

int a = 3.14; // a is 3
short int b = 12121212121.3;

// b = ??

. , (/) .
() /.

static_cast:

int sum = 2 + 3 + 5;
int N = 3;
// Wrong value
double mean1 = sum / N;
// Correct value
5

compiler .

2.

26

C++




/ ( )


/ ( )
bitwise NOT


NOT
/

( )

bitwise AND
bitwise XOR
bitwise OR
AND
OR
4








bitwise AND
bitwise XOR
bitwise OR

.
->
()
[]
++, -sizeof
sizeof()
++, --

&
*
!
+, *
/
%
+
>>, <<
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
=
*=
/=
%=
+=
-=
<<=
>>=
&=
^=
|=
,

2.4: (
) .
.
4

(?:) (=) 3.1.2.

2.7.

27

double mean2 = static_cast<double>(sum) / N;


static_cast :

static_cast<newtype>(variable);
:

(newtype) variable.
.

overloaded ,
. .. , std::sqrt() <cmath> float,
double, long double int
. 4.6,
compiler C++ ,
:

#include <cmath>
int
main() {
int p = 8;
double riza = std::sqrt(p);
// Error, ambiguous
double r = std::sqrt(static_cast<double>(p));
// Correct. Calls sqrt(double).
}
C++

, ..

int a;
int b;
b = a = 3;
//First a = 3; then b = 3;
bool cond;
cond = b < 5;
// First check b < 5; true. Then cond = true.

2.

28

2.7.1

sizeof
sizeof bytes.6
sizeof:

int a;
std::cout << sizeof(int);
// parentheses are necessary
std::cout << sizeof(a);
std::cout << sizeof a;

.
.
sizeof (array) bytes
, ,
. ,

double a[13];
int k = sizeof(a) / sizeof(a[0]);

// k == 13


.
sizeof
, ,
.
sizeof std::size_t, <cstddef>.
.
(,)

(,).
.
bit
bits
, 0 1.
6

, byte

char.

2.8. (NAMESPACE)

29

bit .
(short int, int, long int, bool, char) enum, signed unsigned.
2.5.

<<
>>
&
^
|
<<=
>>=
&=
^=
|=

bitwise NOT


bitwise AND
bitwise XOR
bitwise OR


bitwise AND
bitwise XOR
bitwise OR

expr
expr1 << expr2
expr1 >> expr2
expr1 & expr2
expr1 ^ expr2
expr1 | expr2
expr1 <<= expr2
expr1 >>= expr2
expr1&=expr2
expr1 ^= expr2
expr1 |= expr2

2.5: bit C++.


,
0 1 .
<<, >> bits
. bits .
<< 0 >>
unsigned.
&, ^, | bit pattern
AND, XOR, OR bit .
bit
(true/false,
on/off, . . . ) . C++
bitset<> std::vector<> bool
, .
bool,
,
bit byte, (2.2.4).

2.8

(namespace)

(
)
. ..
solve, -

30

2.



. C++ namespace ( )
. :

namespace onoma {
......
double a;
......
}
a ( , , , . ) namespace onoma.
namespace : onoma::a. namespace (a).

. ,
namespace .
namespace C++
(2.1.2).
Standard Library (STL) namespace std. cin,
cout, complex std::. , namespace
.. std, using namespace std;
block .
block std::. ..

#include <iostream>
#include <complex>
// "std::" needed here
typedef std::complex<double> complex;
int
main() {
using namespace std;
// "std::" not needed here
complex a(2.0,3.0);
complex<double> b(1.0);
// In the following cout "std::" is not needed
cout << a;
cout << \n;
cout << b;
cout << \n;

2.9. (STREAMS)

31

return 0;
}
( ), namespace
:

using std::cout;
: namespace {...}.
namespace.
, ,
.
main() namespace
global.

2.9

(streams)

( streams) (std::cin) (std::cout) . , streams, std::cerr


std::clog, standard error
.
, ..
.
, ..
, , ..
. streams header
<iostream>.

2.9.1

streams streams . header <fstream> std::ifstream


std::ofstream.

std::ifstream inpstr("filename");
stream , inpstr,
"filename". , .
,

std::ofstream outstr("filename");

2.

32

stream , outstr, "filename". ,


.

std::ofstream outstr("filename", std::ios_base::app);


"filename" stream outstr
.
: inpstr, outstr (
, , )
std::cin std::cout . ,

double a(10.0);
outstr << a;
char c;
inpstr >> c;
a
outstr c
inpstr.

.
stream str (..
),
: str.close();. stream str
str.open("filename");.

2.9.2

Strings

(streams) , .
C++ strings, .
header <sstream> , std::istringstream std::ostringstream.
ostringstream C++ string
. string, .
C++ string
"filename_3.dat":

#include <sstream>
int
main() {

2.9. (STREAMS)

33

std::ostringstream os;
os << "filename_";
os << 3;
os << ".dat"; // os contains the string "filename_3.dat"
}
string str(),
ostringstream:

std::cout << os.str(); // prints: filename_3.dat


C++ string C string c_str(). ,
filename_3.dat, .. , ostringstream os,
:

std::ofstream outstr(os.str().c_str());
std::istringstream string
:

#include <sstream>
int
main() {
std::istringstream is("5 6 7 a");
int i,j,k;
is >> i;
is >> j;
is >> k;

// i = 5
// j = 6
// k = 7

char ch;
is >> ch;

// ch = a

2.9.3

,
STL, (stream) standard output, standard
error, string, <<:

std::cout << a;
std::cerr << "Wrong value of b";
std::cin
>>, :

double a;
int b;

2.

34

std::cin >> a;
std::cin >> b;
( ) .
<<, >> . ..

std::cout
std::cout
std::cout
std::cout
std::cout
std::cout
std::cout

<<
<<
<<
<<
<<
<<
<<

"To athroisma toy "


a;
" kai toy ";
b;
" einai: "
a+b;
\n;

std::cout << "To athroisma toy " << a


<< " kai toy " << b;
std::cout << " einai: " << a+b << \n;


bool (2.2.1)
.

std::cout << (3==2);


0. true false,
manipulator std::boolalpha
header <ios>:

std::cout << std::boolalpha << (3==2);


std::noboolalpha.
,
bool .

stream
stream: false
. , (.. )
stream inp :

int i;
while (inp >> i) {
.....
.....
}

2.9. (STREAMS)

35

, inp >> i
inp. i ,
true while.
streams
get(),
EOF (
eof() true).
is ( 3.2.1)

while (is.get() != \n);


seekg()/seekp() ( / ), . .. is is.seekg(0);.

2.9.4

(manipulators) C++,
boolalpha noboolalpha, , bool. header <ios>
(no)skipws: () .
(no)showpos: () + .
(no)showpoint: () 0 .
scientific: d.dddddd Ddd
fixed: dddd.dd
left/right: / .
header <iomanip>
setprecision() (
) . 6.
setw() ( ) .
0.
setfill()
setw() . .

2.

36

manipulators namespace std.


:

#include <ios>
#include <iomanip>
#include <iostream>
int
main() {
double b = 3.25;
std::cout << b << \n;
std::cout << std::showpoint << b << \n;
std::cout << std::noshowpoint;
// reset

double a = 256.123456789987;
std::cout << "default\t"
<< a << \n;
std::cout << "scientific\t" << std::scientific
<< a << \n;
std::cout << "fixed\t" << std::fixed
<< a << \n;
std::cout << "with 9 digits\t"
<< std::setprecision(9)
<< a << \n;
}
,
, precision, width fill, setprecision,
setw setfill :

#include <iostream>
int
main() {
std::cout.precision(9);
std::cout << 256.123456789987 << \n;
}

2.10

1. , .
C++
.

2.10.

37

2. C++ ;
() const
() johns
() y+z12
() 1stclass
() xyz123
() George
() ThisIsALongOne
() To_onoma_mou
() two-way
() proto
() _posotita
3. C++ stream
std::cin
std::cout
std::cerr
std::clog
4. C++
//
{
;
#
5. ;

int a = 2, b = 3, c = 4;
double x = y = 5;
bool equal = b = 3;
int d = d;
int e = "e";
6. compiler;
;
7.
compiler; ;

2.

38

#include <iostream>
#include <limits>
int
main() {
int a = std::numeric_limits<int>::min() - 10;
int b = std::numeric_limits<int>::max() + 10;
" << b << \n;
std::cout << a << "
return 0;
}
8.

() Euler.
() .
() .
() .
() .
9. C++
:
() 37/(5*2)
() 37/5/2
() 37(5/2)
() 37%(5%2)
() 37%5%2
() 37-5-2
() (37-5)2
10. m = 24 n = 8:
() m-8-n
() m==n-3
() m%n
() m%n++
() m%++n
() ++m=n-() m=n=3
() m+=n-=2

2.10.

39

() m*=++n
() m+=--n==m-11. :
() (50 - 5 * 4) / 10 - 7
() 12 + -5 * 2 + 6 / 3
() 1 + 2 + 3 + 4 + 5 + 1 * 2 * 3 / 4 * 5
() 3 > 7
() (3 > 7) || (4 < 9)
() 135 == 100 + 35
() (true && false) || (true || false)
() (3 > 7) || ((10 < 9) == (3 == 8))
() false || !(3 > 7)
() 3!=6
() 6 / 4 * 5 == 6 * 5 / 4
12.
() 7 / 2
() 7.0f / 2
() ((7 / 2) == (7.0 / 2))
() ((6 * 3) / 80) / (36 - 7 * 5)
13. C++
1 n.
14. a, b
c a.
15.
() ++x+=+a++-+b++
() ++x-=-a+b++
() -x---a---b-16.
; .
17. C++ :
() d.
() r.

2.

40

() d h.
() c
a,b .
18.
:
() a==b||a==c&&c<5
() c=x!=0
() 0<=i<6
() a=b==c++
19. a, b, c a 2 + b2 = c 2
. m, n
m > n,
m 2 n 2 , 2mn, m 2 + n 2 .7 C++

.
20. Gauss
( 2099)
:
.
:
() r1 = 19.
() r2 = 4.
() r3 = 7.
() ra = 19r1 + 16.
() r4 = ra 30.
() rb = 2r2 + 4r3 + 6r4 .
() r5 = rb 7.
() rc = r4 + r5 .
rc 3 , .
C++ .
rc .

2.10.

41

21. , , ,
.
: 200000, : 2 days, 7 hours, 33 min & 20 sec.

42

2.


3.1

3.1.1 if
if
. ()
, . C++
:

if (condition) {
...
// block A
} else {
...
// block B
}
(condition) ,
block {} (block
A). , block
else (block B).
block , ,
.
({}) . ..

if (val > max)


max = val;
else {
max = 1000.0;
++i;
}
else block :

if (condition) {
...
}
43

3.

44

block
if. if (condition) {...} else {...} . block
() .
.
if, else . else
if block. ,
, :

if (i == 0)
if (val > max)
max = val;
else
max = 10;
, max = 10; i 0
(val > max) (i == 0).
:

if (i == 0) {
if (val > max)
max = val;
}
else
max = 10;

3.1.2 ?:
(?:) C++.

if (condition)
val = value1;
else
val = value2;

val = (condition ? value1 : value2);


,
(condition ? : )
condition ,
.

3.1.

45

(?:)
, . (=),
. ,
: (?:) (=)
,
. ,

a = b ? c : d

a = (b ? c : d)

a ? b : c = d

a ? b : (c = d)

3.1.3 switch
switch if. :

switch (i) {
case value1:
...
case value2:
...
...
...
case valueN:
...
default:
...
}
i (char, int, (short int,
long int) signed unsigned ) enum.


.
value1, value2,. . . ,valueN
enum ( ).
, i
value1, value2,. . . ,valueN. , case.

3.

46

case / default ,
break ( .. goto, return,
throw). break switch. value1,
value2,. . . ,valueN block default, .
, } switch.
case default .
:

.
+, -, *, /.

.

#include <iostream>
int
main() {
double a, b, res;
char c;
std::cin >> a >> b;
std::cin >> c;
switch (c) {
case +:
res = a + b;
break;
case -:
res = a - b;
break;
case *:
res = a * b;
break;
case /:
res = a / b;
break;
default:
std::cerr << "wrong character\n";
return -1;
}
std::cout << "the result is " << res << \n;
}

3.1.

47

3.1.4 goto

(label). (.. labelname)
.

labelname : statement;

goto:

goto labelname;
goto

.
goto . C++
(3.2) goto . ,
,
. , goto
.

3.1.5 assert()
C++
header <cassert> macro1 assert().
:

assert(integer_number);
integer_number 0, ,
NDEBUG header. ,
assert()
.
, assert() debugging, 0 false ( , 2.2.1), . .. assert(N<10);,
(N<10).
#define NDEBUG
.
std:: (
std) macro .

1
C++
.

3.

48

3.2

3.2.1 while
while , . :

while (condition) {
...
}
while:
1. condition
,
.
block
{}.
2. block ( break, return, goto,
throw, . . . ), 1 ( ).
.

3.2.2 do while
do while while (3.2.1)
. :

do {
...
} while (condition);
do while:
1. block {}.
2. ( break, return, goto, throw,. . . ),
condition.
,
.
1 ( block).

3.2.3 for

for
. C++ for .
:

3.2.

49

for (initial_statement ; condition ; final_statement) {


...
}
for :
1. initial_statement. ( (,), 2.7.1).
2. condition.
,
for.
, block
{}. block ( break, return,
goto, throw,. . . ) final_statement.
3. block , 2
( ).
.
initial_statement, condition, final_statement . (condition)
for .
initial_statement ,
for, , , }.
:
10 a 0, 10, 20, . . . 90
:

for (std::size_t i = 0; i < 10; ++i)


a[i] = i*10;
i . , std::size_t i; for:

std::size_t i;
for (i = 0; i < 10; ++i)
a[i] = i*10;
// here i is 10

3.2.4 continue
continue for,
while, do while.
, .

3.

50

3.2.5 break
break while,
do while, for, switch.
,
.

3.3

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

if (int j = 3) max = 10 + j;
j if.
(3) true.

3.4
1.

()

for (;;) {
...
}
() for
while. do while;
2. :

#include <iostream>
int
main() {
int j = 3;
if (j = 4) {
std::cout << "j is " << j << \n;
std::cout << "Should not print this!!!\n";
}
}
; ; .
;

3.4.

51

3. C++
() (n!) .
() N Fibonacci 2 .
f (n + 2) = f (n + 1) + f (n ),

n 0,

f (0) = 0, f (1) = 1 .

() . 3 .
() Lagrange 4 :
( ) .
: n,
a,b,c,d 0 a, b, c, d n.
n = a 2 + b2 + c 2 + d 2 .
4. C++
ex

ex =

X
xn
n =0

n!

sin x

sin x =

X
(1)k x 2k +1
k =0

(2k + 1)!

cos x

cos x =

X
(1)k x 2k
k =0

(2k )!



.

1012 .
5. 8 .
std::rand() <cstdlib> 0 RAND_MAX.
RAND_MAX compiler; std::srand().5
2

http://oeis.org/A000045
http://en.wikipedia.org/wiki/Euclidean_algorithm
4
http://mathworld.wolfram.com/LagrangesFour-SquareTheorem.html
3

UNIX man srand .

3.

52
6.

() 1000 [a, b] a = 20, b = 20.


( !)

int r = a + (b-a+1) * (std::rand()/(RAND_MAX+1.0));


: r , 0 std::rand()RAND_MAX.
RAND_MAX+1.0 RAND_MAX+1;
() C++ , 0
.
7. Gauss, a
2a = n (n + 1) + m (m + 1) + k (k + 1)
n, m, k .

a, n,m,k
. n,m,k
( n m k).
16 ([0, 1, 5] [0, 3, 4] . . . ), 104
([6, 7, 10] . . . ), 111 ([1, 10, 10] [0, 9, 11] . . . ).
8. C++
() .
() N .
( :
2,3,5,. . . ).
()
6 ( p,p+6,p+12 ) .
9. . , .

() 2.
. /
1.
.
6

http://oeis.org/A047948

3.4.

53

10.
a, b, c 12
ax 2 + bx + c.

x1,2 =

b2 4ac

2a

C++ std::sqrt()
<cmath>. .

( a = 0 a =
b = 0;).
( b2 < 4ac).
11. 4 (, , ).
Ferrari 7 .
12. M N K
1 0. 1
.
() ( M = 20, N = 60, K = 400)
, x
o .
() .ppbm
( M = N = 512, K = 150000):
: P1.
: (.
).
1 0

( ).
plain pbm (portable bitmap) .
13. A (M N ) B (N P). M = 10, N = 20, P = 30
A, B matA.dat
matB.dat. ,
. matC.dat
C = A B.
7
http://en.wikipedia.org/wiki/Quartic_function#Ferrari.27s_
solution

3.

54

14. C++
Ax = B Gauss8 .
A B .
15. C++ A Gauss
Jordan 9 .
16.

() 30
f (x ) = x (x 2 + 5 sin(x ))
[5 : 5]. C++ std::sin()
<cmath>.
() C++ f (x )
[5 : 5]
: x1 , x2
x2

f (x )dx

1
2

x1

x (f1 + f2 ) .

Simpson:
x1 , x2 , x3

x3

f (x )dx

1
3

x1

x (f1 + 4f2 + f3 ) .

Boole: x1 ,
x2 , x3 , x4 , x5

x5

f (x )dx
x1

2
45

x (7f1 + 32f2 + 12f3 + 32f4 + 7f5 ) .

Durand: n x1 ,
x2 , . . . , xn

xn

f (x )dx x
x1

2
5

f1 +

11
10

f2 + f3 + + fn 2 +

11
10

fn 1 +

2
5


fn .

fi f (xi ) x .
[10 sin(5) 50 cos(5)].
.

8
9

http://mathworld.wolfram.com/GaussianElimination.html
http://mathworld.wolfram.com/Gauss-JordanElimination.html

3.4.

55

17. Spline Fit. n (xi , yi ). 2(n 1)


. ,

( 2(n 2) ).
0 (2 ),
, .
(2 ). 4n 4
.

.
() spline
.
() .
()
.
18. C++ Game of Life 10 Dr.
J. Conway. :
M N , ( ). K
. ( ):
()
().
() ().
() (
!).
.
plain pbm ( 12) 11 .
10
11

http://www.math.com/students/wonders/life/life.html

UNIX, imagemagick, animate *.ppbm

56

3.

, (,
).

19. 1 , 2 , 5 , 10 ,
20 , 50 , 100 (= 1) 200 (= 2).

. 300 ;
: , 300
, 150 , 60 5
.
300 .
20.
:
: P3.
: (
).
K .
255.
pixels
.
(R), (G), (B) pixel, . pixel
K 0 0 ( K 255
255 0 0). pixel 0 K 0. 0 0 0
K K K. RGB 0 K
.
plain ppm (portable
pixmap) .
france.pppm
, .
21. p(z ). z0 ( p0 (z0 ) , 0)
p(z ), p(z ),

3.4.

57

:
p(zi )
,
zi +1 = zi 0
p (z i )

i = 0, 1, 2, . . . .

, z0 ,
z1 . z2 ,
.,
p(z ). Newton
Raphson , .
p(z ) = z 3 1
a = 1, b = ei2/3 , c = ei2/3 .
( z = 0 + i0) .


. , ..: a
(RGB = (255,0,0)). b
(RGB = (0,255,0)) c
(RGB = (0,0,255)). 0 +i0
RGB = (255,255,255).
() N = 512
[1 : 1] ( ): xi , i = 0, . . . , N
1.
() M = 512
[1 : 1] ( ): yj , j = 0, . . . , M
1.
() z = xi + iyj
.
() pixels (i, j)
newton.pppm plain ppm (
20).
newton.pppm Newton fractal.

58

3.

4.1

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

, .

, ,
. .., ,
,
, ,
.
,
.

( structured) ( procedural)

C++.
, C++ .
59

4.

60

4.2

(reference) . ,
.., a

int a;
(.. r) a :

int & r = a;
r
a.
, &.
( )
( , , ). ,

.
, a r :

int a;
int & r = a;
a = 3;
r = 2;

// r = 3
// a = 2

int b = a;

// b = 2

int c = r--;

// c = 2, a = 1

int d;
int & r = d;

// Error

const,
:

int const a = 5;
int & r1 = a;

// Error

int const & r2 = a;


// Correct. Value of a cannot change through r2.
r1 ,
a, const, r1.
, ,
, C++ , , ,

4.3.

61

. , <limits> std::numeric_limits<double>::digits10. :

#include <limits>
#include <iostream>
int
main() {
int const & digits = std::numeric_limits<double>::digits10;
std::cout << digits << \n;
}
,
.
:

double const & r = 4.0;


,
.
.

4.3

, , .
,
, (&) .
( )
.
* _;

int a = 3;
&a a
, p,

int * p = &a;
p (*) p. ,

4.

62

, *p
a
*p a. ..

double r = 5.0;
double * q = &r;
*q = 3.0; // r becomes 3.0

void1 :

int
int
p =
int

a = 4;
* p;
&a;
* q = p;

int * q = p; q int
p. , q p , , *q
*p ( a).

int a = 5;
int * p = &a;
void * t = p;
void p, int,
, , a. (*)
p a , ( *) t
. , void
static_cast<> ( )
. ,

int * v = static_cast<int*>(t);
*v = 4;
a 4.

. (*)
.

. ,
( )
.
1

void * .

4.3.

63

0. 0
, , . (null
pointer) (*) (
). (.. ) 0 (
, 2.2.1)
.
: , ,
.
.
(
):

int a;
int
int
int
int

* p1 = &a;
const * p2 = &a;
* const p3 = &a;
const * const p4 = &a;

p1 .
p2 .
*p2.
p3 .
*p3

.
p4 .

.

:
.
:

double x = 1.2;
double * const p = &x;
double y = 0.1;

4.

64

p = &y; // error
double const * q = &x;
*q -= 0.2; // error
int const a = 2;
int * r = &a; // error
p ,

*p. , p . ++,--( )
: T
sizeof(T) . , (.. p+2)
sizeof(T). , , ,
( !) .2
void
, ,
( void *).

. ,
:

int a[10];
int * p = &a[3];
int * q = p + 2;

// q == &a[5]

int a[10];
int * p = &a[0];
*(p+i) a[i] , ,
p+i == &a[i].
.
,
. a[i]
*(a+i). , 2

std::ptrdiff_t <cstddef>.

4.4.

65


.
:
:

double b[10];
double * p = b;
for (int i = 0; i < 10; ++i)
*p++ = 1.0;

double b[10];
for (double * p = b; p != b+10; ++p)
*p = 1.0;
2.6.2 , .. member,
(struct) , , , .. a, :

a.member
, pa,
[ (*) (.), 2.4]

(*pa).member
C++
, :

pa->member

4.4

.
, , 4.7, .
. ,
.

4.4.1

4.

66

__
(__ , __ ,. . . )
{
//
}
void
. ,
(, ,
).
, , void. , ,

(}) .

, :
_ _ [ ]
. ,
,
. , int a[]
int *a .
, ,
. containers STL 5
.
,
. compiler ,
( )
.
.
(
{} ) (;):
__
(__ , __ ,. . . );
.
.
.
,
( ),
, :

4.4.

67

int func(double a, double b = 5.0);


func() ( a) b
, 5.0. ,

,
, compiler
.

4.4.2

return ;
. main() return: ,
return 0;.
( void) return; ( ). ,
void. return , ,

void
f(int a) {
...
return;
}
void
g(int b) {
return f(b);
}

return, .
.
, ,
.

4.4.3

4.

68

( ).
,
, .


, .. , , .

.
read :
:

#include <iostream>
#include <fstream>
double
func(double a, double b);
// declaration. The definition is elsewhere.
int
read(double & a, char const fname[]) { // definition
std::ifstream file(fname);
file >> a;
return 0; // All ok
}
void
print(char c) { // definition
std::cout << c << \n;
}
int
main() {
double x(3.2);
double y(3.4);
double z = func(x,y);
// Calls func with double, double.
int i(3);
double t = func(x,i);
// Calls func with double, int.
// int is promoted to double.
print(a); // calls a void function.

4.4.

69

double r;
read(r, "input.dat");
// calls function and ignores returned value.
}

( ).

.
.

. ..

#include <iostream>
void add3(double x) {

x+=3.0; }

int
main() {
double z(2.0);
add3(z);

//

z = ???

std::cout << z << \n;

// z is 2.0

}
add3() ,
: x z
(2.0), 5.0 ,
. z 2.0.

, ..

void add3(double & x) {

x+=3.0; }

, ..

void add3(double * x) { *x+=3.0; }



. , , add3(z),
x z
z. ,
z, add3(&z). x
z. x ,
*x .

4.

70

, , , ,
. ,
(
). ,

const. ,

void
print(double const a[], std::size_t N) {
for (std::size_t i(0); i < N; ++i)
std::cout << a[i] << \n;
}
a, ,
. ,
.
const
( ).

void f(double x);

void f(double const x);


. :

void f(double * x);


void f(double * const x);
, void f(double * const x),
void f(double const * x),
4.3.
, ,
:
x:

void f(double x); // argument cannot change



x:

void f(double & x);

// argument can change

x:

void f(double const & x);

// argument cannot change

4.4.

71

,
xp, *xp (
)

void f(double * xp);


// argument cannot change, *xp can change
,
*xp ( )

void f(double const * xp);


// argument cannot change, *xp cannot change
,
xp, *xp ( )

void f(double * & xp);


// argument can change, *xp can change
a ,

void f(double a[]);


// argument cannot change, a[i] can change
a ,

void f(double const a[]);


// argument cannot change, a[i] cannot change

4.4.4

, headers,
.h,3

#include "name.h"
name.h header,
(, path ). headers ("). , headers
(<>).
headers, compiler
. ,
3

compiler.

4.

72

,
, headers.
:
min/max /
:
min: <
max: <
utilities.h (.. double)

// utilities.h
// declarations
double
dmin(double a, double b);
double
dmax(double a, double b);
utilities.cc

// utilities.cc
#include "utilities.h"

// Not necessary but good practice

// definitions
double
dmin(double a, double b) { return a<b ? a : b; }
double
dmax(double a, double b) { return a>b ? a : b; }
:
utilities.h , ..

#include <iostream>
#include "utilities.h"
int
main() {
double a, b;
std::cout << "Give two real numbers\n";
std::cin >> a >> b;
std::cout << "Max is " << dmax(a,b) << \n;
std::cout << "Min is " << dmin(a,b) << \n;
}

4.4.

73

compile utilities.cc
main() compiler
,
linking.
(recursive)
C++ . ,
,
.
:
( recursive) :
,

(
n! =

1 2 (n 1) n = (n 1)! n ,
1,

n>0,
n=0.

, n
( n 1).
C++

std::size_t
factorial(std::size_t n) {
std::size_t result;
if (n > 0)
result = n * factorial(n-1);
if (n == 0)
result = 1;
return result;
}

( n
).
factorial()
factorial(n)factorial(n-1) factorial(n-2) . . . (
)
0.

(?:), 3.1.2:

4.

74

std::size_t
factorial(std::size_t n) {
return (n > 0 ? n * factorial(n-1) : 1);
}

4.4.5

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

#include <iostream>
double f(double x);
int
plot(double low, double high) {
double const step = (high - low) / 100;
for (double x = low; x < high; x+=step)
std::cout << x << " " << f(x) << \n;
return 0;
}
plot()
f (x ) . f (x )
plot .
.
__
(__ , __ ,. . . );

__
(*_)(__ , __
,. . . );
*_ (*) (
) (()) ( ), 2.4. , _

4.4.

75

double f(double x);

// declaration of f(x)

double (*fptr)(double x); // declaration of a pointer


fptr = f; // assignment
double x = 1.2;
double y = f(x);
double z = fptr(x);

// or z = (*fptr)(x);

// y == z

plot :

int
plot(double low, double high, double (*f)(double x)) {
double const step = (high - low) / 100;
for (double x = low; x < high; x+=step)
std::cout << x << " " << f(x) << \n;
return 0;
}
, , f (x ) .

double sin(double x);


double cos(double x);
double tan(double x);

// sine
// cosine
// tangent

int
plot(double low, double high, double (*f)(double x));
int
main() {
plot(1.0, 5.0, sin);
plot(1.0, 5.0, cos);
plot(1.0, 5.0, tan);
}

// plot of sine
// plot of cosine
// plot of tangent

typedef ..
, :

4.

76

int func(double a, double b); // target function


typedef int (*ftype)(double x, double y);
ftype g = func;

4.5

// type

// declaration with assignment

main()

, main():

int main() {.....}


main()
( )
:

int main(int argc, char* argv[]) {........}


( 4.4.3) :

int main(int argc, char** argv) {........}


, argc,
1 main()
( 0, ). , char, argc+1
C-style string . argv[0]
, argv[1], argv[2],. . . ,
,. . . , , argv[argc], 0. UNIX (
)
. , a.out

./a.out 12 input.dat output.dat 4.5


main(), , argc 5,
argv :

argv[0]
argv[1]
argv[2]
argv[3]
argv[4]
argv[5]

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

"./a.out";
"12";
"input.dat";
"output.dat";
"4.5";
0;

1 4 . main() .
C++ header <cstdlib> :

4.6. OVERLOADING

int atoi(char const * p);


long atol(char const * p);
double atof(char const * p);

77

// C-string to int
// C-string to long int
// C-string to double

strtod(). namespace std.


#include <cstdlib>
#include <fstream>
int
main(int argc, char *argv[]) {
int n = std::atoi(argv[1]);
// n gets the value of the first argument
double x = std::atof(argv[4]);
// x gets the value of the fourth argument
std::ifstream filein(argv[2]);
// open input file. Name is given in argv[2].
std::ofstream fileout(argv[3]);
// open output file. Name is given in argv[3].
// ..........
}

4.6 overloading

(),
, .

. C++ (overloading)
,
, , .

. C++

double, float long double.
, compiler
( ) . , ,
. , (.. bool, char, short int
int, float double,. . . ). ,

4.

78

int double, double long double, void*, .


,
,
.
(
)
compiler
.

4.7

template

C++
templates ().


.
(swap). ,4 (int,
float,. . . ), (,
6). overloading .

:

void
swap(int & a, int & b) {
int const temp = b;
b = a;
a = temp;
}
void
swap(float & a, float & b) {
float const temp = b;
b = a;
a = temp;
}
void
swap(double & a, double & b) {
double const temp = b;
b = a;
a = temp;
}
4

std::swap() <algorithm>.

4.7. TEMPLATE

79

...
...


. C++
compiler ,
(template)
. template
:

template <typename T>


void swap(T & a, T & b) {
T const temp = b;
b = a;
a = temp;
}
template <typename T> (
) T (
) . ,
, . (
template):

template <typename X, typename Y, ... >.5


template <>
template
:

double a = 2.0;
double b = 3.0;
swap<double>(a,b);
template

. swap(a,b).
, template
(int, char, bool,. . . ) ,

5
Standard

1998 C++ template


,
,
..

template <typename X,typename Y = double>.



.

4.

80

enum.6
, ..,
.
( ) :
bool mult(int a, int b) {
return !(a%b);
}
, mult(a,b). , b
, template:

template<int b>
bool mult(int a) {
return !(a%b);
}
mult<b>(a).

template.
template . header
template.

4.7.1

template (.. )
,
compiler . ..
swap() XOR swap
.
swap() :

template<>
void
swap(int & x, int & y) {
x^=y;
y^=x;
x^=y;
}
, swap<int>(a,b) (, ,
swap ) ,
.
6

4.8. INLINE

81

4.8 inline

,
. C++ compiler

, ,
. . compiler
inline
. ,
:

inline int
max(int a, int b) {
return a > b ? a : b;
}
, , inline main().
inline
compiler , . , header
.

4.9

. ,
.

(0 )
, ,
.
static:

void
func(double a) {
static int howmany = 0;
// .....
++howmany;
}
howmany . func().

4.

82


: compiler static,

( 0 ).
, , , (}), .
, , ,
( ).
( ) 7 .

4.10

C++

C++ .
header <cmath>
float, double, long double. 4.1 double. ,

<cstdlib>. C
C++ .
namespace std.

. compiler
.
,
, .

, errno <cerrno>
EDOM. , errno
ERANGE:

#include
#include
#include
#include

<cerrno>
<cmath>
<limits>
<iostream>

int main() {
errno = 0; // clear error. No error code is 0.
std::sqrt(-1.0);

// here errno becomes EDOM.

if (errno == EDOM)
7

std::abort().

cosh(double)
sinh(double)
tanh(double)
exp(double)
log(double)
log10(double)
modf(double d, double *p)
frexp(double d, int *p)

ldiv_t div(long int n, long int d)

n/d.

n/d.

overloaded long int.


quot,rem
div_t.
quot,rem
ldiv_t.

y *p.
d.

.
.
*p.

.
a>0 x=0
a x<0.
i>0 x=0.
rad.
rad.
rad.
[1 : 1],
[0 : ] rad.
[1 : 1],
[/2 : /2] rad.
[/2 : /2] rad.

. [ : ] rad.

4.1: <cmath> <cstdlib>.

<cstdlib>

.
.
.
.
(ln).
(log).
d.
x [0.5, 1) y d = x 2y .
x.
d/m.
d 2i .

int abs(int)
div_t div(int n, int d)

double fmod(double d, double m)


double ldexp(double d, int i)

double
double
double
double
double
double
double
double

.
arctan(x/y).

double atan(double)
double atan2(double x, double y)

, x i .
.
.
.
.
.

pow(double x, int i)
cos(double)
sin(double)
tan(double)
acos(double)

.

.

.
.
, x a .

<cmath>

double asin(double)

double
double
double
double
double

double sqrt(double)
double pow(double x, double a)

double floor(double)

double abs(double)
double ceil(double)

4.10. C++
83

4.

84

std::cerr <<
"argument out of domain of function.\n";
std::pow(std::numeric_limits<double>::max(), 2.0);
// here errno becomes ERANGE.
if (errno == ERANGE)
std::cerr << "Math result not representable.\n";
}
, std::strerror() header <cstring>. errno
char * ,
.

4.11
4.11.1

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

Bubble sort
. O (n 2 ) :
1. , . , .

4.11.

85

2. .
, , .
3.
.
,
.
, !
Insertion sort
. O (n 2 )
( ) O (n ). :
1. ,
.
2. , ,. . .
( ), .
Quicksort
, , .
O (n 2 ) ( )
() O (n log n ). , :
Quicksort
1. , ( ).
2. .
.
3. . , .
.
4. .
5. - .

4.

86
Quicksort

1. , ( ).
2. , .
3.

.
: .


.
4. ,
.
5. ,
(
).
.
6. - ( ).
Mergesort
. O (n log n ).
mergesort:
1. 0 1 , . :
2. .
3. () mergesort.
4. .

4.11.2

1.
() .

4.11.

87

() () .
;
() .
() .
() .
()
.
() [a, b] .
() P
, i ai bi .
2.
() ex

ex =

X
xn
n =0

n!

() sin x

sin x =

X
(1)k x 2k +1
k =0

(2k + 1)!

() cos x

cos x =

X
(1)k x 2k
k =0

(2k )!



.


.
3. C++
Legendre, P` (x ). P` (x ) x [1, 1], .
P0 (x ) = 1 P1 (x ) = x, `
:
`P` (x ) = (2` 1)xP`1 (x ) (` 1)P`2 (x ) .

4.

88

4. Cliff Pickover 8 :
Xn +1 = |100(ln(Xn )

(mod 1))|

X0 = 0.1.
5.
A N 9

det A =

N
X
(1)i +j aij det e
Aij ,
i =1

j, .. 1. A i j
aij , e
Aij A
i j .
6.
Cramer 10 .
7.
( )
n`m (r, , ) = Rn` (r )Y`m (, ) .
,

s
Y`m (, ) =

2` + 1 (` m )!
4

(` + m )!

P`m (cos )eim .

Legendre, P`m (x ),
` = m
P`m (x ) = (1)m 1 3 5 (2m 1) (1 x 2 )
` = m + 1

m/2

m
P`m (x ) = x (2m + 1)Pm
(x ) ,

(` m )P`m (x ) = x (2` 1)P`m1 (x ) (l + m 1)P`m2 (x ) .


[0, ] [0, 2 ) .
8

http://mathworld.wolfram.com/CliffRandomNumberGenerator.html
http://mathworld.wolfram.com/DeterminantExpansionbyMinors.html
10
http://mathworld.wolfram.com/CramersRule.html
9

4.11.

89


.
Legendre, P`m (x ).
, Y`m (, ).
50 100
Y`m (, ). ylm_data sin cos ,
(, ) (, , x, y, z, )
sin sin , cos , Y`m (, )Y`m
, ` = 2, m = 0 (, d-).
8. Hermite, Hn (x ), x.
:
Hn (x ) 2xHn 1 (x ) + 2(n 1)Hn 2 (x ) = 0 ,

n2,

H0 (x ) = 1, H1 (x ) = 2x.
( m V = kx 2 /2)
( )

s
n (y) =

Hn (y)ey

2n n !

/2

(4.1)

y = x
km/~.
Hermite
( ) (4.1).
n, x. m = k = ~ = 1.
harmonic.dat n = 5 60 x [6 : 6],
x ( , x
).
9. C++ ( )
f (x ) = 0 [xa , xb ] f (x ). :
() 11 . ,
.
11

http://mathworld.wolfram.com/Bisection.html

4.

90

() 12 . ,
,
f (x ).

.
() Brent 13 . ,
, , . .
10. C++ .
,
3 3 , , N N , (.. x o)
(, , N -)
, , . , .

.
. ,
, , , ,
.

x|o|x
--| |o
--o|x|
, , ( )
.
11. C++ four-in-a-row
. , M N ( 7
6 ).
.

, .
, .

12
13

http://mathworld.wolfram.com/MethodofFalsePosition.html
http://mathworld.wolfram.com/BrentsMethod.html

4.11.

91


.
. ,
( ).
, .
12. Sudoku. C++ sudoku.
9 9
, 3 3
1 9, ( ).

, .
:
()
1.
() . , 2, 3, .
. , .
()
. 1 9,
.
, . , , , ...

4.

92

5
6

3
1
9

8
4
7

7
9

6
6
8

3
1
6

3
2

2
4

1
8

9
7

5
9

13. N . N N
N
, .
.
.

.
:
N N .
board. 0
.
N ..
column. ( i
column[i]).

, (, ,
)
board. , ( 0)
( 1).
.

. 1
,
.
.
.
, ,
.
.

4.11.

93

,
, . .
,
(N N , 1 0.).
14. 5 5 .
,
( , ,
). .

. , ,
,

.

( )
. ,
( )
.

.

. .
.
15. fractal : , (x = 0, y = 0),
(x 0 , y0 )
x0
y

= ax +by+e
= cx +dy+f

a, b, c, d, e, f .

fractal (, x 0 x y0 y
(x 0 , y0 )). .
(x, y) , fractal.
:

4.

94

() "in.dat" 4 .
7 : 6
a, b, c, d, e, f p
.
P
. ,
pi ,
1.
() r [0, 1).
. , 0 r < p1
, p1 r < p1 + p2 .
() 1000
"fractal.dat".
"in.dat"
0
0.85
0.2
0.15

0
0.04
0.26
0.28

0.16

0.04 0.85 0
0.23
0.26

0.22
0.24

0
0

0
1.6
1.6
0.44

0.01
0.85
0.07
0.07

0
0.95
0.035
0.04

0
0.005
0.2
0.2

0.25

0.005 0.93
0.16
0.16

0.04
0.04

0.4

0.002
0.09

0.5
0.02
0.12

0.083

0.02
0.84
0.07
0.07

, "fractal.dat" .
16. f (x ), ,
x f (x ) (f (x ) =
0), Mller.
() x0 , x1 , x2
.
()
x2 x1

= q (f (x2 ) f (x1 )) q2 (f (x1 ) f (x0 )) ,

= (q + 1) (f (x2 ) f (x1 )) + A ,

= (q + 1)f (x2 ) .

x1 x0

()
x3 = x2

2C(x2 x1 )
D

4.11.

95

D
B +

B2 4AC, B B2 4AC.
()
16.
() x0 x1 , x1 x2 , x2 x3 .
16.

() .
, xn , q, A, B, C, D
.
Mller,
f (x ) = x 3 x + 1.
17. C++ .
18. C++ .
.
,

.
19.
std::swap() std::min(), std::max() STL,
5.1.3.
20. std::vector<double> (
<vector>) , ,
(<, ) (=, )
([], subscripting).
21. std::sort() STL <algorithm>.
22. dlasrt() lapack14 .

14

96

4.

Standard Library
C++ ,
, .
( 6) (templates, 4.7, 6.3),
Standard Library (STL).
STL :
containers, , .
. containers
(.. set, map) (.. vector, deque)
(.. map).
iterators, container.
iterators containers , .
container
.
,
, container
. iterators.
, STL (adapters)
(function objects), .
97

5. STANDARD LIBRARY

98

containers (container adapters) bitset,


STL, .

STL headers (.. / , , , , ...) . C,
.
STL.
, containers
.

5.1
5.1.1


(Pair)

STL containers .
, header <utility> , ,
std::pair<T1,T2>. class template
T1,T2 .
first second. (..
T1 int T2 double)
:

std::pair<int, double> p1;


// p1 == (0, 0.0)
std::pair<int, double> p2(3, 2.0);
pair :

std::pair<int, double> p(3, 2.0);


std::cout << "first element is " << p.first << " "
<< "second element is " << p.second << \n;
pair std::make_pair()

template <typename T1, typename T2>


std::pair<T1, T2>
make_pair(T1 const & f, T2 const & s);
<utility> :

std::pair<int, double> p; // p.first == 0, p.second == 0.0


p = std::make_pair(4, 3.0);
( 2.3), T1,T2.
first.

5.1.

99

, .
, second
.

5.1.2

containers , , ,
, ,
.
(function object functor). ,
. , (())
6.
header <functional>, C++
std . templates
. 5.1
.
.

negate<T>()
plus<T>()
minus<T>()
multiplies<T>()
divides<T>()
modulus<T>()
equal_to<T>()
not_equal_to<T>()
less<T>()
greater<T>()
less_equal<T>()
greater_equal<T>()
logical_not<T>()
logical_and<T>()
logical_or<T>()


1
1 + 2
1 2
1 2
1 / 2
1 % 2
1 == 2
1 != 2
1 < 2
1 > 2
1 <= 2
1 >= 2
!1
1 && 2
1 || 2

5.1: .

(adapters), 5.2. .. plus<T>()
. , ..

5. STANDARD LIBRARY

100

bind1st(functor,value)
bind2nd(functor,value)
not1(functor)
not2(functor)
ptr_fun(function)

functor(value,parameter)
functor(parameter,value)
!functor(parameter)
!functor(parameter1, parameter2)
function functor

5.2: .

constval
std::bind1st() :

std::bind1st(plus<T>(), constval)
,
( )
(!) .
ptr_fun(),
,
, 5.3.

5.1.3

header <algorithm> std::min<>(), std::max<>()


std::swap<>() templates. :

namespace std {
// minimum of a, b
template <typename T>
T const & min(T const & a, T const & b);
// maximum of a, b
template <typename T>
T const & max(T const & a, T const & b);
// b <-> a
template <typename T>
void swap(T& a, T& b);
}
min/max (<) . , ,
T
. 6
.

5.2. (CONTAINERS)

101

T (<)

min/max :

( ). min/max
:

namespace std {
// minimum of a, b based on cmp(a,b) ordering
template <typename T, typename Compare>
T const & min(T const & a, T const & b, Compare cmp);
// maximum of a, b based on cmp(a,b) ordering
template <typename T, typename Compare>
T const & max(T const & a, T const & b, Compare cmp);
}
,
std::min<>, :

template <typename T, typename Compare>


T const & min(T const & a, T const & b, Compare cmp) {
return cmp(a,b) ? a : b;
}
cmp(a,b)
true false
(, ) .
cmp

template<typename T>
bool cmp(T const & a, T const & b);
, cmp
(()), 6.

5.2
5.2.1

(containers)

containers . container , .
container, ,
C ( C++), (array). C++

( malloc, calloc, realloc,

102

5. STANDARD LIBRARY

new).
, containers.
containers :
sequence containers
.
. ..
container , container . STL
sequence containers: vector,
deque list. , string
containers .
associative containers

. STL
associative containers: set, multiset, map
multimap.
associative container containers
. sequence containers .
containers class template (6.3).
container
. map multimap

. associative containers
.
(true/false)
.
std::less<T> (5.1.2)
(<). , ,
.
container
header: <vector>, <deque>, <list>,
<set> ( set multiset) <map> ( map multimap). containers, STL,
std.
containers
, . ,

5.2. (CONTAINERS)

103

,
, ,
.
container
containers . c ( ) set
v vector :

#include <set>
#include <vector>
#include <complex>
std::set<int> c;
std::vector<std::complex<double> > v;
// use c, v ........
> v
>>.
,
containers:
cntr container (vector, list, map,. . . ).
, <T>
template container ( , , .).

cntr<T> c1;
c1 cntr.

cntr<T> c2;
// fill c2 ....
cntr<T> c3(c2);
c2 cntr, (
) c3 c2,
. c2, c3 .
template.
iterator. ,
.. beg, end iterators () container
beg end,

5. STANDARD LIBRARY

104

container ( ),
[beg,end):

cntr<T1> c4;
// fill c4 ...
// set beg, end on c4
cntr<T2> c5(beg,end);
// creates c5 by copying the elements of c4
// from beg to (one before) end.
T1, T2
T1 T2.
.. T2double, T1int (
int double) T1std::complex<double>.

containers iterators . .. vector :

#include <vector>
double a[5] = {0.1, 0.2, 0.5, 0.3, 7.2};
std::vector<double> v(a, a+5);
(4.3)
n n
. , a a[0] a+5
( a[4]).
, , container.
containers
containers . 5.3. reverse iterator rbegin() reverse iterator rend()
container .
container
(.) container (
). .., vector
c,

std::vector<double> c;
, ,
:

5.2. (CONTAINERS)

105

size()
empty()

.
true/false container .
( size()==0 )

( ).
container
container .
( container ).
iterator
iterators .
.
iterator .
iterator .
reverse iterator .
reverse iterator .

max_size()
swap()
clear()
erase()
insert()
begin()
end()
rbegin()
rend()

5.3: containers STL.

std::cout << "Size of argument is " << c.size() << \n;


container
==, !=, <, >, <=, >= . containers
, .
:
1.
.
containers.
2. , container .
3. containers .
container
container
:
container, :

c1 = c2;
c1
c2. c1
c2.
.

5. STANDARD LIBRARY

106

container
std::swap() <algorithm>:

std::swap(c1,c2);
, , swap()

c1.swap(c2);
- insert():

c.insert(pos, elem);
elem
( sequence containers) ( associative containers)
iterator pos. associative containers

, ,
.
iterator .
insert() .
:
erase()
:

c.erase(pos);
c.erase(beg,end);
iterator pos iterators [beg,end)
(, , c). c sequence container iterator
associative containers .
clear(). container. ( void):

c.clear();
, container .

5.2.2 Iterators
,
iterators
containers.

5.2. (CONTAINERS)

107

iterator
. iterator
,
(*) iterator
. , *it
, container, iterator it.
, iterator
(&) . STL containers.
, .. it, iterator container (.. vector)
:

std::vector<double>::iterator it;
pointers iterators
. Iterator
:

std::vector<double>::const_iterator it;
, it
const ( ) .
rbegin() rend()
container. (reverse) iterator. ( ) container containers.
iterator. ,
, iterator, .. vector, :

std::vector<double> v(10);
std::vector<double>::reverse_iterator rit = v.rbegin();
, const_reverse_iterator
iterators .
:
container, .. std::vector<double>
v, (
5.3 begin(), end()):

for (std::vector<double>::const_iterator cit = v.begin();


cit != v.end();
++cit)
std::cout << *cit << \n;

for (std::vector<double>::const_reverse_iterator crit = v.rbegin();


crit != v.rend();

5. STANDARD LIBRARY

108

++crit)
std::cout << *crit << \n;
, .. 3, std::vector<int>
v

for (std::vector<int>::iterator it = v.begin(); it != v.end();


++it)
*it = -3;
iterators :
random ( ) iterators. ,
:
( 2.3), ++it it , iterator
, random iterators container
, . iterators vector
deque .
bidirectional ( ) iterators. iterators :
1.
(==) (!=).
2. ,
++it --it (, , it++
it--). bidirectional iterator
, .
iterators list associative containers
.
,
containers, STL <iterator>

void advance(Iterator & it, Difference_type n);


n .1 iterator it random,
it += n;. bidirectional
n ++it ( n>0) --it ( n<0).

1

std::iterator_traits<InputIterator>::difference_type.

5.2. (CONTAINERS)

109

Difference_type distance(Iterator it1, Iterator it2);


it1, it2 iterators container. random it2-it1 bidirectional
it1 it2
. , it1
it2.

container container , , ,
template. ..,

template<typename T, typename C>


void
f(C & a) {
std::vector<T> v;
C b;
...
}
f std::vector
T C ( ,
.. std::list<int>). iterators

std::vector<T>::iterator itv;
C::iterator itl; // error

// error

C::iterator
std::vector<T>::iterator . iterators typename:

typename std::vector<T>::iterator itv;


typename C::iterator itl; // correct

// correct

5.2.3 vector
vector . sequence container,
. vector . ,
, ,
. :
vector
container. ,
.

5. STANDARD LIBRARY

110

vector .

vector ,
, , , . , , iterators
.
vector (array),
( ) , , / . , ,
.
vector
.
std::vector header
<vector>.

vector .
.

std::vector<T> v;
vector.

std::vector<T> v(N);
v vector N T.
T(), T.2 T
, 0 (2.2).

std::vector<T> v(N, elem);


v vector N elem.
, , elem T
.

2

constructor, 6.2.2.

5.2. (CONTAINERS)

111

std::vector<T> v1(v2);
v1 v2.

std::vector<T> v(beg,end);
v
iterators beg end.
vector vector size(), empty()
max_size() :
capacity()
vector ,
, .
reserve() .
vector .

vector. , ,
N T vector
,

std::vector<T> v;
v.reserve(N);
N push_back() ( ),

std::vector<T> v(N);
v[0], v[1], . . . , v[N-1].

container .
vector.

v1 = v2;
v2 v1 .

5. STANDARD LIBRARY

112

v.assign(N,elem);
v N elem , , v.

v.assign(beg, end);
v container ( ) iterators beg
end. beg
end container,
v beg
end.

v1.swap(v2);

std::swap(v1,v2);
v1, v2.

v.insert(pos, elem);
iterator pos,
elem iterator .

v.insert(pos, N, elem);
, iterator pos, N
elem, .

.

insert() iterators:

v.insert(pos, beg, end);


, iterator pos, vector v,
iterators beg (),
end ( ).

5.2. (CONTAINERS)

113

v.push_back(elem);

elem
vector. .
resize() . .

v.resize(N);
v N
.
.
,

v.resize(N,elem);
elem.

vector :
resize() .
clear().
erase(). container
, iterators

c.erase(beg,end);
sequence containers,
iterator, pos:

v.erase(pos);
iterator .
push_back() - pop_back(),
, :

v.pop_back();
, iterators
. , vector
, , iterators.

5. STANDARD LIBRARY

114

, vector :
([])
:

std::vector<double> v(3);
v[0] = 1.0;
v[1] = 3.0;
v[2] = v[1] + 5.0;
at() .
, , ,. . . vector v v.at[0], v.at[1],
v.at[2],. . . . [0:v.size()-1]
.3

.
front() back(). , ,
.
(*) iterator.
const_iterator
.
:
, vector
:

#include <iostream>
#include <vector>
#include <cstddef>
int
main() {
std::vector<double> v(10);
// v = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
// assign values
for (std::size_t i = 0; i < v.size(); ++i)
v[i] = 4.0 * i*i;
3

at().

5.2. (CONTAINERS)

115

std::vector<double> v2(v);
// v2 is a copy of v
// append more values to v2
std::size_t const size = v2.size();
for (std::size_t i = size; i < 2*size; ++i)
v2.push_back(4.0*i*i);
// print v2
std::cout << "v2 is\t";
for (std::vector<double>::const_iterator it = v2.begin();
it != v2.end();
++it)
std::cout << *it << ;
std::cout << \n;
}

std::vector<bool> ( container bool!).


std::deque<bool> bool (.. [1], . 158, [2], . 4145, [3], item 18)
.

5.2.4 deque
deque (double-ended queue)
vector. sequence container , vector,
.
, vector
, deque
. ,
.
std::deque header
<deque>.
deque
.
, vector

. , ,
vector, . deque
. ,

5. STANDARD LIBRARY

116

, iterator , .
deque
vector.
capacity() reserve() vector.
( )

deque , iterators
.
( iterators).
capacity() reserve(),
vector deque. , push_front() ( ) pop_front() ( ),
push_back() pop_back().
:
deque . .
iterator .

#include <deque>
#include <iostream>
int
main() {
std::deque<int> d;

// d is empty

for (int i = 0; i != 10; ++i)


d.push_front(i);
// d is : {9, 8, ..., 0}

int & r = d.front();


std::cout << "front element is " << r << \n;
std::deque<int>::iterator beg = d.begin();
std::cout << "front element through iterator is "
<< *beg << \n;
for (int i = 10; i != 10000; ++i)
d.push_front(i);
// d is : {9999, 9998, ..., 0}
// THE SAME AS BEFORE INSERTION
std::cout << "old front element is " << r << \n;
// NOT NECESSARILY THE SAME AS ABOVE

5.2. (CONTAINERS)

117

std::cout << "old front element through iterator is "


<< *beg << \n;
}

5.2.5 list
list, sequence container STL,
, vector deque. list
,
( )
, 5.1.

5.1: list.
,
vector deque, . ,
. ,
, sequence
containers ( ).
:
list ( 5.2)
.
, iterators .


6

6
?-


5.2: list.
std::list header <list>.

list
sequence containers. .
std::list<T> c;: .
std::list<T> c1(c2);: , .

118

5. STANDARD LIBRARY

std::list<T> c(N);: N T().


std::list<T> c(N, elem);: N
elem.
std::list<T> c(beg,end);:
[beg,end).

list :
c1 = c2;: c2 c1
.
c.assign(N,elem);: c N elem.
c.assign(beg,end);: c
iterators [beg,end).
c1.swap(c2); std::swap(c1,c2);:
c1, c2.
c.insert(pos,elem);: iterator
pos elem. iterator .
c.insert(pos,N,elem);: iterator pos N elem. .
c.insert(pos,beg,end);: iterator pos [beg,end). .
c.push_back(elem);: elem c.
c.push_front(elem);: elem c.
c.resize(N);: N c.
,
. .
c.resize(N,elem);: , elem.

5.2. (CONTAINERS)

119


list c, :
c.pop_back();: .
c.pop_front();: .
c.erase(pos);: iterator pos
iterator .
c.erase(beg,end);:
[beg,end) iterator .
c.clear();: c.
resize().

list :
front() back(). , ,
.
(*) iterator.
const_iterator
.

list, containers, size(), empty()
max_size() (5.2.1),
iterators, , capacity() reserve().
list
sequence containers:

c.remove(val);
c val.

c.remove_if(func);

5. STANDARD LIBRARY

120

, true false. remove_if()


list
func() true.
unique()
.
unique(func)
func() true.

c1.splice(pos, c2);
, iterator pos, c2, c2. c1, c2 list.

c1.splice(c1pos, c2, c2pos);


iterator c1pos c2 iterator
c2pos. c1, c2 .

c1.splice(c1pos, c2, c2beg, c2end);


iterator c1pos c2
[c2beg, c2end). c1, c2 .
sort()
(<).
std::sort() <algorithm>
, list.
sort(op)
true false.
.

c1.merge(c2);
c1 c2, c2 c1
, ,
.

5.2. (CONTAINERS)

121

c1.merge(c2, op);

op().
reverse()
list .
:

#include <list>
#include <iostream>
inline bool
lessthan10(double a) {
return a < 10.0;
}
int main() {
std::list<double> c;

// creates empty list

for (int i = 0; i != 10; ++i)


c.push_back(2.0 * i);
// c: {0.0, 2.0, 4.0, ..., 18.0}
c.remove(18.0);
// any element with value equal to 18.0 is erased.
c.remove_if(lessthan10);
// all elements with value less than 10 are erased.

std::cout << "List is :\t";


for ( std::list<double>::const_iterator it = c.begin();
it != c.end();
++it )
std::cout << *it << " ";
std::cout << \n;
}

c.remove_if(lessthan10);

c.remove_if(std::bind2nd(std::less<double>(), 10.0));

5. STANDARD LIBRARY

122

<functional>. , , lessthan10(),

.

5.2.6 set multiset


set multiset containers , .
, ,
.
containers multiset set
. , set
. , set
multiset.
containers,
, sequence containers
. (binary search)
associative containers O (log n )
sequence containers
O (n ).
std::set std::multiset <set>.

set T
.4 5.2.1
:

std::set<T> c;
set.

std::set<T> c1(c2);
set .

4

5.2. (CONTAINERS)

123

std::set<T> c(beg,end);
set container, , iterators
[beg,end).
, std::less<T> (<) (
). , template

, true/false,
. .. set

std::set<T, std::greater<T> > c;


template
.
, f(a,b), :
f(x,x) false.
f(x,y) true f(y,x) false.
f(x,y) f(y,z) true, f(x,z) true.
x y , f(x,y) f(y,x) false,
y z , f(y,z) f(z,y) false,
x z , f(x,z) f(z,x) false.

set :
c1 = c2;: c2 c1
.
c1.swap(c2); std::swap(c1,c2);:
c1, c2.
c.insert(elem);: set multiset c elem.
c multiset iterator .
c set (pair, 5.1.1),
iterator
bool
.

124

5. STANDARD LIBRARY

c.insert(pos,elem);: elem, iterator pos, iterator


.
c.insert(beg,end);: c [beg,end). .

set c :
c.erase(elem);: elem
c.erase(pos);: pos.
.
c.erase(beg,end);: iterators
[beg,end). .
c.clear();: c.

set . .
,
. iterator .

.

set multiset, containers,
size(), empty() max_size() (5.2.1),
iterators. ,

. :
count(elem): elem.
find(elem): iterator elem
, , end().

5.2. (CONTAINERS)

125

lower_bound(elem):
elem.
upper_bound(elem):
elem.
equal_range(elem): , , iterators elem.
:

#include <set>
#include <iostream>
#include <functional>
int
main() {
typedef std::set<int, std::greater<int> > Set;
// define empty set.
Set c;
// insert values in random order.
c.insert(5);
c.insert(12);
c.insert(3);
c.insert(6);
c.insert(7);
c.insert(1);
c.insert(9);
// print set
std::cout << "Number of elements in set: "
<< c.size() << \n;
for (Set::const_iterator it = c.begin(); it != c.end(); ++it)
std::cout << *it << " ";
std::cout << \n;
// remove elements with value 4, 6 and print information
int howmany = c.erase(4);
std::cout << "There were " << howmany
<< " elements with value 4\n";
howmany = c.erase(6);
std::cout << "There were " << howmany
<< " elements with value 6\n";

5. STANDARD LIBRARY

126

std::cout << \n;


typedef std::multiset<int, std::greater<int> > MSet;
// create multiset from c
MSet mc(c);
//insert element 12 three times
mc.insert(12);
mc.insert(12);
mc.insert(12);
// print multiset
std::cout << "Number of elements in multiset: "
<< mc.size() << \n;
for (MSet::const_iterator it = mc.begin();
it != mc.end(); ++it)
std::cout << *it << " ";
std::cout << \n;
}

5.2.7 map multimap


map multimap containers (5.1.1)
(first)
(second) . . containers
multimap
map . , map
multimap.
map set
map
.
std::map std::multimap <map>.

map .
, template, K,
, T,
.5
5

5.2. (CONTAINERS)

127

std::map<K,T> c;
map.

std::map<K,T> c1(c2);
map , .

std::map<K,T> c(beg,end);
map map, , iterators [beg,end).

, std::less<K>
(<) ( ). , template
, true/false,
.
set, 5.2.6.

map :
c1 = c2;: c2 c1
.
c1.swap(c2); std::swap(c1,c2);:
c1, c2.
c.insert(elem);: map multimap c elem.
elem pair , , (5.1.1). c multimap iterator
. c map ,
iterator bool
.
c.insert(pos,elem);: elem, iterator pos, iterator
.
c.insert(beg,end);: c [beg,end). .

5. STANDARD LIBRARY

128

map c :
c.erase(key);: key
.
c.erase(pos);: pos.
.
c.erase(beg,end);: iterators
[beg,end). .
c.clear();: c.

map .
. ,
.
iterator.
it iterator map (*it).first (, , it->first)
(*it).second (, , it->second) .
.
map (, multimap)
set
( []) . ,
,
. :
c map key c[key]
.
c map key

c[key] = value;
c make_pair(key,value). , ,
, ..

std::cout << c[key];


, key map.
.

5.2. (CONTAINERS)

129

:
, map .

#include
#include
#include
#include

<iostream>
<string>
<map>
<utility>

int
main() {
typedef std::map<std::string, int> Map;
Map birthyear;

// Empty map.

// insert a few pairs.


birthyear.insert(std::make_pair("John", 1940));
birthyear.insert(std::make_pair("Paul", 1942));
birthyear.insert(std::make_pair("George", 1943));
std::cout << "John was born in "
<< birthyear["John"] << "\n\n";
// insert new data
birthyear["Ringo"] = 1941; // wrong value, change it
birthyear["Ringo"] = 1940;
// print all pairs
for (Map::const_iterator it = birthyear.begin();
it != birthyear.end();
++it)
std::cout << it->first << " was born in "
<< it->second << \n;
}

map multimap,
(5.2.1), size(), empty() max_size()
iterators.

set/multiset:
count(key): key.
find(key): iterator key
, , end().
lower_bound(key): key.

130

5. STANDARD LIBRARY

upper_bound(key): key.
equal_range(key): , , iterators key.

5.3

(algorithms)

STL . ,
: , , , , .
containers.
iterators , ,
, containers . ,
: container , ,
. containers : , .. , random iterators
(5.2.2). containers.
.
header <algorithm>.
<numeric> . std.
iterators container .
iterator , ,
. iterator
.
container. iterator

container .
,
,
( UnaryFunctor)
( BinaryFunctor)6 .
:

accumulate, count.

5.3. (ALGORITHMS)

131

accumulate()
Type accumulate(Iterator beg, Iterator end, Type value)
Type accumulate(Iterator beg, Iterator end, Type value,
BinaryFunctor op)

[beg,end) value. {a1, a2, a3, . . . }

value + a1 + a2 + a3 + ...

.
<numeric>.
:
std::vector v
:

double sum = 0.0;


for (std::size_t i = 0; i < v.size(); ++i)
sum += v[i];
accumulate,

double sum = std::accumulate(v.begin(), v.end(), 0.0);


v,

double prod = 1.0;


for (std::size_t i = 0; i < v.size(); ++i)
prod *= v[i];
, ( )

double prod = std::accumulate(v.begin(), v.end(), 1.0,


std::multiplies<double>());
accumulate , 5.1.2.

partial_sum()
Iterator
partial_sum(Iterator beg1, Iterator end1, Iterator beg2)
Iterator
partial_sum(Iterator beg1, Iterator end1, Iterator beg2,
BinaryFunctor op)

132

5. STANDARD LIBRARY

(
) ( ).
:
beg2 beg1
beg2+1 beg2
beg1+1
beg2+2 beg2+1
beg1+2, .
[beg1,end1).
,
op(), ,
beg2+i+1 op(*(beg2+i), *(beg1+i+1)).
beg2 container beg1,
end1.
<numeric>.

inner_product()
Type
inner_product(Iterator beg1, Iterator end1,
Iterator beg2, Type value)
Type
inner_product(Iterator beg1, Iterator end1,
Iterator beg2, Type value,
BinaryFunctor op1, BinaryFunctor op2)
value
[beg1,end1)
beg2. {a1, a2, a3, . . . } {b1, b2, b3,
. . . }

value + a1 * b1 + a2 * b2 + a3 * b3 + ...

, op1(), op2().

value op1 (a1 op2 b1) op1 (a2 op2 b2) op1 (a3 op2 b3) + ...
<numeric>.

for_each()
UnaryFunctor
for_each(Iterator beg, Iterator end, Unaryfunctor op)

5.3. (ALGORITHMS)

133

op() [beg,end). op().



op(). ,
.

count()
Difference_type
count(Iterator beg, Iterator end, Type const & value)
Difference_type
count_if(Iterator beg, Iterator end, UnaryFunctor op)
[beg,end)
value. associative containers
.

op() true.
Difference_type 1 .
:
a, std::vector
v , :

std::size_t cnt = 0;
for (std::size_t i = 0; i < v.size(); ++i)
if (v[i] == a)
++cnt;
( )
count :

std::size_t cnt = std::count(v.begin(), v.end(), a);


, count_if, . v a,

std::size_t cnt =
std::count_if(v.begin(), v.end(),
std::bind2nd(std::less<double>(), a));
, 5.2, :
std::less<double>()
a std::bind2nd().

134

5. STANDARD LIBRARY

min_element()
Iterator
min_element(Iterator beg, Iterator end)
Iterator
min_element(Iterator beg, Iterator end, BinaryFunctor op)
iterator (
) [beg,end).
(<)
op(), .

max_element()
Iterator
max_element(Iterator beg, Iterator end)
Iterator
max_element(Iterator beg, Iterator end, BinaryFunctor op)
iterator ( ) [beg,end). (<)
op(),
.

find()
Iterator
find(Iterator beg, Iterator end, Type const & value)
Iterator
find_if(Iterator beg, Iterator end, UnaryFunctor op)
iterator
[beg,end) value. associative containers
.
iterator
op() true.
end
.
[beg,end) ,
(lower_bound(), upper_bound(),
equal_range(), binary_search()).

5.3. (ALGORITHMS)

135

equal()
bool
equal(Iterator beg1, Iterator end1, Iterator beg2)
bool
equal(Iterator beg1, Iterator end1, Iterator beg2,
BinaryFunctor op)
true [beg1,end1)
beg2.
, false.

op(), .
, op() false, equal
false true.

copy()
Iterator
copy(Iterator beg1, Iterator end1, Iterator beg2)
[beg1, end1)
beg2. iterator
.
beg2 container
[beg1, end1).

copy_backward()
Iterator
copy_backward(Iterator beg1, Iterator end1, Iterator end2)
[beg1, end1) end2, . iterator
.
end2 container
[beg1, end1).

swap_ranges()
Iterator
swap_ranges(Iterator beg1, Iterator end1, Iterator beg2)
[beg1, end1)
beg2 ( [beg2, beg2+(end1-beg1))).

136

5. STANDARD LIBRARY

transform()
Iterator
transform(Iterator beg1, Iterator end1, Iterator beg2,
UnaryFunctor op)
Iterator
transform(Iterator beg1, Iterator end1, Iterator beg2,
Iterator beg3,
BinaryFunctor op)
op()
[beg1,end1)
beg2. beg1, beg2 .
beg2 (beg1,end1).
op()
[beg1,end1)
beg2
beg3. beg1, beg2, beg3 .
iterator
.

fill()
void
fill(Iterator beg, Iterator end, Type const & value)
void
fill_n(Iterator beg, Size N, Type const & value)
value [beg,end).
value N
beg.

generate()
void
generate(Iterator beg, Iterator end, Functor op)
void
generate_n(Iterator beg, Size N, Functor op)

op() ( ) [beg,end).
op() N
beg.

5.3. (ALGORITHMS)

137

replace()
void
replace(Iterator beg, Iterator end,
Type const & oldvalue, Type const & newvalue)
void
replace_if(Iterator beg, Iterator end,
UnaryFunctor op, Type const & newvalue)
newvalue [beg,end)
oldvalue. op
true.

replace_copy()
void
replace_copy(Iterator beg1, Iterator end1, Iterator beg2,
Type const & oldvalue, Type const & newvalue)
void
replace_copy_if(Iterator beg1, Iterator end1, Iterator beg2,
UnaryFunctor op, Type const & newvalue)
[beg1,end1)
beg2 newvalue oldvalue.

op true.

remove()
Iterator
remove(Iterator beg, Iterator end, Type const & value)
Iterator
remove_if(Iterator beg, Iterator end, UnaryFunctor op)
[beg,end)
value.
op true.
.
iterator . , beg
iterator .
,
associative containers.
(erase()).

138

5. STANDARD LIBRARY

list (remove())
.

reverse()
void
reverse(Iterator beg, Iterator end)
[beg,end).
list .

reverse_copy()
Iterator
reverse(Iterator beg1, Iterator end1, Iterator beg2)
[beg1,end1) beg2.
container.

merge()
Iterator
merge(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3)
Iterator
merge(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3,
BinaryFunctor op)
[beg1,end1)
[beg2,end2) beg3, . op()
true false
.

container.
list .

set_union()
Iterator
set_union(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3)
Iterator

5.3. (ALGORITHMS)

139

set_union(Iterator beg1, Iterator end1,


Iterator beg2, Iterator end2, Iterator beg3,
BinaryFunctor op)
merge()
. ,
.

set_intersection()
Iterator
set_intersection(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator
set_intersection(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3, BinaryFunctor op)
merge()
.

set_difference()
Iterator
set_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator
set_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3, BinaryFunctor op)
merge()

.

set_symmetric_difference()
Iterator
set_symmetric_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator

140

5. STANDARD LIBRARY

set_symmetric_difference(Iterator beg1, Iterator end1,


Iterator beg2, Iterator end2,
Iterator beg3, BinaryFunctor op)
merge()

.

binary_search()
bool
binary_search(Iterator beg, Iterator end, Type const & value)
bool
binary_search(Iterator beg, Iterator end, Type const & value,
BinaryFunctor op)
true false
[beg,end) value.
, op(),
,
.

sort()
void
sort(RandomIterator beg, RandomIterator end)
void
sort(RandomIterator beg, RandomIterator end,
BinaryFunctor op)
[beg,end). ,
(<)
op(),
.
.
random iterators list. list
list.

stable_sort()
void
stable_sort(RandomIterator beg, RandomIterator end)
void

5.4.

141

stable_sort(RandomIterator beg, RandomIterator end,


BinaryFunctor op)
sort()
.

partial_sort()
void
partial_sort(RandomIterator beg, RandomIterator sortEnd,
RandomIterator end)
void
partial_sort(RandomIterator beg, RandomIterator sortEnd,
RandomIterator end, BinaryFunctor op)
sort()
[beg,sortEnd)
.

random_shuffle()
void
random_shuffle(RandomIterator beg, RandomIterator end)
[beg,end).
random iterators list associative containers.

5.4

1. 1000000
[1000000, 1000000].
2. , container .

() .
() 1234. ;
.
() .
() 0.
() .
() 0.

142

5. STANDARD LIBRARY
() 10000
10000.
() 100 .
template
container;
containers vector, deque, list, set; containers ( clock()7
<ctime>). ;

3.
list: unique(), splice(), merge(), reverse().
4. STL.
, interface, iterators.
. ;
5. quicksort, 4.11.1, container iterators. , ,

template<typename Iterator>
void
quicksort(Iterator beg, Iterator end) {
...
}
6.

typedef std::list<int> container;


void
split(container const & c, container & odd,
container & even){
...
}
container c
, , ,. . . ,
container odd , , ,. . . ,
container even.
, std::list<int> 3, 5, 1, 9, 7, 88, 3, 6, 4
a, b
split. , ,
7

Unix man 3 clock .

5.4.

143

. a
odd.dat b
even.dat.
7.

() std::equal()
equal. , ,

template<typename Iterator>
bool
equal(Iterator beg1, Iterator end1, Iterator beg2) {
.....
}
() std::list,
1, 3, 5, 88, 92, 4, 91
1, 3, 5, 88, 92, 4, 2, 91 .
equal() ( false).
8. .
( )
( , ,
).
9. :
, , ( ), , , .
,
.

144

5. STANDARD LIBRARY

6.1

C++
(object based) (object
oriented programming). , ,

, .

6.1.1

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

std::size_t const N = 50; // number of students


std::string studentName[N];
int studentAM[N];
int studentYear[N];
// .......
145

146

std::size_t const M = 500;


std::string bookTitle[M];
std::string bookAythor[M];
int bookYear[M];
// .......

6.

// number of books


( ) , ,
.

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

.
: ,
!
C++
struct, 2.6.2,

struct Student {
std::string name;
int AM;
int Year;
// ......
};
struct Book {
std::string title;
std::string author;
int year;
// ......
};

6.1.

147

, , , .
() :

std::size_t const N = 50;


std::size_t const M = 500;
Student students[N];
Book
books[M];

6.1.2

(encapsulation)

students, books ,
students books. ,

std::cout << "Name: " << students[10].name


<< "AM: "
<< students[10].AM
<< "Year: " << students[10].year
......
,


(
,
, .).
.

.

(.. )
Student
Book.

int printStudent(Student const & s);


int printBook(Book const & c);

, . . , , ,

148

6.

. Student Book.
( )
( encapsulation). .
C++ struct
C
, .
, class struct
, (
) , :
,
, .1

class Student {
std::string name;
int AM;
int Year;
// ......
public:
int print() {....}
// the old printStudent
std::string getName() {....}
int getAM() {....}
int getYear() {....}
// ......
};

class Book {
public:
int print() {....} // the old printBook
std::string getTitle() {....}
std::string getAuthor() {....}
int getYear() {....}
// ......
private:
std::string title;
std::string author;
int year;
// ......
1
struct
.

6.1.

149

};
. (
, ) printStudent()
printBook() (
) (

).
struct (.).
. , print()
s Student :

Student s;
// .... give values to s
s.print();
s
print() .
,
public: (
) ( )
. ,
{
private:
.
, ,
.
, ..

class Student {
std::string name;
int AM;
// ......
public:
std::string getName() {return name;}
void setAM(int i) { AM = i;}
// ......
};

6.1.3


, -

150

6.

, , , . . , ,
, ,
. ..,

(, , .) ,
() .
.

. , ,
, , , ( , inheritance) . , ,

. , , ( ), ,
( ),
.
( ) ,
, , ,
. ( polymorphism).

,
.
, ,
. ,
(
)
.

C++ .

6.2.

6.2

151

,
( ), :
.
, . ,
( ).
, 2.5.4, : ()
().
. , ( )
. , ,
.
,

, ,
. .
.

-

- .
.
.
, ,

.

, , Student
.

6.

152

class Student {
public:
Student(char const * onoma, int am, int y)
: name(onoma), AM(am), Year(y) {}
Student() {}
Student(Student const & other);
Student & operator=(Student const & other);
int print() const {
std::cout << name << << AM << << Year << \n;
return 0;
}
std::string const & getName() const {return name;}
int getAM() const {return AM;}
int getYear() const {return Year;}
void setName(char const * s) {name = s;}
void setAM(int am) {AM = am;}
void setYear(int y) {Year = y;}
private:
std::string name;
int AM;
int Year;
};

6.2.1

( , )
class struct,
, {}, (
). (;)
.
, name, AM, Year,
. private:
. , , print(), getName(), getAM(), getYear(), setName(), setAM(), setYear()
, public:.
,
.2 , ,
.
2

protected:, .

6.2.

153

private:
class public: struct.
,
class.
setName(), setAM(), setYear(), .
. ,
.

. , , const
. ,
getName(), getAM(), getYear(),
, const
( ). ( const)
. , s Student,

Student & s1 = s;
Student const & s2 = s;
s1.setYear(2000);
s2.setYear(2000);

// correct
// error

int y = s1.getYear();
int z = s2.getYear();

// correct
// correct

setYear() s1 s2
. getYear()
.
,
const ,

const.
,

, private ,
, public
.
, , , (, ,
public) . ,

154

6.

. ,
Student print() setYear()
:

class Student {
public:
// ............
int print() const;
void setYear(int y);
// ............
private:
std::string name;
int AM;
int Year;
};

int
Student::print() const {
std::cout << name << << AM << << Year << \n;
return 0;
}
inline
void
Student::setYear(int y) {
Year = y;
}

, .


( Student::).

inline, 4.8 ,
inline .

header
(.. Student.h) ( inline
template, 4.8 4.7) (.. Student.cc)
. ,
( #include "Student.h")
header .

6.2.

6.2.2

155

(ConstructorsCopy constructor)

, , ,
:
Student(char const * onoma, int am, int y),
Student()
Student(Student const & other).
Student ( ), ( )
Student ( ).
, .
( ) constructors () copy constructor
( ) .
(constructor)
:

Student(char const * onoma, int am, int y)


: name(onoma), AM(am), Year(y) {}
,
. .
constructors
.
.

Student s("George Thomson", 123, 2000);


, , Student s, char const *, int, int (
). Student, s,
name, AM, year. constructor, ,

std::string name(onoma);
int AM(am);
int Year(y);

6.

156


,
constructor.

Student(char const * onoma, int am, int y) {


name = onoma;
AM = am;
Year = y;
}

std::string name;
name = onoma;
int AM;
AM = am;
int Year;
Year = y;
: name, AM, Year, name ""
. , . ,
. , const
, .
,
constructor (:)
.
, constructors, ( ), 4.6.
Student(){}.
constructor . , Student,
name "" . Student
:

Student s;

// calls constructor Student()

Student s(); //function declaration, does not call Student()


s
Student.

6.2.

157

constructor , constructor , X X(){}.


(copy constructor)
Student(Student const & other) copy
constructor
Student .
() t1 t2:

Student s("George Thomson", 123, 2000);


Student t1(s);
Student t2 = s;
, copy constructor
. ,

void f(Student t);


copy constructor Student:

Student s("George Thomson", 123, 2000);


f(s);
Student s f, Student t (
) s

Student t(s);
t .
, 4.2,
, ,
.
copy constructor
,
copy constructor.
copy constructor
. ,
return3 .
X copy constructor, ,
3

return.

6.

158

, copy constructor, (X(X const & other)),



.
, 4.3, ( ) (..
ifstream, ofstream),
copy constructor.

6.2.3

(Destructor)

Student(){} destructor ()

Student. static
(4.9),
4 .
destructor .
destructor, X
, X(){}.
, destructor destructors (
) , .
destructor
,
.

6.2.4

(assignment operator)

,
,
(=,+,<, .). =

.
, , . ..

Student s("George Thomson", 123, 2000);


Student t;
t = s; // operator= is called.
t=s; t.operator=(s);.

return exception.

6.2.

159

Student & operator=(Student const & other);


. , . ,
s, , t.
, .
, , ( )
.
. , t=t
t . , -.
,
operator= Student

Student &
operator=(Student const & other){
if (this != &other) {
name = other.name;
AM = other.AM;
Year = other.Year;
}
return *this;
}
this
operator=. if
other . , . ,
,
a=b=c=d, .
, : , , .
.

6.2.5

(=) , . , ,
. ,
.

6.

160

operator. 2.4 (
)
(.)
(sizeof).

6.3

template


. ,
X T
template<typename T>:

template<typename T>
class X {
T a;
...
...
};
( , )
T .
, a T. X T :

X<double> x1;
X<int>
x2;
, x1.a x2.a .
template .
.., , Y
,

template<int n>
class Y {
double v[n];
};
Y template:

Y<10> c;
c.v, , 10 .
X
,
template<typename T>
<T>:

6.4.

161

template<typename T>
class X {
T a;
...
void f(T v);
};
template<typename T>
void
X<T>::f(T v) {
...
}

6.4

1. Book .
2.
. date interface
date.h.
:

#include <iostream>
#include "date.h"
int
main() {
date
date
date
date
date
date
date
date
date
date

a;
b(1996);
c(5,2003);
d(14,5,2005);
e(d);
const f(d+3);
g(d+30);
h(d-30);
i(32,5,2000);
j(12,13,2000);

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

a
b
c
d
e
f
g
h
i
j

=
=
=
=
=
=
=
=
=
=

January 1, 2000
January 1, 1996
May 1, 2003
May 14, 2005
d (May 14, 2005)
May 17, 2005
Jun 13, 2005
April 14, 2005
June 1, 2000
January 12, 2001

<< h.day()
std::cout << "h day is "
<< "h month is " << h.month()
<< "h year is " << h.year();
h.add_year(2);
h.add_month(2);
h.add_day(2);

// h = April 14, 2007


// h = June 14, 2007
// h = June 16, 2007

std::cout << "f day is "


<< f.day()
<< "f month is " << f.month()

6.

162

<< "f year is "

<< f.year();

std::cout << j.to_string();


// prints to std::cout : January 12, 2001
int k = d-c;
++a;
--c;

// k = 366 + 365 + 13 = 744

// a = January 2, 2000
// c = April 30, 2003

if (c > a)
std::cout << c.to_string() << "is after "
<< a.to_string() << \n;
if (c == a)
std::cout << c.to_string() << "coincides with "
<< a.to_string()<<\n;
if (c < a)
std::cout << c.to_string() << "is before "
<< a.to_string() << \n;

d += 4;
g -= 3;
i = g;

// d = May 18, 2005


// g = Jun 10, 2005
// i = Jun 10, 2005

}
3.
3 . , ,
, , ,

.
4. (,
template<typename T> complex<T> std::complex STL.


. . . !
, , C
. C++
.
1 .
Raymond Cheong 2001, .1.
( ).
Michael Savastio 1995, .2.
429539.
Ken Huffman 1996, .3.
Braille .
#include <stdio.h>
int l;int main(int o,char **O,
int I){char c,*D=O[1];if(o>0){
for(l=0;D[l
];D[l
++]-=10){D
[l++]-=120;D[l]-=
110;while
(!main(0,O,l))D[l]
+=
20;
putchar((D[l]+1032)
/20
)
;}putchar(10);}else{
c=o+
(D[I]+82)%10-(I>l/2)*
(D[I-l+I]+72)/10-9;D[I]+=I<0?0
:!(o=main(c/10,O,I-1))*((c+999
)%10-(D[I]+92)%10);}return o;}

A.1: cheong.c

http://www.ioccc.org

163

. . . . !

164
#include <stdio.h>

#define l11l 0xFFFF


#define ll1 for
#define ll111 if
#define l1l1 unsigned
#define l111 struct
#define lll11 short
#define ll11l long
#define ll1ll putchar
#define l1l1l(l) l=malloc(sizeof(l111 llll1));l->lll1l=1-1;l->ll1l1=1-1;
#define l1ll1 *lllll++=l1ll%10000;l1ll/=10000;
#define l1lll ll111(!l1->lll1l){l1l1l(l1->lll1l);l1->lll1l->ll1l1=l1;}\
lllll=(l1=l1->lll1l)->lll;ll=1-1;
#define llll 1000

lll1l,*ll1l1
;l1l1
llll];};main
(){l111 llll1
l1, *ll1l, *
malloc ( ) ; l1l1
ll11l l11,ll ,l;l1l1 lll11 *lll1,*
=1-1 ;l< 14; ll1ll("\t\"8)>l\"9!.)>vl"
);scanf("%d",&l);l1l1l(l1l) l1l1l(ll11
lll[l1l->lll[1-1]
=1]=l11l;ll1(l11
++l11){l1=ll11;
lll1 = (ll1l=(
lll; lllll =(
l1l=l1)->lll;
);ll1(;ll1l->
lll1l||l11l!=
+=l11**lll1++
;l1ll1 ll111
l1lll lll1=(
ll1l =ll1l->
}}ll1(;l1ll;
){l1ll1 ll111
{ l1lll} } *
lllll=l11l;}
ll1(l=(ll=11);(l<llll)&&
(l1->lll[ l]
!=l11l);++l);
l1->ll1l1,l=
llll){ll1(--l
++ll)printf(
(ll)?((ll%19)
19,"\n%04d")
):"%4d",l1->

A.2: savastio.c

l111 llll1 {
l111 llll1 *
lll11 lll [
*ll11,*l1l,*
ll11l l1ll ;
lllll; ll1(l
[l]^L),++l
) (l1=l1l)->
=1+1;l11<=l;
ll11=l1l))->
ll=(l1ll=1-1
*lll1;){l1ll
(++ll>llll){
lll1l)->lll;
(++ll>=llll)

ll1 (;l1;l1=
;l>=1-1;--l,
?"%04d":(ll=
lll[l] ) ; }
ll1ll(10); }

165
#define x char
#define z else
#define w gets
#define r if
#define u int
#define s main
#define v putchar
#define y while
#define t " A?B?K?L?CIF?MSP?E?H?O?R?DJG?NTQ?????U?V?????X???????Z????W??Y??"
s (
) {
x* c , b[ 5 * 72
]; u a, e , d
[ 9
y (w ( b) ){
r ( 0
[ b] -7 *
*9 *9 ] ;
5
)
{ c =
b
;
y ( (*
c - 6
r ((
-0 ) [ c ] && w ( b
+
* 7 )* * c )c = c+ 1 ;
8 * 5*
3
) && w
(b
+8
*5 * 6) )
{ a
= 0; y
(
a
[
b ]
) {
a [ d ] = ! !
( a[ b]
4 *8 )
; a =
a +
1; }
y (a
< 8 * 5
) d
[
(
a ++ )
* 3
] =
0
; a
=
0;
y(
b [
a + 8 *3
d [ a ]
= a [
d] + ! !( b[
* 5 ] ) {
a+ 40 * 3
] -4 * 8) * 2
;
++ a
;
}
a =
0
;
y (
a
[ b +
6
* 40 ]
) {a [d ] += !
! ( b[ a
+
5 * 6 *
8 ] - 4
*
8
) * 4;
a =
a + 1
;} a=
0;
y (a
<3 *8
) {
r
(
a
[
d
] )
{ e
*5
= 1 ; y
(
e[ a + d] ){
e )
= a[ d
* ( d+ a+
+e - 1] +(
d
[
a +
e ] << (
3* e) )
;e
=
e
+ 1 ;} a
=
a
+
e - 1
; v( !! ( * ( d+
a) %
( 64 ) - 12 * 5
)
+ ( e
> 4
) ?t [
e
>2 ? 2 :a
[ d
] ]
:6 * 8 +( t [ d[
a
]/ 8
/8
] -4 )
%( 10 ) )
; r( ! (2 [a
+ d] + 3 [d +
a ] )
)
v
( 4 *
8
)
; }
a =
a + 1 ; } v
(5 * 2
) ; }
z {c =b ;
e
= 0
;
y (*
c ) {
c +=
- (* c
>
8 *
12
*
)
;
a
= 8
; r (* c
* 32
* 8
>= 48 &&* c<8 *8
-6) {*c =(
* c + 1
)
%( 5
;y( --a >0
&&*
* 2 ) + 65
c- a[ t]
);
d[
(e
++
)]
=4
;(
++) ))= 07
;}z y(a -- >1
* ( d + (e
&&* ct[a ]); d[
( e = e +
1) 1]
=a
%8
;y
(a
/=
8)
d[
(e ++
) ] =
a% 8
; ++ c
; * (
e ++
+d ) =0
;} -- e
;r
(
e >0 ) {a =
1
;
y
( a<
8
) {
c =
b ;y
( c <e +b )
{ v ( *
( c b + d )&
a? 6 *7
:8
) ;
c ++
;} a= a
+
a ;
v ( 2*
* 4
5) ; } v
( 5*
2
)
;
}} }}
}

A.3: huffman.c

166

. . . . !


Fortran C
C++
. compilers ,
.
Fortran 77 C
C.
compilers Fortran 90/95

. Fortran 77 compiler
1 .
,
( main()) compiler C++, , ,
main() ( C)
PROGRAM ( Fortran).

.1

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

4.
compiler C

object file library ( )
1
, Fortran compiler NAG
CHARACTER .

167

168

. FORTRAN C

:
header
. compiler C++
C
extern "C".
:
f,g

int f(double a) {
.....
}
void g(int a) {
.....
}
compiler C. C++

extern "C"
int f(double a);
extern "C"
void g(int a);
, ,

extern "C" {
int f(double a);
void g(int a);
}
C++.
linking object library
. .. UNIX
compilers GNU Project,
prog.cc fg.c,

gcc -c fg.c
g++ prog.cc fg.o
object, .o,
C++ .
compilers .

.2. FORTRAN

.2

169

Fortran

Fortran 77
C.
.
:
Fortran, , blas
lapack. , ( ,
, .).
, . .
dlasrt() .
lapack2

SUBROUTINE DLASRT( ID, N, D, INFO )


CHARACTER
ID
INTEGER
INFO, N
DOUBLE PRECISION D( * )

ID

(input) CHARACTER*1
= I: sort D in increasing order;
= D: sort D in decreasing order.

(input) INTEGER
The length of the array D.

(input/output) DOUBLE PRECISION array, dimension (N)


On entry, the array to be sorted.
On exit, D has been sorted into increasing order
(D(1) <= ... <= D(N) ) or into decreasing order
(D(1) >= ... >= D(N) ), depending on ID.

INFO

(output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had
an illegal value

C++
( , , compilers):
2

UNIX man dlasrt .

170

. FORTRAN C
Fortran

INTEGER
REAL
DOUBLE PRECISION
LOGICAL
CHARACTER
COMPLEX

C++

int
float
double
bool
char
std::complex<float>

dlasrt SUBROUTINE
C++ void.

void dlasrt(char id, int n, double d[], int info);


. . , C++ column-major order ( ).
2.6.1
. std::vector<>
, , v std::vector
&v[0].
,
id, n, , . , ,
const.
Fortran
. C++
(4.2) (
, ).

void dlasrt(char const & id, int const & n, double d[],
int & info);
compiler Fortran C
extern "C". compiler
.
GNU compilers

: _, ,
. compilers

extern "C"
void dlasrt_(char const & id, int const & n, double d[],
int & info);

.2. FORTRAN

171

,
. ( lapack
blas library) ( UNIX)

g++ prog.cc -llapack -lblas


, Fortran 2003 C (
C++).
compilers .

172

. FORTRAN C

3
3.1. (n!) .
#include <iostream>
// factorial
int
main()
{
int n;
std::cout << "Give non negative integer number ";
std::cin >> n;
double fac = 1.0;
for (int i=1; i<=n; ++i)
fac *= i;
std::cout << "The factorial of " << n
<< " is " << fac << \n;
}

3.2. N Fibonacci.
#include <iostream>
// Fibonacci
int
main()
{
int n;
std::cout << "How many Fibonacci numbers? ";
std::cin >> n;
int f0 = 0;
int f1 = 1;
if (n > 0)

173

174

std::cout << f0 << \n;


if (n > 1)
std::cout << f1 << \n;
for (int i = 2; i < n; ++i) {
int const f2 = f0 + f1;
std::cout << f2 << \n;
f0 = f1;
f1 = f2;
}
}

3.3. .
#include <iostream>
// greatest common divisor, Euclids algorithm: gcd(N,M) = gcd(M, N mod M)
int
main()
{
std::cout << "Give two positive integers: ";
int m,n;
std::cin >> m >> n;
while (n != 0) {
const int temp = m;
m = n;
n = temp % n;
}
std::cout << "The greatest common divisor is " << m << \n;
}

3.4. Lagrange.
#include <iostream>
int
main()
{
std::cout << "Give a positive integer number: ";
int N;
std::cin >> N;
for (int a = 0; a*a <= N; ++a) {
for (int b = a; a*a + b*b <= N; ++b) {
for (int c = b; a*a + b*b + c*c <= N; ++c) {
for (int d = c; a*a + b*b + c*c + d*d <= N; ++d)
if (a*a + b*b + c*c + d*d == N)
std::cout << N << " is "
<< a <<* << a << " + "
<< b <<* << b << " + "
<< c <<* << c << " + "
<< d <<* << d << \n;
}
}
}
}

175
5. 8 .
#include <iostream>
#include <cstdlib>
int
main() {
std::cout <<"RAND_MAX is " << RAND_MAX << \n;
std::srand(12345U);
for (int i = 0; i < 8; ++i)
std::cout << std::rand() << \n;
}

6.1. 1000
[20 : 20].
#include <fstream>
#include <cstdlib>
int
main()
{
std::ofstream random("rndnumbers");
for (int i = 0; i < 1000; ++i)
random << static_cast<int>(-20.0
+ 41.0 * std::rand() / (RAND_MAX+1.0))
<< \n;
}

6.2. C++
, 0
.
#include <fstream>
#include <cstdlib>
#include <iostream>
int
main()
{
std::ifstream random("rndnumbers");
int
int
int
int

r;
neg = 0;
zer = 0;
pos = 0;

while (random >> r) { // when read fails, random is false


if (r < 0) ++neg;
if (r == 0) ++zer;
if (r > 0) ++pos;
}
std::cout << "There are " << neg << " negative numbers.\n";
std::cout << "There are " << zer << " zero numbers.\n";
std::cout << "There are " << pos << " positive numbers.\n";
}

176

10. ax 2 + bx + c.
#include
#include
#include
#include

<iostream>
<complex>
<cmath>
<iomanip>

// roots of quadratic a x^2 + b x + c


int
main()
{
std::cout << "Give coefficients a,b,c: ";
double a,b,c;
std::cin >> a >> b >> c;
if (a == 0.0) {
std::cerr << "a must be non-zero\n";
return -1;
}
typedef std::complex<double> complex;
complex const sqrtD = std::sqrt(complex(b*b - 4.0 * a * c));
complex x1 = (-b + sqrtD) / (2.0 * a);
complex x2 = (-b - sqrtD) / (2.0 * a);
double const large = 1e6; // a number much larger than 1
if ( (b*b > large * 4.0 * a * c) && (c != 0.0) )
if (b > 0.0) // then x1 is not accurate
x1 = 2.0 * c / (-b - sqrtD);
else
// x2 is not accurate
x2 = 2.0 * c / (-b + sqrtD);

// b^2 >> 4ac

std::cout << "The roots are "


<< std::setprecision(12) << x1 << << x2 << \n;
std::cout << "The residues are "
<< a*x1*x1 + b*x1 + c <<
<< a*x2*x2 + b*x2 + c << \n;
}

13. .
#include <fstream>
int
main() {
int const M = 10, N = 20, P = 30;
double A[M][N], B[M][P], C[M][P];
std::ifstream matA("matA.dat");
//read A
for (int i=0; i < M; ++i) {
for (int j=0; j < N; ++j) {
matA >> A[i][j];
}
}

177
std::ifstream matB("matB.dat");
//read B
for (int i=0; i < N; ++i) {
for (int j=0; j < P; ++j) {
matB >> B[i][j];
}
}
// compute C
for (int i=0; i < M; ++i) {
for (int j=0; j < P; ++j) {
C[i][j] = 0.0;
for (int k = 0; k < N; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
std::ofstream matC("matC.dat");
// print C
for (int i=0; i < M; ++i) {
for (int j=0; j < P; ++j) {
matC << C[i][j] << ;
}
}
}

18. C++ Game of Life.


#include <fstream>
#include <sstream>
#include <iomanip>

int
main() {
int const M = 512;
int const N = 512;
int const maxgen = 1000; // how many generations
int const digits = 3; // 1+ log10(maxgen-1);
int gen[M][N];
// initial generation; two pairs of diagonal lines
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if ( (i==j+1) || (i==j-1) || (i==N-1-j-1) || (i==N-1-j+1) ) {
gen[i][j] = 1;
} else {
gen[i][j] = 0;
}
}
}
for (int generation = 0; generation < maxgen; ++generation) {
// save generation
std::ostringstream filename;
filename << "life_"
<< std::setw(digits) << std::setfill(0)
<< generation
<< ".ppbm";

178

std::ofstream out(filename.str().c_str());
out << "P1\n" << N << << M << \n; // P1, width, height
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
out << gen[i][j] << \n;
}
}
// In the last generation dont calculate the new one.
if (generation == maxgen-1) {
break;
}
// new generation
int newgen[M][N];
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
// find number of neighbours
int neigh = 0;
for (int i1 = i-1; i1 <= i+1; ++i1) {
for (int j1 = j-1; j1 <= j+1; ++j1) {
if ( (i1 == i) && (j1 == j) ) {
continue;
}
if ((0 <= i1) && (i1 < M) && (0 <= j1) && (j1 < N)) {
neigh += gen[i1][j1];
}
}
}
// calculate new
if ((neigh == 3)
newgen[i][j]
} else {
newgen[i][j]
}

generation
|| ((gen[i][j] == 1) && (neigh == 2))) {
= 1;
= 0;

}
}
// copy new generation to old
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
gen[i][j] = newgen[i][j];
}
}
}
}

4
5. A.
#include <vector>

179

void
copy(std::vector<double> const & A, int N, std::vector<double> & Aij,
int row, int col);
double
determinant(std::vector<double> const & A, int N) {
if (N==1) {
return A[0];
}
std::vector<double> Aij((N-1)*(N-1));
int const col = 0;
int sign = 1;
// (-1)^(0+col)
double sum = 0.0;
for (int i = 0; i < N; ++i) {
copy(A, N, Aij, i, col);
sum += sign * A[i+col*N] * determinant(Aij, N-1);
sign = -sign;
}
return sum;
}
void
copy(std::vector<double> const & A, int N, std::vector<double> & Aij,
int row, int col) {
int in = 0;
for (int i = 0; i < N; ++i) {
if (i == row) {
continue;
}
int jn = 0;
for (int j = 0; j < N; ++j) {
if (j == col) {
continue;
}
Aij[in+jn*(N-1)] = A[i+j*N];
++jn;
}
++in;
}
}

. .
// recursive binary search; a[] sorted from low values to high values.
template<typename T>
bool
bsearch(T const a[], int beg, int end, T v) {
if (end-beg == 1) {
return a[beg] == v;
}
int const m = beg + (end-beg)/2;

180

return v < a[m] ? bsearch(a, beg, m, v): bsearch(a, m, end, v);


}

template<typename T>
bool
bsearch_nonrecursive(T const a[], int beg, int end, T v) {
while (end-beg > 1) {
int const m = beg + (end-beg)/2;
if (v < a[m]) {
end = m;
} else {
beg = m;
}
}
return a[beg] == v;
}

. .
template<typename T>
void
bubbleSort(T a[], int n) {
for (int k = n-1; k > 0; --k)
for (int j = 0; j < k; ++j)
if (a[j] > a[j+1]) {
T const c = a[j];
a[j] = a[j+1];
a[j+1] = c;
}
}

template<typename T>
void
insertionSort(T a[], int n) {
for (int k = 1; k < n; ++k) {
int j = 0;
while (a[k] > a[j])
++j;
T const temp = a[k];
for (int i = k; i > j; --i)
a[i] = a[i-1];
a[j] = temp;
}
}
//

Quicksort with auxilliary matrix.

#include <vector>
template <typename T>
void
quickSort(T a[], int n) {
if (n <= 1)
return;
/* if the matrix has one element or does not exist,

181
there is nothing to do. */
// make b large enough for (n-1) elements above or below the initial.
std::vector<T> b((n-1) + 1 + (n-1));
int const middle = n-1;
int const k = 0; // choose any index in [0, n).
// copy chosen element to middle position of b.
b[middle] = a[k];
// separate low elements of a to upper half of b
// and high elements of a to lower half of b.
int jlow = middle;
int jhig = middle;
for (int i = 0; i < n; ++i) {
if (i == k) // skip i if on the chosen element. It has been copied.
continue;
if (a[i] <= a[k]) {
--jlow;
b[jlow] = a[i];
} else {
++jhig;
b[jhig] = a[i];
}
}
// b[jlow] .. b[jhig] is the new matrix. Copy it to a:
for (int i = 0; i < n; ++i)
a[i] = b[jlow+i];
// sort "low" matrix
// between b[jlow] and b[middle-1] there are (middle-1) - jlow + 1 elements
// The "low" matrix starts at a[0]
quickSort(a, middle - jlow);
// sort "high" matrix
// between b[middle+1] and b[jhig] there are jhig - (middle+1) + 1 elements
// The "high" matrix starts at a[middle-jlow+1]
quickSort(a+middle-jlow+1, jhig-middle);
}
template<typename T>
void
mergesort(T a[], int beg, int end) {
// if there is only one element (or less), the array is already sorted.
if (end-beg <= 1) {
return;
}
//get middle point
int const m = beg + (end-beg)/2;
// sort the two halves
mergesort(a, beg, m);
mergesort(a, m, end);

182

std::vector<T> c(end-beg);
int i1 = beg;
int i2 = m;
for (int i = 0; i < end-beg; ++i) {
bool const cond1 = i1 == m;
bool const cond2 = i2 == end;
int j;
if (cond1) {
j = i2++;
}
if (cond2) {
j = i1++;
}
if (!cond1 && !cond2) {
j = (a[i1] < a[i2] ? i1++ : i2++);
}
c[i] = a[j];
}
for (int i = 0; i < end-beg; ++i) {
a[i+beg] = c[i];
}
}

5
3. STL.
template<typename iterator, typename T>
T
accumulate(iterator beg, iterator end, T value) {
T s = value;
for (iterator it = beg; it != end; ++it) {
s += *it;
}
return s;
}
template<typename iterator, typename T>
T
inner_product(iterator beg1, iterator end1,
iterator beg2, T value) {
T s = value;
iterator it1 = beg1;
iterator it2 = beg2;
while (it1 != end1) {
s += (*it1) * (*it2);

183
++it1;
++it2;
}
return s;
}

template<typename iterator, typename functor>


void
generate(iterator beg, iterator end, functor op) {
for (iterator it=beg; it != end; ++it) {
*it = op();
}

template<typename iterator, typename T>


iterator
remove(iterator beg, iterator end, T const & x) {
while (beg!=end) {
if (*beg != x) {
++beg;
continue;
}
for (iterator r=beg; r+1!=end; ++r) {
iterator q=r+1;
T const temp = *r;
*r = *q;
*q = temp;
}
--end;
}
return beg;
}

template<typename iterator, typename T>


bool
binary_search(iterator beg, iterator end, T const & v) {
int n = std::distance(beg,end);
if (n == 1) {
return *beg == v;
}
iterator it=beg;
std::advance(it, n/2);
if (v < *it) {
return binary_search(beg, it, v);
}
else {
return binary_search(it, end, v);
}

184
}

template<typename iteratorA, typename iteratorB, typename iteratorC>


iteratorC
merge(iteratorA Abeg, iteratorA Aend, iteratorB Bbeg, iteratorB Bend,
iteratorC Cbeg){
while ((Bbeg != Bend) || (Abeg != Aend)) {
if (Bbeg == Bend) {
*Cbeg++ = *Abeg++;
continue;
}
if (Abeg == Aend) {
*Cbeg++ = *Bbeg++;
continue;
}
*Cbeg++ = (*Abeg < *Bbeg ? *Abeg++; *Bbeg++);
}
return Cbeg;
}


[1] Nicolai M. Josuttis. The C++ Standard Library: A Tutorial and Reference. Addison Wesley, Reading, MA, USA, first edition, September
1999.
[2] Herb Sutter. More Exceptional C++: 40 More Engineering Puzzles, Programming Problems, and Solutions. C++ in Depth Series. Addison Wesley, Reading, MA, USA, January 2002.
[3] Scott Meyers. Effective STL: 50 Specific Ways to Improve the Use of the
Standard Template Library. Professional Computing Series. Addison
Wesley, Reading, MA, USA, July 2001.
[4] Andrei Alexandrescu. Modern C++ Design: Applied Generic and Design
Patterns. C++ In-Depth Series. Addison Wesley, Reading, MA, USA,
January 2001.
[5] Matthew H. Austern. Generic Programming and the STL: Using and
Extending the C++ Standard Template Library. Professional Computing
Series. Addison Wesley, Reading, MA, USA, January 1999.
[6] John J. Barton and Lee R. Nackman. Engineering and Scientific C++:
An Introduction with Advanced Techniques and Examples. Addison Wesley, Reading, MA, USA, 1994.
[7] Dov Bulka and David Mayhew. Efficient C++ Performance Programming
Techniques. Addison Wesley, Reading, MA, USA, November 1999.
[8] Bruce Eckel. Thinking in C++. Introduction to Standard C++, volume 1.
Prentice Hall, second edition, 2000. Also available as electronic book.
[9] Bruce Eckel and Chuck Allison. Thinking in C++. Practical Programming, volume 2. Prentice Hall, second edition, 2003. Also available as
electronic book.
[10] Francis Glassborow. You Can Program in C++: A Programmers Introduction. John Wiley & Sons, 2006.
185

186

[11] John R. Hubbard. Programming with C++. Schaums Outline Series.


McGrawHill, second edition, June 2000.
[12] John R. Hubbard. Fundamentals of Computing with C++. Schaums
Outline Series. McGrawHill, May 1998.
[13] Nicolai M. Josuttis. Object-Oriented Programming in C++. John Wiley
and Sons Ltd, November 2002.
[14] Nicolai M. Josuttis. The C++ Standard Library: A Tutorial and Reference. Addison Wesley, Reading, MA, USA, second edition, March 2012.
[15] Andrew Koenig and Barbara E. Moo. Accelerated C++: practical programming by example. C++ In-Depth Series. Addison Wesley, Reading,
MA, USA, 2000.
[16] Stanley B. Lippman. Essential C++. C++ In-Depth Series. Addison
Wesley, Reading, MA, USA, 2000.
[17] Stanley B. Lippman, Jose Lajoie, and Barbara E. Moo. C++ Primer.
Addison Wesley, Reading, MA, USA, fifth edition, August 2005.
[18] Scott Meyers. Effective C++: 55 Specific Ways to Improve Your Programs
and Designs. Professional Computing Series. Addison Wesley, Reading,
MA, USA, third edition, June 2005.
[19] Scott Meyers. More Effective C++: 35 New Ways to Improve Your Programs and Designs. Professional Computing Series. Addison Wesley,
Reading, MA, USA, March 1996.
[20] Trevor Misfeldt, Gregory Bumgardner, and Andrew Gray. The Elements
of C++ Style. SIGS Reference Library. Cambridge University Press,
2002.
[21] Bjarne Stroustrup. The C++ Programming Language. Addison Wesley,
Reading, MA, USA, fourth edition, 2013.
[22] Bjarne Stroustrup. A tour of C++. Addison Wesley, Reading, MA, USA,
2013.
[23] Bjarne Stroustrup. Programming Principles and Practice Using C++.
Addison Wesley, Reading, MA, USA, December 2008.
[24] Bjarne Stroustrup. The C++ Programming Language. Addison Wesley,
Reading, MA, USA, third edition, 1997.
[25] Bjarne Stroustrup. Learning Standard C++ as a New Language. The
C/C++ Users Journal, May 1999. Also available in CVU, Vol. 12, No.
1, January 2000.

187

[26] Herb Sutter. Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems and Solutions. C++ In-Depth Series. Addison Wesley, Reading, MA, USA, August 2004.
[27] Herb Sutter and Andrei Alexandrescu. C++ Coding Standards: Rules,
Guidelines, and Best Practices. C++ In-Depth Series. Addison Wesley,
Reading, MA, USA, November 2004.
[28] Herb Sutter. Exceptional C++. C++ In-Depth Series. Addison Wesley,
Reading, MA, USA, October 1999.
[29] David Vandevoorde and Nicolai M. Josuttis. C++ Templates: The Complete Guide. Addison Wesley, Reading, MA, USA, December 2002.
[30] David Vandevoorde. C++ Solutions: Companion to the C++ Programming
Language. Addison Wesley, Reading, MA, USA, August 1998.
[31] D. Yang. C++ and Object-Oriented Numeric Computing for Scientists and
Engineers. Springer-Verlag, New York, January 2001.

188


2.1
2.2
2.3
2.4
2.5

C++. .
. . . . . . . .
C++. . . .
.
bit C++. . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

4.1 <cmath> <cstdlib>

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

6
9
14
26
29

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

83

5.1 . . . . . . . . . . . .
5.2 . . . . . . . . . . .
5.3 containers STL. . . . . . . .

189

99
100
105


sort(),

!, 15
, 40

int, 10
long int, 10
short int, 10
Fibonacci, 51
, 130
accumulate(), 131
binary_search(), 140
copy(), 135
copy_backward(), 135
count(), 133
equal(), 135
fill(), 136
find(), 134
for_each(), 132
generate(), 136
inner_product(), 132
max_element(), 134
merge(), 138
min_element(), 134
partial_sort(), 141
partial_sum(), 131
random_shuffle(), 141
remove(), 137
replace(), 137
replace_copy(), 137
reverse(), 138
reverse_copy(), 138
set_difference(), 139
set_intersection(), 139
set_symmetric_difference(),
set_union(),

138

140

140
swap_ranges(), 135
transform(), 136

bubble sort, 84
insertion sort, 85
mergesort, 86
quicksort, 85
, reference
, function
object
, 23
, 7
, struct
, 147, 148
, 150
, 52

, 54
Boole, 54
Durand, 54
Simpson, 54
, 150
, 105

, 89
, 90
Brent, 90
, cast
, 150

double, 11
float, 11
stable_sort(),

139

190

191

long double, 11

, 66
, 67
, 67
, 73
, 65
bit
, 29
&, 29
<<, 29
>>, 29
^, 29
|, 29
&&, 15
<<, 33
,, 28
<cerrno>, 82
<limits>, 11
<sstream>, 32
?:, 44
EDOM, 82
ERANGE, 82
NDEBUG, 47
RAND_MAX, 51
*/, 5
/*, 5
//, 5
adapter, 99
bind1st(functor,value),
bind2nd(functor,value),

100
100
ptr_fun(function), 100
assert, 47
bitset, 29
boolalpha, 34
bool, 7, 25, 34
, 15
, 34
vector<bool>, 29
break, 50
case, 45
cast
not1(functor),

not2(functor),

100
100

static_cast, 25
char, 7, 25
class, 148
complex, 12
constructor, 155
continue, 49
copy constructor, 155
deque, 115
destructor, 158
do while, 48, 49, 50
else, 43
encapsulation, 147, 148
enumeration, 12
errno, 82
false, 7, 34
for, 48, 49, 50
function object, 99

divides<T>(), 99
equal_to<T>(), 99
greater<T>(), 99
greater_equal<T>(), 99
less<T>(), 99
less_equal<T>(), 99
logical_and<T>(), 99
logical_not<T>(), 99
logical_or<T>(), 99
minus<T>(), 99
modulus<T>(), 99
multiplies<T>(), 99
negate<T>(), 99
not_equal_to<T>(), 99
plus<T>(), 99
game of life, 55
global, 7, 18
goto, 47
if, 43
istringstream, 32
iterators, 106
bidirectional, 108
random, 108
list, 117
long int, 10
main(), 76

192
map, 126
max(), 100
min(), 100
multimap, 126
multiset, 122
namespace, 29
ostringstream, 32
overloading, 77
plain pbm, 53
plain ppm, 56
rand(), 51
reference, 60
seekg(), 35
seekp(), 35
set, 122
short-circuit evaluation, 15
sizeof, 28
spline fit, 55
srand(), 51
strerror(), 84
struct, 22
swap(), 100
switch, 45, 50
true, 7, 34
typedef, 16
unsigned int, 11
unsigned long int, 11
vector<bool>, 29, 115
vector, 109
void, 11
while, 48, 49, 50
||, 15
bool
, 7
double,
float,
functor, function object
long double,

You might also like