You are on page 1of 147

C++

c 2004 , stamatis@iesl.forth.gr
Copyright

LaTEX2.
c , (
).

23 2006. http://www.materials.uoc.gr/tetycpp

1
1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
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 . . . . . . . . . .
2.9.3 . .
2.9.4 . . . . . . . . .
2.10 . . . . . . . . . . . . . . .
i

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1
1
4
5
5
5
6
6
6
7
8
9
10
10
11
11
13
14
14
15
15
16
17
17
20
21
24
26
27
28
28
29
31
32

ii
3
3.1 . . .
3.1.1 if . . . . . . . .
3.1.2 ?: . . . . . . . .
3.1.3 switch . . . . .
3.1.4 goto . . . . . .
3.1.5 assert() . . . .
3.2 . . . . . . . .
3.2.1 while . . . . . .
3.2.2 do while . . . .
3.2.3 for . . . . . . .
3.2.4 continue . . . .
3.2.5 break . . . . .
3.3
3.4 . . . . . . .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

37
37
37
38
39
40
40
41
41
41
42
43
43
43
43

4
4.1 . . . . . . . . . . . . .
4.2 . . . . . . . . . . . . .
4.3 . . . . . . . . . . . . . .
4.4 .
4.4.1 . . .
4.4.2 . . . . . . . . .
4.4.3 . . . . . . . . . . .
4.4.4 . . .
4.5 main() . . . . . . . . . . . . . . .
4.6 overloading . . . . . . . . . . . .
4.7 template . . . . . .
4.7.1 . . . . . . . .
4.8 inline . . . . . . . . . . . . . . .
4.9 . . . . . . . .
4.10 C++
4.11 . . . . . . . . . . . . .
4.11.1 . . . . . . . .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

49
49
50
51
54
54
57
57
61
63
64
64
67
67
68
68
70
72

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

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

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

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

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

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

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

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

75
. 76
. 76
. 76
. 77
. 79
. 79
. 84
. 89
. 91
. 95
. 99
. 103
. 111

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

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

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

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

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

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


6
6.1 . . . . . . . . . . . . . . .
6.2 . . . . . . . . . . .
6.2.1 Constructor . . . . . . . . . .
6.2.2 Destructor . . . . . . . . . . .
6.2.3 Copy constructor, assignment
6.2.4 Other operators, overloading .
6.3 template . . . . . . . . . . .
. . . !

iii

. . . . .
. . . . .
. . . . .
. . . . .
operator
. . . . .
. . . . .

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

113
. 113
. 117
. 120
. 120
. 120
. 120
. 120
121

Fortran C
125
.1 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
.2 Fortran . . . . . . . . . . . . . . . . . . . . . . . . . . 126

129

135

137

138

iv



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

, Fortran
C. C++
.
C++
Standard 1998, , ,
, ,

.
,
C++ C.

STL .
C++
(
).

vi


. , ,
.
, ,
, ,
.

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

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

1.1
:
. C++ ,
:

1.

2
#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), , , . ( ) {} ()
. C++.

, , (return 0;) , }
( 0).1 0 main()
1

main() .

1.1.

.
. , 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).
(*)
.
(;)
(, , ). (
#) ;.
C++ ,
. C++ .
( ). , ,
(+=, ==, <<, /*, //,. . . ). ,
, // .
(
) #.

1.

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
#if 0
.....
#endif
,
( ). ,
# .
5

2.

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

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

2.1: C++.

2.2
C++ :

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

2.2.

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;
, ,
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.
:

1

array of const char.

2.

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.


\?
\
\"
\\
\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.

2.2.4
(.. int) :
int i;
, namespace,
i 0, .
(.. 10)
int i = 10;
, ,
int i(10);

. int
16  bih
ts, 215 , 215 =
[32768, 32768) .
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
( 07).
0x 0X, (
, , af AF).

2.

10

long int L l
:
12L, 0xBABEL, 665l
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.,

2e 4 ( 0.0002),

2.3E2 ( 230.0) .

F f float L l
long double.

2.2.6 void
void
. , .
void* ( void)
. .

2.3.

11

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;

// Error

2.3
C++
class template,
.
C++
header <complex>
#include <complex>
.
(.. z) ,
double :
std::complex<double> z;

// z = 0.0 + 0.0 i

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

:

2.

12
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()
. ,
, .
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
<<

2.4.

13

(,)
>>
:
(,)
()

, ,
typedef (2.5.1).

2.4
C++ ( 2.3).
==
>
>=

!=
<
<=

2.3: C++.
true false. .. 3.0>2.0 true 2!=1+1
false.
.
, , (==, ) (!=, ).
, .
C++ !
(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

14

2.

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)
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.

15

2.5.2
, compiler
, ,

.
const
( ) :
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);

2.

16

, (.. int) (.. std::complex<double>), :


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).
, .
, ,
.
3
.
block . ..
2

2.6.

17

#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 . , , ,
.
C++ :
[_];
_
, .
containers STL, 5.
temperature 365

( int):

2.

18
double temperature[365];
int const N = 155;
int telephone[N];

telephone
.
, .. temperature,
0 D1 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 ( ):
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];

2.6.

19

. ,
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
:
[Ai j ] N1N2,
C++ N1 N2. Ai, j
a[i+ N1*j].
[Ai jk ] N1 N2 N3,
N1 N2 N3.
Ai, j,k a[i + N1 * (j + N2 * k)].
.
C
,
Fortran ,
,
.
, C++
. , Standard Library (STL) .

std::vector<> header <vector>:
v, 30 .. double
std::vector<double> v(30);
.
,
:
:
#include <vector>
#include <iostream>
int main() {

2.

20
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>.
, , :
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";
3

2.7.

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

<<
<<
<<
<<
<<

21

"The mass of element ";


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

(struct) C
C++ 6.
.

2.7
C C++
:
+,-: 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;

2.

22

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

++ --
, , , ,
.
2.4 .
,
. .
( )
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;
5

compiler .

2.7.

23

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.

24

// Correct value
double mean2 = static_cast<double>(sum) / N;
static_cast :
static_cast<newtype>(variable);
:
(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.7.1

sizeof
sizeof
bytes.6
6

, byte

char.

2.7.

25

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.
bit .
(short int, int, long int, bool, char) enum, signed unsigned.
2.5.
, 0 1 .
<<, >> bits
. bits .
<< 0 >>
unsigned.
&, , | bit pattern
AND, XOR, OR bit .

2.

26

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++.

bit (true/false, on/off,


. . . ) . C++ bitset<>
std::vector<> bool
, .
bool, ,
bit byte, (2.2.4).

2.8

(namespace)

( )
. ..
solve,

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

2.9. (STREAMS)

27

.
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;
return 0;
}
( ),
namespace :
using std::cout;
: namespace {...}.

namespace.
, ,
.
main() namespace
global.

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

28

2.

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");
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, .

2.9. (STREAMS)

29

header <sstream> ,
std::istringstream std::ostringstream. ostringstream C++ string . string, .
C++ string "filename_3.dat":
#include <sstream>
int
main() {
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";

2.

30

std::cin >>,
:
double a;
int b;
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
.

std::cout << (3==2);
0. true false,
manipulator std::boolalpha header <ios>:
std::cout << std::boolalpha << (3==2);
std::noboolalpha.
, bool
.
stream
stream: false .
streams
get(),
EOF ( eof()
true). is
( 3.2.1)
while (is.get() != \n);
seekg()/seekp() ( / ),
. ..
is is.seekg(0);.

2.9. (STREAMS)

31

2.9.4
manipulators C++, boolalpha
noboolalpha, , bool. header <ios>
(no)skipws: () .
(no)showpos: () + .
(no)showpoint: () 0 .
scientific: d.dddddd dd
fixed: dddd.dd
left/right: / .
header <iomanip>
setprecision() (
)
. 6.
setw()
( ) .
0.
setfill() setw() .
.
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;

2.

32

std::cout << "fixed\t" << std::fixed


<< a << \n;
std::cout << "with 9 digits\t"
<< std::setprecision(9)
<< a << \n;
return 0;
}

2.10
1. , .
C++ .
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. ;

2.10.

33

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; ;
#include <iostream>
#include <limits>
int
main() {
int a = std::numeric_limits<int>::min() - 10;
int b = std::numeric_limits<int>::max() + 10;
std::cout << a << "
" << b << \n;
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

2.

34
() m%n++
() m%++n
() ++m=n-() m=n=3
() m+=n-=2
() 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.

2.10.

35

() r.
() d h.
() c
a,b .
18.
:
() a==b||a==c&&c<5
() c=x!=0
() 0<=i<6
() a=b==c++
() a*=b?c:d*2
19. a, b, c a2 + b2 = c2 . m, n m > n,

m2 n2 , 2mn, m2 + n2 . C++
.

36

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) {
...
}
block
if. if (condition) {...} else {...}
. block
37

3.

38

() .
.
if,
else . else if
block. , ,
:
if (i == 0)
if (val > max)
max = val;
else
j = 10;
, j = 10; i 0
(val > max) (i == 0).
:
if (i == 0) {
if (val > max)
max = val;
}
else
j = 10;

3.1.2 ?:
(?:) C++.

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

val = (condition ? value1 : value2);
,
(condition ? : )
condition ,
.
(?:) ,
. (=)
. ,
: (?:) (=) ,
. ,
a = b ? c : d

a = (b ? c : d)

3.1.

39


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.
case / default , break (
.. goto, return, throw). break

switch. value1, value2,. . . ,valueN
block default, . ,
} switch.
case default .
:


. +, -, *,
/.

.
#include <iostream>
int

3.

40
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.4 goto

(label). (.. labelname)
.
labelname : statement;

goto:
goto labelname;
goto
.
goto . C++
(3.2) goto .
, , .
, goto .

3.1.5 assert()
C++
header <cassert> macro assert().

3.2.

41

:
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).

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.

3.

42

, .
1 ( block).

3.2.3 for
for

. C++ for . :
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.3.

43

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

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.

44

; ; . ;
3. C++
e x

ex =

X
xn
,
n!
n=0

sin x

sin x =

X
(1)k x2k+1

(2k + 1)!

k=0

cos x

cos x =

X
(1)k x2k
k=0

(2k)!

.
4. 8 . rand()
<cstdlib> 0 RAND_MAX. RAND_MAX compiler; srand().1
5.

() 1000
[20, 20]. ( !)
int r = -20.0 + 41.0 * (std::rand() / (RAND_MAX+1.0));
() C++
, 0
.

6. C++
() (n!) .
() N Fibonacci2

f (n + 2) = f (n + 1) + f (n),

n 0,

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

() .
() Lagrange 3 :
(
) .
1

UNIX man srand .


http://www.research.att.com/projects/OEIS?Anum=A000045
3
http://mathworld.wolfram.com/LagrangesFour-SquareTheorem.html
2

3.4.

45

7. C++
() .
() N . ( : 2,3,5,. . . ).
()
4 , p,p+6,p+12 ,
.
()

1 + (p 1)!
p

(mod p) = 0 ,

Wilson primes5 .
8.
a, b, c 12
ax2 + bx + c.

x1,2 =

b2 4ac
,
2a

(
b2  4ac)

x1,2 =

2c
.

b b2 4ac

C++ std::sqrt()
<cmath>. .
.
.
9. M N K
1 0.
() ( M = 20, N = 60)
, x o
.
() .ppbm
( M = N = 512):
: P1.
: .
1 0 ( ).
plain pbm (portable
bitmap) .
4
5

http://www.research.att.com/projects/OEIS?Anum=A047948
http://www.research.att.com/projects/OEIS?Anum=A047540

3.

46

10.
A ( M N ) B (N P).
;
11. C++
Ax = B Gauss (Gauss elimination6 ).
A B
.
12. C++ A Gauss
Jordan (GaussJordan elimination7 ).
13.

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

: x1 , x2

x2

f (x)d x
x1

1
x ( f1 + f2 ) .
2

Simpson: x1 ,
x2 , x3

x3

f (x)d x
x1

1
x ( f1 + 4 f2 + f3 ) .
3

Boole: x1 , x2 ,
x3 , x4 , x5

x5

f (x)d x
x1

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

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

xn

f (x)d x x
x1

!
2
11
11
2
f1 +
f2 + f3 + + fn2 +
fn1 + fn .
5
10
10
5

fi f (xi ) x
. [10 sin(5)
50 cos(5)].
.
14. Spline Fit. n (xi , yi ).
2(n 1)
. , ( 2(n 2)
6
7

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

3.4.

47

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

.
() spline
.
() .
()
.
15. C++ Game of Life8 Dr. J.
Conway.
:
M N , ( ). K . ( ):
() ().
() ().
() ( ( !.
.
plain pbm ( 9) .

,
(, ).

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

48

3.

4.1

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

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

.

(structured) (procedural)
C++.
,
C++
.
49

4.

50

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++ , , ,
. , <limits> std::numeric_limits<double>::digits10.
:
#include <limits>
#include <iostream>

4.3.

51

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. ,
, *p a *p
a. ..
double r = 5.0;
double * q = &r;
*q = 3.0; // r becomes 3.0

void1 :
int
int
p =
int
1

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

void * .

4.

52

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.
. *)
.
. , (
) .
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.

4.3.

53

p3 . *p3

.
p4 .

.
: .
:
double x = 1.2;
double * const p = &x;
double y = 0.1;
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;
2

// q == &a[5]

std::ptrdiff_t <cstddef>.

4.

54
,
int a[10];
int * p = &a[0];

*(p+i) a[i] , ,
p+i == &a[i].

.
, . a[i] *(a+i).
:
:
double b[10];
double * p = b;
for (int i = 0; i < 10; ++i)
*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.4.

55

//
}
void . ,
(, ,
). , ,
void. , ,
(}).

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

. . ,
headers,
.h,3


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

compiler

4.

56

,
, headers.
:
min/max /
:
min: <

max: <

utilities.h
(.. float)
// utilities.h
// declarations
float
fmin(float a, float b);
float
fmax(float a, float b);
utilities.cc
// utilities.cc
#include "utilities.h"

// Not necessary but good practice

// definitions
float
fmin(float a, float b) { return a<b ? a : b; }
float
fmax(float a, float b) { return a<b ? b : a; }
:
utilities.h , ..
#include <iostream>
#include "utilities.h"
int
main() {
float a, b;
std::cout << "Give two numbers\n";
std::cin >> a >> b;
std::cout << "Max is " << fmax(a,b) << \n;
std::cout << "Min is " << fmin(a,b) << \n;
}
compile utilities.cc
main() compiler

4.4.

57

, linking.
,
( ),
, :
int func(double a, double b = 5.0);
func()
( a) b
, 5.0. ,
, , compiler
.

4.4.2

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

return, .
.

, , .

4.4.3
,
( ).
,

, . ,
, !
:
#include <iostream>
#include <fstream>
double
func(double a, double b);
// declaration. The definition is elsewhere.

4.

58

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.
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

4.4.

59

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
.
, ,
, ,
.
( , ),
, const. ..
void
print(std::size_t const N, double const a[]) {
for (std::size_t i = 0; i < N; ++i)
std::cout << a[i] << \n;
}
N, ,
. const ,

.
,
:
x
void f(double x);

// x cannot change

x
void f(double & x);

// x can change

x
void f(double const & x);

// x cannot change

4.

60

xp ,
*xp ( )
void f(double * xp);

// xp cannot change, *xp can change

xp , *xp (
)
void f(double const * xp);

// xp cannot change, *xp cannot change

a ,

void f(double a[]);

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

a ,

void f(double const a[]);

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

(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)

4.4.

61

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

4.4.4
, , .

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.

62
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
..
, :
int func(double a, double b); // target function
typedef int (*ftype)(double x, double y);
ftype g = func;

// type

// declaration with assignment

4.5. MAIN()

63

4.5 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> :
int atoi(char const * p);
long atol(char const * p);
double atof(char const * p);

// 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

4.

64

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,. . . ).
, int
double, double long double, void*, .
,

, .
(
)
compiler
.

4.7 template
C++ templates ().
.
(swap).

4.7. TEMPLATE

65

,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;
}
...
...

. 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):

std::swap() <algorithm>.

4.

66

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,. . . ) , 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 . C++
( ) ( )
template export:
// util.cc
export template <typename T>
T const & max(T const & a, T const & b) {
return a>b ? a : b;
}
// util.h
template <typename T>
T const & max(T const & a, T const & b);
5
Standard 1998 template , , .. template <typename X,typename Y = double>.

.
6
.

4.8. INLINE

67

compilers export
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) , .

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.

68

4.9

. ,

.

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

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.

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

double
double
double
double
double
double
double
double

n/d.

ldiv_t div(long int n, long int 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>.

n/d.

<cstdlib>
.

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

double fmod(double d, double m)


double ldexp(double d, int i)

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

, xi .
.
.
.
.
.
.
arctan(x/y).

pow(double x, int i)
cos(double)
sin(double)
tan(double)
acos(double)
asin(double)
atan(double)
atan2(double x, double y)

double
double
double
double
double
double
double
double

double floor(double)

double abs(double)
double ceil(double)

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

<cmath>


.

.

.
.
, xa .

4.10. C++
69

4.

70

if (errno == EDOM)
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
1.
.
.
2. 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) .


3. Cliff Pickover7 :

Xn+1 = |100(ln(Xn ) (mod 1))|


X0 = 0.1.
4. A N 8

det A =

N
X
ei j ,
(1)i+ j ai j det A
i=1

j, .. 1. A i j ei j A
ai j , A
i j .
5. Cramer9 .

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

4.11.

71

6.
( )

n`m (r, , ) = Rn` (r)Y`m (, ) .


,

s
Y`m (, ) =

2` + 1 (` m)! m
P (cos )eim .
4 (` + m)! `

Legendre, Pm
` (x),
` = m
m
2 /2
Pm
,
` (x) = (1) 1 3 5 (2m 1) (1 x )
m

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


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

[0, ] [0, 2) .
50 100 Y`m (, ).

sin cos , sin sin , cos , Y`m (, )Y`m


(, ) (, ,

x, y, z, ) , ` = 2, m = 0 (, d ).
7. C++ ( ) f (x) = 0 [xa , xb ] f (x).
:
() 10 . ,
.
() 11 . ,
,

f (x).
.
() Brent12 . ,

, , .
.

10

http://mathworld.wolfram.com/Bisection.html
http://mathworld.wolfram.com/MethodofFalsePosition.html
12
http://mathworld.wolfram.com/BrentsMethod.html
11

4.

72

8. C++ .
,
3 3 , , N N , (.. x o)
(, , N -)
, , .
, .

.
. ,
, , , , .

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

.
, .
, .

4.11.1
1. C++
.
.
,
.
2. std::swap()
std::min(), std::max() STL, 5.1.3.
3.
std::vector<double> ( <vector>) , , (<, )
(=, ) ([],
subscripting).
4. std::sort() STL <algorithm>.
5. dlasrt() lapack13 .
13

4.11.

73

Bubble sort
. O(n2 ) :
1. ,
. ,
.
2. . , , .
3. .
,
.
,
, !
Insertion sort
. O(n2 ) (
) O(n). :
1. ,
.
2. , ,. . .
( ),
.
Quicksort
, , . O(n2 ) ( )
() O(n log n). ,
:
1. .
2. , , ,

.
. .
3. - . ,
.

74

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).
STL
headers (.. / , , , , ...)
. C, .
STL.
,
containers .
75

5. STANDARD LIBRARY

76

5.1
5.1.1

(Pair)

STL containers
. , header
<utility> , , std::pair<T1,T2>. 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).

first. ,
. , second
.

5.1.2

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

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>()

77

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>()
. , ..
constval
std::bind1st() :
std::bind1st(plus<T>(), constval)
,
( )
(!) .

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: .

( )
ptr_fun().

5.1.3 ,
header <algorithm> std::min<>(), std::max<>()
std::swap<>() templates. :
namespace std {
// minimum of a, b

78

5. STANDARD LIBRARY

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
.
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. (CONTAINERS)

79

5.2 (containers)
5.2.1
containers
. container
, , ,
C, .
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). ,
STL, containers std.
c ( ) set
v vector :
#include <set>
#include <vector>
#include <complex>

5. STANDARD LIBRARY

80

std::set<int> c;
std::vector<std::complex<double> > v;
// use c, v ........
> v
>>.
containers , . , , ,
,
.
container
, 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,
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.

5.2. (CONTAINERS)

81

, 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 .

size()
empty()


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

( )
iterator
iterator
reverse iterator
reverse iterator

max_size()
begin()
end()
rbegin()
rend()

5.3: containers STL.


container
(.) container (
). .., vector
:
void f(std::vector<double> & c) {
std::cout << "Size of argument is " << c.size() << \n;
}

5. STANDARD LIBRARY

82

container ==,
!=, <, >, <=, >= . container
, .
:
1. .
containers.
2. , container .
3. containers .
container
container :
container, :
c1 = c2;
c1
c2. c1
c2.
.
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(beg,end);

5.2. (CONTAINERS)

83

iterators [beg,end) (, , ). c
sequence container iterator
associative containers .
clear().
container. void:
c.clear();
, container .
Iterators
,
iterators
containers.
iterator
. iterator
,
(*) iterator
. , *it container
iterator it.
pointers iterators.
, , iterator
(&) .
STL containers. , ..
it, iterator container (.. vector) :
std::vector<double>::iterator it;
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 .
iterators :

5. STANDARD LIBRARY

84

random () iterators,
,
: ( 2.3), ++it it ,
iterator
, random iterators
container , . iterators
vector deque .
bidirectional ( ) 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).

Difference_type distance(Iterator it1, Iterator it2);
it1, it2 iterators container.
random it2-it1 bidirectional
it1 it2 .
, it1
it2.

5.2.2 vector
vector
. sequence container,
. vector
. ,
, , .
:
vector
container. ,
1

std::iterator_traits<InputIterator>::difference_type.

5.2. (CONTAINERS)

85

.

vector
.
vector
, ,
, , . ,
, iterators
.
,
vector .
std::vector header <vector>.

vector
.
.

std::vector<T> v;
vector.

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

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

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

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

5. STANDARD LIBRARY

86

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 .

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);

5.2. (CONTAINERS)

87

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 (
).

v.push_back(elem);
elem
vector. .
resize()
. .
v.resize(N);
v N
.
.
, .
v.resize(N,elem);
elem.

5. STANDARD LIBRARY

88

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.

,
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] .2

.
2

at().

5.2. (CONTAINERS)

89

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;
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::bitset std::deque<bool> (..
[1], . 158, [2], . 4145, [3], item 18) .

5.2.3 deque
deque (double-ended queue) vector. sequence container , vector,

5. STANDARD LIBRARY

90

. ,
vector
, deque .
, .
std::deque header <deque>.
deque
. , vector

. ,
, vector,
.
deque
. , , 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 "

5.2. (CONTAINERS)

91

<< *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 << "front element is " << r << \n;
// NOT NECESSARILY THE SAME AS ABOVE
std::cout << "front element through iterator is "
<< *beg << \n;
}

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

5.1: list.
, vector
deque, . ,

. , ,
sequence containers ( ). , , :
list
( 5.2) . , iterators
.

?-

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

5. STANDARD LIBRARY

92

list sequence containers. .


std::list<T> c;: .
std::list<T> c1(c2);: , .
std::list<T> c(N);: N .
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);: c1, c2.
std::swap(c1,c2);: swap()
.
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)

93


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);

, true false. remove_if()
list
func() true.
unique()
.

5. STANDARD LIBRARY

94

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
, , .

c1.merge(c2, op);

op().
reverse() list
.
:

5.2. (CONTAINERS)

95

#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));
<functional>. , , lessthan10(),
.

5.2.5 set multiset


set multiset containers
, . ,
, .
containers multiset set
. , set
. , set
multiset.

5. STANDARD LIBRARY

96

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

set T
.3 5.2.1 :

std::set<T> c;
set.

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

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.
3

5.2. (CONTAINERS)

97


set :
c1 = c2;: c2 c1 .
c1.swap(c2);: c1, c2.
std::swap(c1,c2);: swap()
.
c.insert(elem);: set multiset c elem.
c multiset iterator .
c set (pair, 5.1.1),
iterator
bool .
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
.

.

5. STANDARD LIBRARY

98

set multiset, containers,


size(), empty() max_size() (5.2.1),
iterators. ,
. :
count(elem): elem.
find(elem): iterator elem ,
, end().
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;

5.2. (CONTAINERS)

99

// 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";
std::cout << \n;
typedef std::multiset<int, std::greater<int> > MSet;
// create multiset from c
MSet mc(c.begin(), c.end());
//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.6 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. STANDARD LIBRARY

100
.4

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<T> (<)
( ). , template
, true/false,
.
set, 5.2.5.

map :
c1 = c2;: c2 c1 .
c1.swap(c2);: c1, c2.
std::swap(c1,c2);: swap()
.
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.2. (CONTAINERS)

101


map c :
c.erase(elem);: elem
.
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.
.
:
, map
.

5. STANDARD LIBRARY

102
#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.
upper_bound(key):
key.
equal_range(key): , , iterators key.

5.3. (ALGORITHMS)

103

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

container. iterator

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

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>.
:

104

5. STANDARD LIBRARY

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

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)
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)

5.3. (ALGORITHMS)

105

[beg,end)
value. associative containers
.

op() true.
Difference_type .1

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()).

106

5. STANDARD LIBRARY

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

op(), .

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).

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 .
op()
[beg1,end1)

5.3. (ALGORITHMS)

107

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.

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)

108

5. STANDARD LIBRARY

[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()).
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)

5.3. (ALGORITHMS)

109

[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
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()
.

110

5. STANDARD LIBRARY

set_symmetric_difference()
Iterator
set_symmetric_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator
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.

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

5.4.

111

void
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. 1000 .
()
. container
( )
.
() ( clock()5 <ctime>).
;
()
.
() .
() 0.
() 0.
() .
2.
list: unique(), splice(), merge(), reverse().
5

Unix man 3 clock .

112

5. STANDARD LIBRARY

3. STL. . ;
4. .
( )
( , ,
).
5. :
, , ( ), , , .
,
.

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


.
,
, ,
, . , , ( ,
, , ,
.), ( , , , , .), .
( )
. .. C++
std::size_t const N = 50; // number of students
std::string studentName[N];
int studentAM[N];
int studentYear[N];
// .......
std::size_t const M = 500;
std::string bookTitle[M];
std::string bookAythor[M];
int bookYear[M];
// .......

// number of books


( ) ,
,
113

114

6.

.
, compiler
.
( ,
, . , , , , , .) , ,
, , .
, , ,
.
, .
: , !

C++ struct, 2.6.2,

struct Student {
std::string name;
int AM;
int Year;
// ......
};
struct Book {
std::string title;
std::string author;
int year;
// ......
};
, .
:
std::size_t const N = 50;
std::size_t const M = 500;
Student students[N];
Book
books[M];
: , , (..
) Student
Book.
int printStudent(Student const & s);
int printBook(Book const & c);
, , . ,

6.1.

115

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

.

,
(
, , .).

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

class Student {
std::string name;
int AM;
int Year;
// ......
public:
int print() {....}
// former int printStudent(Student const & s);
std::string getName() {....}
int getAM() {....}
int getYear() {....}
// ......
};

class Book {
1

.

struct

116

6.

public:
int print() {....} // former int printBook(Book const & c);
std::string getTitle() {....}
std::string getAuthor() {....}
int getYear() {....}
// ......
private:
std::string title;
std::string author;
int year;
// ......
};
. (
, ) printStudent() printBook()

( )
( ).
struct (.).
. ,
print() Student :
Student s;
s.print();
s print() . ,
public:
( )
( )
. , {
private:
.
,
,
. ( )
, ..
class Student {
std::string name;
// ......
public:
std::string getName() {return name;}
// ......
};
C++
.

,

6.2.

117

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

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

. C++
.

6.2
, ,
Student .
class Student {
public:
Student(std::string const & onoma, int am, int y)
: name(onoma), AM(am), Year(y) {}
Student() {}
Student(Student const & other);
Student & operator=(Student const &other);

6.

118

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(std::string const & s) {name = s;}
void setAM(int am) {AM = am;}
void setYear(int y) {Year = y;}
private:
std::string name;
int AM;
int Year;
};
( , )
class struct,
, {}, (
). (;)
.
, name, AM, Year,
.
private: .
, , print(), getName(),
getAM(), getYear(), setName(), setAM(), setYear() ,

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


. , , const. ,
getName(), getAM(), getYear(),
, const
( ).
. ,
2

protected:, .

6.2.

119

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

// correct
// error

setYear() s1 s2 .
, ,
const ,

const.
(Student(), Student(), operator=())
.
,

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

. , 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;
}
, .

120

6.


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

6.2.1 Constructor
6.2.2 Destructor
6.2.3 Copy constructor, assignment operator
6.2.4 Other operators, overloading

6.3 template


. . . !
, , 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.es.ioccc.org/years.html

121

. . . . !

122
#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->

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); }

A.2: savastio.c

123
#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
*9 *9 ] ;
y (w ( b) ){
r ( 0
[ b] -7 *
5
)
{ c =
b
;
y ( (*
c - 6
* 7 )* * c )c = c+ 1 ;
r ((
-0 ) [ c ] && w ( b
+
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
* 3
) d
[
(
a ++ )
] =
0
; a
=
0;
y(
b [
a + 8 *3
* 5 ] ) {
d [ a ]
= a [
d] + ! !( b[
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
*5
) {
r
(
a
[
d
] )
{ e
= 1 ; y
(
e[ a + d] ){
* ( d+ a+
e )
= a[ d
+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
)
* 32
;
a
= 8
* 8
; r (* c
>= 48 &&* c<8 *8
-6) {*c =(
* c + 1
)
%( 5
* 2 ) + 65
;y( --a >0
&&*
c- a[ t]
);
d[
(e
++
)]
=4
;(
* ( d + (e
++) ))= 07
;}z y(a -- >1
&&* 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
* 4
) ;
c ++
;} a= a
+
a ;
v ( 2*
5) ; } v
( 5*
2
)
;
}} }}
}

A.3: huffman.c

124

. . . . !


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
C , , compiler C++.
C
C++. , 4.
compiler C object
file library ( ) :
header .
compiler C++
C
extern "C".
1
, Fortran compiler NAG
CHARACTER .

125

. FORTRAN C

126

:
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

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

UNIX man dlasrt .

.2. FORTRAN

127

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):
Fortran

C++

INTEGER

int

REAL

float

DOUBLE PRECISION

double

LOGICAL

bool

CHARACTER

char

COMPLEX

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.

128

. FORTRAN C

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);

,
. ( lapack
blas library) ( UNIX)

g++ prog.cc -llapack -lblas


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

3
4. 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;
}

5.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;
}

5.2. C++
, 0 .
#include <fstream>
#include <cstdlib>

129

130
#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";
}

6.1. C++ (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;
}

6.2. C++ 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)
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;
}
}

131
6.3. C++ .
#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;
}

6.4. C++ Lagrange.


#include <iostream>
#include <cmath>
int
main()
{
using std::sqrt;
std::cout << "Give a positive integer number: ";
double N;
// double, to use it in sqrt
std::cin >> N;
for (int a1 = 0; a1 <= sqrt(N); ++a1) {
int const a1sq = a1 * a1;
for (int a2 = a1; a2 <= sqrt(N-a1sq); ++a2) {
int const a2sq = a2 * a2;
for (int a3 = a2; a3 <= sqrt(N-a1sq-a2sq); ++a3) {
int const a3sq = a3 * a3;
for (int a4 = a3; a4 <= sqrt(N-a1sq-a2sq-a3sq); ++a4)
if (a1sq + a2sq + a3sq + a4*a4 == N)
std::cout << N << " is "
<< a1 <<* << a1 << " + "
<< a2 <<* << a2 << " + "
<< a3 <<* << a3 << " + "
<< a4 <<* << a4 << \n;
}
}
}
}

8. ax2 + bx + c.
#include
#include
#include
#include

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

// roots of quadratic a x2 + b x + c
int
main()
{
std::cout << "Give coefficients a,b,c: ";

132

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);

// b2 >> 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;
}

15. 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";
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;

133

if (generation == maxgen-1) break;


// In the last generation dont calculate the new one.
// new generation
int newgen[M][N];
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
int neigh = 0;
if (i-1 >= 0)
neigh += gen[i-1][j];
if (i+1 < M)
neigh += gen[i+1][j];
if (j-1 >= 0)
neigh += gen[i][j-1];
if (j+1 < N)
neigh += gen[i][j+1];
if ((i-1 >= 0) && (j-1 >= 0))
neigh += gen[i-1][j-1];
if ((i-1 >= 0) && (j+1 < N))
neigh += gen[i-1][j+1];
if ((i+1 < M) && (j-1 >= 0))
neigh += gen[i+1][j-1];
if ((i+1 < M) && (j+1 < N))
neigh += gen[i+1][j+1];
if ((neigh == 3) || (gen[i][j] && (neigh == 2)))
newgen[i][j] = 1;
else
newgen[i][j] = 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
4. .
#include <vector>

int
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;

134
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;
}
int
copy(std::vector<double> const & A, int N, std::vector<double> & Aij,
int row, int col) {
int in = 0;
int jn = 0;
for (int i = 0; i < N; ++i) {
if (i == row) continue;
for (int j = 0; j < N; ++j) {
if (j == col) continue;
Aij[in+jn*(N-1)] = A[i+j*N];
++jn;
}
++in;
}
return 0;
}


[1] Nicolai M. Josuttis. The C++ Standard Library: A Tutorial and Reference.
Addison Wesley, Reading, MA, USA, 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] John R. Hubbard. Programming with C++.
McGrawHill, second edition, June 2000.

Schaums Outline Series.

[11] John R. Hubbard. Fundamentals of Computing with C++. Schaums Outline Series. McGrawHill, May 1998.
[12] Nicolai M. Josuttis. Object-Oriented Programming in C++. John Wiley and
Sons Ltd, November 2002.
135

136

[13] Andrew Koenig and Barbara E. Moo. Accelerated C++: practical programming by example. C++ In-Depth Series. Addison Wesley, Reading, MA,
USA, 2000.
[14] Stanley B. Lippman. Essential C++. C++ In-Depth Series. Addison Wesley,
Reading, MA, USA, 2000.
[15] Stanley B. Lippman, Josee Lajoie, and Barbara E. Moo. C++ Primer. Addison Wesley, Reading, MA, USA, fourth edition, February 2005.
[16] 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.
[17] Scott Meyers. More Effective C++: 35 New Ways to Improve Your Programs
and Designs. Professional Computing Series. Addison Wesley, Reading,
MA, USA, March 1996.
[18] Trevor Misfeldt, Gregory Bumgardner, and Andrew Gray. The Elements of
C++ Style. SIGS Reference Library. Cambridge University Press, 2002.
[19] Bjarne Stroustrup. The C++ Programming Language. Addison Wesley,
Reading, MA, USA, third edition, 1997.
[20] 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.
[21] Herb Sutter. Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems and Solutions. C++ In-Depth Series. Addison Wesley,
Reading, MA, USA, August 2004.
[22] Herb Sutter and Andrei Alexandrescu. C++ Coding Standards: Rules, Guidelines, and Best Practices. C++ In-Depth Series. Addison Wesley, Reading,
MA, USA, November 2004.
[23] Herb Sutter. Exceptional C++. C++ In-Depth Series. Addison Wesley, Reading, MA, USA, October 1999.
[24] David Vandevoorde and Nicolai M. Josuttis. C++ Templates: The Complete
Guide. Addison Wesley, Reading, MA, USA, December 2002.
[25] David Vandevoorde. C++ Solutions: Companion to the C++ Programming
Language. Addison Wesley, Reading, MA, USA, August 1998.
[26] D. Yang. C++ and Object-Oriented Numeric Computing for Scientists and
Engineers. Springer-Verlag, New York, January 2001.


2.1
2.2
2.3
2.4
2.5

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

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

4.1 <cmath> <cstdlib>

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

. 6
. 8
. 13
. 23
. 26

. . . . . . . . . . . . . . . 69

5.1 . . . . . . . . . . . . . . . 77
5.2 . . . . . . . . . . . . . . 77
5.3 containers STL. . . . . . . . . . . 81

137


!, 13
<<, 29
&&, 13
,, 25
<cerrno>, 68
<limits>, 10
<sstream>, 29
?:, 38
EDOM, 68
ERANGE, 68
NDEBUG, 41
RAND_MAX, 44
Wilson primes, 45
*/, 5
/*, 5
//, 5
adapters, 77
assert, 40
bitset, 26
boolalpha, 30
bool, 6, 7, 14, 30
break, 43
case, 39
char, 7
complex, 11
continue, 43
deque, 89
do while, 41, 43
else, 37
encapsulation, 115
enumeration, 11
errno, 68
export, 66
false, 7, 30
for, 42, 43
function object, 76
game of life, 47
global, 7, 16

goto, 40
if, 37
istringstream, 29
iterators, 83
list, 91
long int, 10
main(), 63
map, 99
max(), 77
min(), 77
multimap, 99
multiset, 95
namespace, 26
ostringstream, 29
overloading, 64
plain pbm, 45
rand(), 44
reference, 50
seekg(), 30
seekp(), 30
set, 95
short-circuit evaluation, 14
sizeof, 24
spline fit, 46
srand(), 44
strerror, 70
struct, 20
swap(), 77
switch, 39, 43
true, 7, 30
typedef, 14
unsigned int, 10
unsigned long int, 10
vector<bool>, 26, 89
vector, 84
void, 10
while, 41, 43
||, 13
138


adapters
bind1st(), 77
bind2nd(), 77
not1(), 77
not2(), 77
ptr_fun(), 77
cast
static_cast, 22
double,
float,
function object

divides<T>(), 76
equal_to<T>(), 76
greater<T>(), 76
greater_equal<T>(), 76
less<T>(), 76
less_equal<T>(), 76
logical_and<T>(), 76
logical_not<T>(), 76
logical_or<T>(), 76
minus<T>(), 76
modulus<T>(), 76
multiplies<T>(), 76
negate<T>(), 76
not_equal_to<T>(), 76
plus<T>(), 76
functor, function object
iterators
bidirectional, 84
random, 84
long double,

int, 9
long int, 9
short int, 9
Fibonacci, 44

bubble sort, 73
insertion sort, 73
quicksort, 73
, reference
, function
object
, 21
, 7
, struct
, 115

139
, 117
, 45

Boole, 46
Durand, 46
Simpson, 46
, 46
, 117
, 82

Brent, 71
, 71
, 71
, cast
, 117

double, 10
float, 10
long double, 10
, 35

, 54
, 57
, 57
, 60
, 54
bit
, 25
<<, 25
>>, 25
&, 25
, 25
|, 25

You might also like