Professional Documents
Culture Documents
Νotes C++
Νotes C++
Νotes C++
c 20042011 , stamatis@materials.uoc.
Copyright
gr
LaTEX2.
c , (
).
21 2012.
http://www.materials.uoc.gr/el/undergrad/
courses/ETY215
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
25
26
28
28
29
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
41
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.4.5 . . . . . . . . .
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
4.11.2 . . . . . . . . . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
49
49
50
51
54
55
56
56
59
62
63
65
65
67
68
68
69
71
71
73
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
81
. 82
. 82
. 82
. 84
. 85
. 85
. 89
. 91
. 97
. 98
. 102
. 106
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
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 . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
iii
123
. 123
. 123
. 125
. 127
. 128
. 129
. 131
. 134
. 134
. 135
. 136
. 137
. . . !
139
Fortran C
143
.1 C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
.2 Fortran . . . . . . . . . . . . . . . . . . . . . . . . . . 144
147
157
159
160
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.
2
#include <iostream>
/*
main:
Takes no arguments.
Prompts for a real number and prints its square.
Returns 0.
*/
int
main() {
double a;
// Print result
// Change line
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
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
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
h
16 bits, 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 (
x X)
07. 0x 0X,
2.
10
( , ,
af AF).
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++
template class (6.3),
.
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). ,
, 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
// c = 3
int * a,b;
( ), a, ,
b. .
2.5.4
, , , 2 } block
.
.
(global) ,
(4.4), ( 6) namespace (2.8),
( #include).
, .
, ,
.
3
.
2
, .
2.6.
17
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 . , , ,
.
C++ :
[_];
_
, .
containers STL, 5.
2.
18
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
<<
<<
<<
<<
<<
(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
// Error
// a == {12,5,4,0,0}
( )
C Fortran . ( )
C C++
( ) .
C++ :
2.6.
19
[__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
:
[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);
.
,
:
:
2.
20
#include <vector>
#include <iostream>
int main() {
int N;
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"};
(.)
(.) :
3
2.7.
21
oxygen.name = "Oxygen";
oxygen.mass = 15.99494;
oxygen.Z = 8;
oxygen.symbol = "O";
std::cout
std::cout
std::cout
std::cout
std::cout
<<
<<
<<
<<
<<
(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;
2.
22
b = a-- + c;
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;
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
2.
24
// Wrong value
double mean1 = sum / N;
// Correct value
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.7.
25
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.
bit .
(short int, int, long int, bool, char) enum, signed unsigned.
2.5.
, 0 1 .
6
, byte
char.
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.8 (namespace)
(
)
. .. solve,
. C++ namespace ( )
. :
namespace onoma {
......
double a;
......
}
2.8. (NAMESPACE)
27
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;
return 0;
}
( ),
namespace :
using std::cout;
: namespace {...}.
namespace.
, ,
.
main() namespace
global.
2.
28
2.9 (streams)
( streams)
(std::cin) (std::cout) .
, streams, std::cerr std::clog, standard error .
, .. .
,
.. , ,
.. .
streams header <iostream>.
2.9.1
2.9. (STREAMS)
29
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() {
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,
2.
30
string, <<:
std::cout << a;
std::cerr << "Wrong value of b";
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
<<
<<
<<
<<
<<
<<
<<
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 :
2.9. (STREAMS)
31
int i;
while (inp >> i) {
.....
.....
}
, 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.ddddddDdd
fixed: dddd.dd
left/right: / .
header <iomanip>
setprecision() (
)
. 6.
setw()
( ) .
0.
setfill() setw() .
.
2.
32
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. C++ ;
() const
2.10.
33
() 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; ;
#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;
}
2.
34
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
() 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)
2.10.
35
() 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.
() 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 a2 + b2 = c2 . m, n m > n,
m2 n2 , 2mn, m2 + n2 .7 C++
.
20. Gauss
( 2099) :
7
2.
36
.
:
() 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 .
21. , , ,
.
: 200000,
: 2 days, 7 hours, 33 min & 20 sec.
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
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 ,
.
(?:) ,
. (=)
. ,
: (?:) (=) ,
. ,
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.2.
41
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 .
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);
1
C++ .
3.
42
do while:
1. block {}.
2. ( break, return, goto, throw,. . . ),
condition.
, .
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:
3.3.
43
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.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;
3.
44
if (j = 4) {
std::cout << "j is " << j << \n;
std::cout << "Should not print this!!!\n";
}
}
; ; . ;
3. C++
() (n!) .
() N Fibonacci2
f (n + 2) = f (n + 1) + f (n),
n 0,
f (0) = 0, f (1) = 1 .
() . .
() Lagrange 3 :
(
) .
: n,
a,b,c,d 0 a, b, c, d n.
n = a2 + b2 + c2 + d2 .
4. C++
e x
ex =
X
xn
,
n!
n=0
sin x
sin x =
X
(1)k x2k+1
k=0
(2k + 1)!
cos x
cos x =
X
(1)k x2k
k=0
(2k)!
.
1012 .
2
3
http://www.research.att.com/projects/OEIS?Anum=A000045
http://mathworld.wolfram.com/LagrangesFour-SquareTheorem.html
3.4.
45
5. 8 . std::rand() <cstdlib>
0 RAND_MAX.
RAND_MAX compiler;
std::srand().4
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
http://www.research.att.com/projects/OEIS?Anum=A047948
3.
46
10.
a, b, c 12
ax2 + bx + c.
x1,2 =
b2 4ac
.
2a
C++ std::sqrt()
<cmath>. .
( a = 0 a = b = 0;).
( b2 < 4ac).
11. 4 (, , ).
Ferrari6 .
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.
14. C++
Ax = B Gauss (Gauss elimination7 ).
A B
.
15. C++ A Gauss
Jordan (GaussJordan elimination8 ).
6
http://en.wikipedia.org/wiki/Quartic_function
http://mathworld.wolfram.com/GaussianElimination.html
8
http://mathworld.wolfram.com/Gauss-JordanElimination.html
7
3.4.
16.
47
() 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
x1
f (x)d x x
!
11
11
2
2
f1 +
f2 + f3 + + fn2 +
fn1 + fn .
5
10
10
5
fi f (xi ) x
. [10 sin(5)
50 cos(5)].
.
17. Spline Fit. n (xi , yi ).
2(n 1)
. , ( 2(n 2)
).
0 (2 ),
, . (2
). 4n 4 .
.
() spline
.
() .
()
.
3.
48
9
10
http://www.math.com/students/wonders/life/life.html
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
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;
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.
55
4.4.1
:
_
(__ , __ ,. . . )
{
//
}
void . ,
(, ,
). , ,
void. , ,
(})
.
, :
_ _ [ ]
. ,
,
. , int a[] int *a
.
, , . containers
STL 5 .
,
. compiler ,
( )
. .
( {}
) (;):
_
(__ , __ ,. . . );
.
.
.
,
( ),
, :
int func(double a, double b = 5.0);
func()
( a) b
, 5.0. ,
4.
56
, , 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
,
( ).
,
, .
,
.. , , .
.
read :
:
4.4.
57
#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.
double r;
read(r, "input.dat");
// calls function and ignores returned value.
}
( ).
.
.
. ..
#include <iostream>
void add3(double x) {
int
x+=3.0; }
4.
58
main() {
double z(2.0);
add3(z);
//
z = ???
// 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
.
, ,
, , . ,
(
). ,
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);
4.4.
59
x:
void f(double const & x);
, 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 ,
4.4.4
, headers, .h,3
3
compiler.
4.
60
#include "name.h"
name.h header, (, path ).
headers
("). , headers
(<>).
headers, compiler
. ,
,
, 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"
// 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() {
4.4.
61
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;
}
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.
62
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. , _
:
double f(double x);
// declaration of f(x)
4.5. MAIN()
63
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
4.5 main()
, main():
int main() {.....}
4.
64
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
4.6. OVERLOADING
65
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 (int, float,. . . ),
(, 6).
overloading
.
:
4
std::swap() <algorithm>.
4.
66
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):
template <typename X, typename Y, ... >.5
template <>
template
:
5
C++
1998
template
,
,
..
Standard
4.7. TEMPLATE
67
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 . header template.
4.7.1
template
(.. ) , compiler
. .. swap()
XOR swap .
swap() :
template<>
void
swap(int & x, int & y) {
x^=y;
y^=x;
x^=y;
}
4.
68
, swap<int>(a,b) (, ,
swap ) , .
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.10. C++
69
:
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);
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";
7
std::abort().
4.
70
, xi .
.
.
.
.
.
.
arctan(x/y).
<cmath>
double abs(double)
double ceil(double)
double floor(double)
.
.
.
.
, xa .
pow(double x, int i)
cos(double)
sin(double)
tan(double)
acos(double)
asin(double)
atan(double)
atan2(double x, double y)
double sqrt(double)
double pow(double x, double a)
double
double
double
double
double
double
double
double
cosh(double)
sinh(double)
tanh(double)
exp(double)
log(double)
log10(double)
modf(double d, double *p)
frexp(double d, int *p)
d 2i .
n/d.
double
double
double
double
double
double
double
double
double fmod(double d, double m)
double ldexp(double d, int i)
n/d.
.
.
.
.
(ln).
(log).
d.
x [0.5, 1) y d = x 2y .
x.
d/m.
int abs(int)
div_t div(int n, int d)
<cstdlib>
.
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.
.
.
*p.
y *p.
d.
4.11.
71
}
, std::strerror()
header <cstring>. errno
char * , .
4.11
4.11.1
,
, , : -
.
. (
) .
.
( )
.
.
Bubble sort
. O(n2 ) :
1. , .
, .
2. . , , .
3. .
,
.
,
!
Insertion sort
. O(n2 ) (
) O(n). :
4.
72
1. ,
.
2. , ,. . .
( ),
.
Quicksort
, , . O(n2 ) ( )
() O(n log n). , :
Quicksort
1. ,
( ).
2. . .
3. . , .
.
4. .
5. - .
Quicksort
1. ,
( ).
2. , .
3.
.
: .
.
4. ,
.
5. ,
( ).
.
6. - ( .
4.11.
73
Mergesort
. O(n log n). mergesort:
1. 0 1 , . :
2. .
3. () mergesort.
4.
.
4.11.2
1.
() .
() () .
;
() .
()
.
() .
()
.
() [a, b] .
()
P
, i ai bi .
2.
() e x
ex =
X
xn
,
n!
n=0
() sin x
sin x =
X
(1)k x2k+1
k=0
(2k + 1)!
() cos x
cos x =
X
(1)k x2k
k=0
(2k)!
4.
74
.
.
3. C++
Legendre, P` (x). P` (x) x [1, 1],
.
P0 (x) = 1 P1 (x) = x, `
:
Xn+1 = |100(ln(Xn )
(mod 1))|
X0 = 0.1.
5. A N 9
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 .
6. Cramer10 .
7.
( )
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
http://mathworld.wolfram.com/CliffRandomNumberGenerator.html
http://mathworld.wolfram.com/DeterminantExpansionbyMinors.html
10
http://mathworld.wolfram.com/CramersRule.html
9
4.11.
75
` = 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) .
.
Legendre, Pm
` (x).
, Y`m (, ).
50 100 Y`m (, ).
ylm_data sin cos , sin sin , cos ,
Y`m (, )Y`m
(, ) (, , x, y, z, ) ,
` = 2, m = 0 (, d-).
8. Hermite,
Hn (x) x. :
n2,
n (y) =
q
1
2n n!
Hn (y)ey /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.
76
() 12 . ,
,
f (x).
.
() Brent13 . ,
, , .
.
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. Sudoku. C++ sudoku.
9 9
, 3 3
1 9, ( ).
12
13
http://mathworld.wolfram.com/MethodofFalsePosition.html
http://mathworld.wolfram.com/BrentsMethod.html
4.11.
77
, .
:
()
1.
() . , 2, 3, .
.
, .
()
. 1 9,
. , . ,
, , ...
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 4/10
N , .
.
.
.
:
78
4.
N N . board. 0
.
N ..
column. ( i
column[i]).
, (, , ) board.
, ( 0) ( 1).
.
.
1 ,
.
.
.
, ,
.
.
, ,
. .
,
(N N ,
1 0.).
14. 5 5 .
,
( , , ).
.
. , ,
,
.
(
) . ,
( ) .
.
.
. .
4.11.
79
15. fractal :
, ( x = 0, y = 0),
(x0 , y0 )
x0
y0
=
=
ax+by+e
cx+dy+ f
a, b, c, d, e, f .
fractal (, x0 x y0 y
(x0 , y0 )). .
(x, y) , fractal.
:
() "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
0.85
0.04
0.2 0.26
0.15
0.28
0
0.04
0.23
0.26
0.16 0
0.85 0
0.22 0
0.24 0
0
1.6
1.6
0.44
0.01
0.85
0.07
0.07
0
0
0.95
0.005
0.035 0.2
0.04
0.2
0
0.005
0.16
0.16
0.25
0.93
0.04
0.04
0
0.002
0.09
0.083
0.4
0.5
0.02
0.12
0.02
0.84
0.07
0.07
, "fractal.dat" .
16. C++
.
17. C++
.
. ,
.
4.
80
18.
std::swap() std::min(), std::max() STL, 5.1.3.
19. std::vector<double> (
<vector>) , ,
(<, ) (=, )
([], subscripting).
20. std::sort() STL <algorithm>.
21. dlasrt() lapack14 .
14
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), . containers (container adapters) bitset,
STL, .
STL
headers (.. / , , , , ...)
. C, .
STL.
81
5. STANDARD LIBRARY
82
, 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).
first. ,
. , second
.
5.1.2
containers , ,
, , , .
(function object functor). ,
. ,
(()) 6.
header <functional>, C++
std .
5.1.
83
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>() -
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.
84
5. STANDARD LIBRARY
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
.
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);
5.2. (CONTAINERS)
85
, cmp
(()), 6.
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).
containers, STL, std.
5. STANDARD LIBRARY
86
containers , . , , ,
,
.
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,
container ( ),
[beg,end):
5.2. (CONTAINERS)
87
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
:
void f(std::vector<double> & c) {
std::cout << "Size of argument is " << c.size() << \n;
}
container ==,
!=, <, >, <=, >= . containers
, .
:
5. STANDARD LIBRARY
88
size()
empty()
true/false container
( size()==0 )
( )
iterator
iterator
reverse iterator
reverse iterator
max_size()
begin()
end()
rbegin()
rend()
5.2. (CONTAINERS)
89
:
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.
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, :
5. STANDARD LIBRARY
90
std::vector<double> v(10);
5.2. (CONTAINERS)
91
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.
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
. ,
, , .
:
1
std::iterator_traits<InputIterator>::difference_type.
5. STANDARD LIBRARY
92
vector
container. ,
.
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
.
std::vector<T> v1(v2);
2
constructor, 6.2.2.
5.2. (CONTAINERS)
93
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 .
v.assign(N,elem);
v N elem , , v.
5. STANDARD LIBRARY
94
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 (
).
v.push_back(elem);
elem vector.
.
resize()
. .
v.resize(N);
5.2. (CONTAINERS)
95
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.
,
vector :
([])
:
std::vector<double> v(3);
v[0] = 1.0;
v[1] = 3.0;
v[2] = v[1] + 5.0;
5. STANDARD LIBRARY
96
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;
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;
}
at().
5.2. (CONTAINERS)
97
5.2.4 deque
deque (double-ended queue) vector. sequence container , vector,
. ,
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
5. STANDARD LIBRARY
98
for (int i = 0; i != 10; ++i)
d.push_front(i);
// d is : {9, 8, ..., 0}
5.2.5 list
list, sequence container STL,
, vector deque. list
,
( )
, 5.1.
5.1: list.
, vector
deque, . ,
. , , sequence containers (
). :
list
( 5.2) .
,
iterators .
std::list header <list>.
5.2. (CONTAINERS)
99
6
?-
5.2: list.
5. STANDARD LIBRARY
100
c.resize(N);: N c.
,
. .
c.resize(N,elem);: ,
elem.
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.2. (CONTAINERS)
101
, 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
, , .
c1.merge(c2, op);
op().
reverse() list
.
5. STANDARD LIBRARY
102
:
#include <list>
#include <iostream>
inline bool
lessthan10(double a) {
return a < 10.0;
}
int main() {
std::list<double> c;
5.2. (CONTAINERS)
103
. , 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 .
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.
4
104
5. STANDARD LIBRARY
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 .
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.2. (CONTAINERS)
105
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. STANDARD LIBRARY
106
map . , template, K,
, T, -
5.2. (CONTAINERS)
107
.5
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
108
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.
.
:
, map
.
5.2. (CONTAINERS)
#include
#include
#include
#include
109
<iostream>
<string>
<map>
<utility>
int
main() {
typedef std::map<std::string, int> Map;
Map birthyear;
// Empty map.
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. STANDARD LIBRARY
110
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()
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>.
6
accumulate, count.
5.3. (ALGORITHMS)
111
:
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)
( ) ( ). :
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>.
112
5. STANDARD LIBRARY
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)
[beg,end)
value. associative containers
.
op() true.
Difference_type 1 .
:
a, std::vector v
, :
5.3. (ALGORITHMS)
113
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().
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()
114
5. STANDARD LIBRARY
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()).
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).
5.3. (ALGORITHMS)
115
swap_ranges()
Iterator
swap_ranges(Iterator beg1, Iterator end1, Iterator beg2)
[beg1, end1)
beg2 ( [beg2, beg2+(end1-beg1))).
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.
116
5. STANDARD LIBRARY
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()).
list (remove())
.
5.3. (ALGORITHMS)
117
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
set_union(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3,
BinaryFunctor op)
merge()
.
,
.
118
5. STANDARD LIBRARY
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
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
5.3. (ALGORITHMS)
119
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
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) .
5. STANDARD LIBRARY
120
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.
() 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) {
...
}
7
5.4.
121
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.
, ,
. a
odd.dat b
even.dat.
7. .
( )
( , ,
).
8. :
, , ( ), , , .
,
.
122
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];
// .......
std::size_t const M = 500;
std::string bookTitle[M];
std::string bookAythor[M];
// number of books
123
124
6.
int bookYear[M];
// .......
( ) ,
, .
,
. ( ,
, . , , ,
, , .) , ,
, , .
, , ,
.
,
.
, .
: ,
!
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];
6.1.
125
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);
,
.
.
, , ,
.
Student Book.
( )
( encapsulation). .
C++ struct
C
, . , class struct
, ( ) , :
, , .1
1
struct .
126
6.
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;
// ......
};
. (
, ) printStudent() printBook()
( )
(
). struct
(.). .
, print() s Student :
Student s;
// .... give values to s
s.print();
s print()
. ,
public: ( )
( )
. , {
private:
.
,
,
6.1.
127
.
, ..
class Student {
std::string name;
int AM;
// ......
public:
std::string getName() {return name;}
void setAM(int i) { AM = i;}
// ......
};
6.1.3
, , , , .
.
, , , ,
. ..,
(, , .) ,
() .
.
. , , ,
, ,
( , inheritance)
.
, ,
.
, ,
( ), , (
), .
( )
, , ,
,
.
( polymorphism).
, .
, , . -
6.
128
,
(
)
.
C++ .
6.2
, ( ),
:
. ,
. , ( ).
, 2.5.4, :
() (). . ,
( ) .
, ,
.
,
, , .
.
.
-
- .
.
.
, ,
.
, ,
Student .
6.2.
129
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 , ,
.
private:
class public:
struct.
,
class.
protected:, .
6.
130
// correct
// error
int y = s1.getYear();
int z = s2.getYear();
// correct
// correct
setYear() s1 s2 . getYear()
.
,
const ,
const.
,
, private , ,
public .
, , , (, ,
public) .
,
. , Student
print() setYear() :
class Student {
public:
// ............
int print() const;
void setYear(int y);
// ............
private:
std::string name;
int AM;
int Year;
};
6.2.
131
int
Student::print() const {
std::cout << name << << AM << << Year << \n;
return 0;
}
\begin{comment}>>\end{comment}
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
.
132
6.
,
.
.
costructors
. .
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);
,
costructor.
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 (:)
.
6.2.
133
, constructors, ( ), 4.6.
Student(){}. constructor . , Student,
name "" .
Student :
Student s;
Student s(); //function declaration, does not call Student()
s
Student.
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.
6.
134
copy constructor . ,
return3 .
X copy constructor, ,
, copy constructor, (X(X const & other)),
.
, 4.3, ( ) (.. ifstream, ofstream),
copy
constructor.
6.2.3
(Destructor)
6.2.4
(assignment operator)
, ,
(=,+,<, .). =
. ,
, . ..
Student s("George Thomson", 123, 2000);
Student t;
t = s; // operator= is called.
t=s; t.operator=(s);.
3
return.
4
return exception
6.2.
135
6.2.5
(=) ,
. , ,
. ,
.
operator.
2.4 (
) (.)
(sizeof).
136
6.
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>:
template<typename T>
class X {
T a;
...
void f(T v);
};
template<typename T>
void
X<T>::f(T v) {
...
}
6.4.
137
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
// 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 "
6.
138
d += 4;
g -= 3;
i = g;
}
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
139
. . . . !
140
#include <stdio.h>
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
141
#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
142
. . . . !
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 .
143
144
. FORTRAN 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
Fortran 77
C. . :
Fortran, , blas
lapack. ,
( ,
, .).
, .
.
dlasrt()
.2. FORTRAN
145
. lapack2
ID
(input) CHARACTER*1
= I: sort D in increasing order;
= D: sort D in decreasing order.
(input) INTEGER
The length of the array D.
INFO
(output) INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had
an illegal value
C++ (
, , compilers):
Fortran
INTEGER
REAL
DOUBLE PRECISION
LOGICAL
CHARACTER
COMPLEX
C++
int
float
double
bool
char
std::complex<float>
dlasrt SUBROUTINE
C++ void.
146
. FORTRAN C
, , 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);
,
. ( lapack
blas library) ( UNIX)
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)
std::cout << f0 << \n;
if (n > 1)
std::cout << f1 << \n;
147
148
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;
}
}
}
}
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;
}
149
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;
10. ax2 + bx + c.
#include
#include
#include
#include
<iostream>
<complex>
<cmath>
<iomanip>
150
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];
}
}
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] << ;
}
}
}
int
main() {
int const M = 512;
int const N = 512;
151
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];
}
}
152
}
}
4
5. A.
#include <vector>
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;
}
153
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;
}
}
//
#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,
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).
154
155
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);
++it1;
++it2;
}
return s;
}
156
[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.
[11] John R. Hubbard. Programming with C++.
McGrawHill, second edition, June 2000.
[12] John R. Hubbard. Fundamentals of Computing with C++. Schaums Outline Series. McGrawHill, May 1998.
157
158
2.1
2.2
2.3
2.4
2.5
C++. .
. . . . . . . .
C++. . . . .
.
bit C++. . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
. 6
. 8
. 13
. 23
. 26
. . . . . . . . . . . . . . . 70
5.1 . . . . . . . . . . . . . . . 83
5.2 . . . . . . . . . . . . . . 83
5.3 containers STL. . . . . . . . . . . 88
159
!, 13
, 35
int, 9
long int, 9
short int, 9
Fibonacci, 44
, 110
accumulate(), 110
binary_search(), 118
copy(), 114
copy_backward(), 114
count(), 112
equal(), 114
fill(), 115
find(), 113
for_each(), 112
generate(), 115
inner_product(), 112
max_element(), 113
merge(), 117
min_element(), 113
partial_sort(), 119
partial_sum(), 111
random_shuffle(), 120
remove(), 116
replace(), 116
replace_copy(), 116
reverse(), 117
reverse_copy(), 117
set_difference(), 118
set_intersection(), 118
set_symmetric_difference(),
set_union(),
sort(),
117
119
119
115
transform(), 115
stable_sort(),
swap_ranges(),
118
bubble sort, 71
insertion sort, 71
mergesort, 73
quicksort, 72
, reference
, function
object
, 21
, 7
, struct
, 125
, 127
, 45
, 47
Boole, 47
Durand, 47
Simpson, 47
, 127
, 87
, 75
, 76
Brent, 76
, cast
, 127
double, 10
float, 10
long double, 10
, 55
, 56
, 56
, 61
, 55
bit
160
161
, 25
false, 7, 30
for, 42, 43
function object, 82
divides<T>(), 83
equal_to<T>(), 83
greater<T>(), 83
&,
26
<<, 26
>>, 26
^, 26
|, 26
&&, 13
<<, 30
,, 25
<cerrno>, 69
<limits>, 10
<sstream>, 29
?:, 38
EDOM, 69
ERANGE, 69
NDEBUG, 41
RAND_MAX, 45
*/, 5
/*, 5
//, 5
adapter, 83
bind1st(functor,value),
bind2nd(functor,value),
83
83
ptr_fun(function), 83
assert, 41
bitset, 26
boolalpha, 30
bool, 6, 22, 30
, 14
, 30
vector<bool>, 26
break, 43
case, 39
cast
static_cast, 22
char, 7, 22
class, 125
complex, 11
constructor, 131
continue, 43
copy constructor, 131
deque, 97
destructor, 134
do while, 41, 43
else, 37
encapsulation, 125
enumeration, 11
errno, 69
not1(functor),
not2(functor),
greater_equal<T>(),
less<T>(),
83
83
logical_not<T>(), 83
logical_or<T>(), 83
minus<T>(), 83
modulus<T>(), 83
multiplies<T>(), 83
negate<T>(), 83
not_equal_to<T>(), 83
plus<T>(), 83
game of life, 48
global, 7, 16
goto, 40
if, 37
istringstream, 29
iterators, 89
bidirectional, 90
random, 90
list, 98
long int, 10
main(), 63
map, 106
max(), 84
min(), 84
multimap, 106
multiset, 102
namespace, 26
ostringstream, 29
overloading, 65
plain pbm, 46
rand(), 45
reference, 50
seekg(), 31
seekp(), 31
set, 102
short-circuit evaluation, 14
sizeof, 25
spline fit, 47
srand(), 45
strerror(), 71
struct, 20
less_equal<T>(),
logical_and<T>(),
83
83
83
83
162
swap(), 84
switch, 39, 43
true, 7, 30
typedef, 14
unsigned int, 10
unsigned long int, 10
vector<bool>, 26, 97
vector, 91
void, 10
while, 41, 43
||, 13
bool
, 7
double,
float,
functor, function object
long double,