Professional Documents
Culture Documents
C++ Notes
C++ Notes
c 20042015 , stamatis@materials.
Copyright
uoc.gr
LaTEX2.
c , (
).
10 2015.
http://www.materials.uoc.gr/el/undergrad/courses/ETY215
1
1.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1
1
4
2
2.1 . . . . . . . . . . . . . . .
2.1.1 . . . . . . . . . . . . .
2.1.2 . . . . . . . . . . . .
2.2 . . . . . . . . . .
2.2.1 . . . . . . . . .
2.2.2 . . . . . . .
2.2.3
2.2.4 . . . . . . . .
2.2.5 . . . . . .
2.2.6 void . . . . . . . . . . . . . .
2.2.7 Enumeration . . . . . . . . .
2.3 . . . . . . . . . . .
2.4 . . .
2.5 . . . . . . . .
2.5.1 typedef . . . . . . . . . . . .
2.5.2 . . . . . .
2.5.3
2.5.4 . . . . . . . . . . . .
2.6 . . . . . . . . . . . .
2.6.1 . . . . . . . . . . . .
2.6.2 (struct) . . . . . . . . .
2.7 . . . . . . . . .
2.7.1 . . . . . . . . .
2.8 (namespace) . . . .
2.9 (streams) . . . . . . . . . . . .
2.9.1 . . . . . . . . .
2.9.2 Strings . . . . . . . . . .
i
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
. . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
5
5
5
6
7
7
7
9
9
11
11
12
12
14
16
16
16
17
18
19
19
22
23
28
29
31
31
32
ii
2.9.3 . . . . . . . . . . . . . . . .
33
2.9.4 . . . . . . . . . . . . . . . . . . . . . . .
35
2.10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
36
43
3.1 . . . . . . . . . . . . . . . . . . . . . . . . .
43
3.1.1 if . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
43
3.1.2 ?: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
44
3.1.3 switch . . . . . . . . . . . . . . . . . . . . . . . . . . .
45
3.1.4 goto . . . . . . . . . . . . . . . . . . . . . . . . . . . .
47
3.1.5 assert()
. . . . . . . . . . . . . . . . . . . . . . . . . .
47
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
48
3.2.1 while . . . . . . . . . . . . . . . . . . . . . . . . . . . .
48
3.2.2 do while . . . . . . . . . . . . . . . . . . . . . . . . . .
48
3.2
3.2.3 for . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
48
3.2.4 continue . . . . . . . . . . . . . . . . . . . . . . . . . .
49
3.2.5 break
. . . . . . . . . . . . . . . . . . . . . . . . . . .
50
3.3 . . . . . . . . . . . . . . . . . . . . . .
50
3.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
50
59
4.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
59
4.2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
60
4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
61
4.4 . . . . . . . . . . . . . . . . .
65
4.4.1 . . . . . . . . . . . . . . . . . . .
65
4.4.2 . . . . . . . . . . . . . . . . . . . . . . . . .
67
4.4.3 . . . . . . . . . . . . . . . . . . . . . . . . . . .
67
4.4.4 . . . . . . . . . . . . . . . . . . . . .
71
4.4.5 . . . . . . . . . . . . . . . . . . .
74
4.5 main() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
76
4.6 overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . .
77
4.7 template . . . . . . . . . . . . . . . . . . . . . .
78
4.7.1 . . . . . . . . . . . . . . . . . . . . . . . .
80
4.8 inline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
81
4.9 . . . . . . . . . . . . . . . . . . . . . . . .
81
4.10 C++ . . . . . . . . . . . . . . .
82
4.11 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
84
4.11.1 . . . . . . . . . .
84
4.11.2 . . . . . . . . . . . . . . . . . . . . . . . . . .
86
5 Standard Library
5.1 . .
5.1.1 (Pair) . . . . . . . . . .
5.1.2 . . . . .
5.1.3 ,
5.2 (containers) . . . . . . . . .
5.2.1 . . . . . . . . . . . .
5.2.2 Iterators . . . . . . . . . . . . .
5.2.3 vector . . . . . . . . . . . . . .
5.2.4 deque . . . . . . . . . . . . . .
5.2.5 list . . . . . . . . . . . . . . . .
5.2.6 set multiset . . . . . . . . .
5.2.7 map multimap . . . . . . .
5.3 (algorithms) . . . . . . . .
5.4 . . . . . . . . . . . . . . . .
iii
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
. . . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
97
98
98
99
100
101
101
106
109
115
117
122
126
130
141
6
6.1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.1.1 . . . . . . . . . . . . . . . . .
6.1.2 (encapsulation) . . . . . . . . . . . . . . .
6.1.3 . . . . . . . . . . .
6.2 . . . . . . . . . . . . . . . . . . . . . . . . .
6.2.1 . .
6.2.2 (ConstructorsCopy constructor) . . . . . . . . . . . . . . . . . . . . . . . . . . . .
6.2.3 (Destructor) . . . . . . . . . . . . . . . .
6.2.4 (assignment operator) . . . . . . . .
6.2.5 . . . . . . . . . . . . . . . . . . . . . .
6.3 template . . . . . . . . . . . . . . . . . . . . . . . . .
6.4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
145
145
145
147
149
151
152
. . . !
163
155
158
158
159
160
161
Fortran C
167
.1 C . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
.2 Fortran . . . . . . . . . . . . . . . . . . . . . . . 169
173
185
189
190
iv
ISO C++,
, .
C++ , , ,
Fortran C. (
) C++ .
- C++,
Standard 1998,
, ,
.
, C++ C , STL ,
..
C++ 1 ( ).
http://www.dmst.aueb.gr/dds/faq/academic.html#oo
vi
.
, ,
.
, ,
, , .
(Fortran, C, C++) ,
, , ( ) .
.
, ,
,
.
.
, ,
.
C++ .
C++
.
1.1
:
. C++
1
1.
,
:
#include <iostream>
/*
main:
Takes no arguments.
Prompts for a real number and prints its square.
Returns 0.
*/
int
main() {
double a;
// Print result
// Change line
1.1.
C++.
, , (return 0;) ,
} ( 0).1 0 main() .
.
,
main(). main()
.
double a;
() 15 a (2.2.5).
C++ ,
compiler, .
std::cin std::cout , , standard input ()
standard output () . (<<), () ,
( ) std::cout ( ). , (>>) std::cin (
) . , ,
standard header <iostream> (2.9). ,
, C++ format
/ .
. , ,
..
(2.9.4).
(") , C-style string. \n ( ),
. ()
( , (\))
(character literal, 2.2.2).
(*)
.
(;)
(, ,
).
( #) ;.
1
main() .
1.
C++
, .
C++ .
( ). , ,
(+=, ==, <<,
/*, //,. . . ). , , //
.
( )
#.
1.2
1. , .2
2. . +,-,*,/
( ). .
3. C++ ;
#include <iostream>
main(){std::cout << Hello World!\n}
4. C++ ;
5. C++ ;
include iostream.h
Main();
{
Double x,y,z;
cout < "Enter two numbers ";
cin >> a >> b
cout << The numbers in reverse order are << b,a;
}
2
compiler
.
2.1
2.1.1
C++ . compiler
// ,
/* */ .
/* */
tab, .
.
:
// This is a comment
int j; // Here is a declaration
/* Let us make
an ugly multi-line
comment.
/
*
, , ,
.
. ,
: compiler
5
2.
#if 0
.....
#endif
,
( ). ,
#
.
2.1.2
, , , . C++
(az,AZ), (09), underscore
(_). .
C++ ,
. underscore (_)
compiler
. ,
C++ (Keywords, 2.1) , , , .
:
:
ena lathos onoma, pali_latho$, 1234qwer, delete, .onoma+
:
timi, value12, ena_onoma_me_poly_megalo_mikos, sqrt, Delete
C++ Keywords
and
bool
compl
do
export
goto
namespace
or_eq
return
struct
try
using
xor
and_eq
break
const
double
extern
if
new
private
short
switch
typedef
virtual
xor_eq
asm
case
const_cast
dynamic_cast
false
inline
not
protected
signed
template
typeid
void
auto
catch
continue
else
float
int
not_eq
public
sizeof
this
typename
volatile
bitand
char
default
enum
for
long
operator
register
static
throw
union
wchar_t
2.1: C++.
bitor
class
delete
explicit
friend
mutable
or
reinterpret_cast
static_cast
true
unsigned
while
2.2.
2.2
C++
:
2.2.1
(bool)
(.. /, /,. . . ). , .. a, :
bool a;
true false. , a
, (4.4),
( 6) namespace (2.8), (global)
false.
:
bool a = true;
, ,
bool a(true);
bool , , , . ,
true 1 false 0. , true 0
false. , (4.3)
true false.
2.2.2
(char) .. c,
:
char c;
, ,
ASCII.
char c = a;
, ,
2.
char c(a);
c
, a.
() (") C-style string1
char.
. 2.2,
( ) . ..
char
char
char
char
newline(\n);
bell(\a);
alpha(\141); // alpha = a in ASCII
Alpha(\x61); // Alpha = a in ASCII
C-style
string.
:
std::cout <<
"This\nis\na\ntest\n\nShe said, \"How are you?\"\n";
This
is
a
test
She said, "How are you?"
char , namespace
, ,
.
(\0, 0 ASCII),
0 ( 48 ASCII).
,
int ( ) .
, , char signed unsigned.
2.2.
\?
\
\"
\\
\a
\b
\f
\n
\r
\t
\v
\xhhh
\ooo
\0
Carriage return
tab
tab
hhh
ooo
2.2: .
2.2.3
C++ wchar_t
256 . ..
256
.. ASCII.
2.2.4
(.. int) :
int i;
, namespace,
i 0, .
(.. 10)
int i = 10;
, ,
int i(10);
. int
16 bits,
h
15
15
2 , 2
= [32768, 32768) .
2.
10
std::numeric_limits<int>::min()
std::numeric_limits<int>::max()
header <limits>:
#include <limits>
#include <iostream>
int
main() {
std::cout
std::cout
std::cout
std::cout
<<
<<
<<
<<
std::numeric_limits<int>::min();
\n;
std::numeric_limits<int>::max();
\n;
return 0;
}
C++ , short int, int long int,
16, 16, 32 bits . ,
short int int
long int.
, char,
sizeof() , 2.7.1.
signed () unsigned.
, int. C++ int
int
.
, 0, .
, + . 0 ( x X)
07. 0x 0X,
( ,
, af AF).
long int L l
:
12L, 0xBABEL, -665l
2.2.
11
U u unsigned int,
unsigned long int.
2.2.5
C++ :
(float), (double) (long double).
float
double long double.
float
std::numeric_limits<float>::digits10
std::numeric_limits<float>::min()
std::numeric_limits<float>::max()
header <limits>.
. std::numeric_limits<>::min()
.
, double, .
, (
) double.
. e
E, , 10
e/E :
2.034,
0.23,
.44,
23.,
2e4
( 0.0002),
2.3E2 ( 230.0) .
F f float L l
long double.
2.2.6 void
void
. ,
2.
12
. void* ( void) .
.
2.2.7 Enumeration
Enumeration ()
. ..
Color c(RED);
switch
(3.1.3), compiler . ,
(4.4).
:
0. RED 0,
GREEN 1 BLUE 2.
,
1 :
Color d(2);
2.3
// Error
C++ template class (6.3),
.
C++
header <complex>
#include <complex>
2.3.
13
.
(.. z) , double :
std::complex<double> z;
// z = 0.0 + 0.0 i
, double
(int, float, long double,. . . ).
, 0, ,
STL.
:
std::complex<double> z1(3.41);
// z1 = 3.41 + 0.0i
// or z1 = 3.41;
std::complex<double> z2(3.0,2.0);
// z2 = 3.0 + 2.0i
std::complex<double> z3(z2);
// z3 = z2
// or z3 = z2;
std::complex<double> z4(std::polar(2.0));
// z4 = 2.0 exp(0.0i)
std::complex<double> z5(std::polar(2.0,0.75));
// z5 = 2.0 exp(0.75i)
std::polar() (magnitude)
(phase angle) ( rad) .
+,-,*,/ +=,-=,*=,/= (2.7)
,
. ,
C++ (4.1) ,
. std::abs()
. , std::norm() std::arg()
z = + i
std::abs(z) = 2 + 2 ,
std::norm(z) = zz * 2 + 2 ,
std::arg(z) = arctan(/ ).
, std::conj() .
, ,
.
2.
14
z
, std::real(z) std::imag(z),
std::complex<>, z.real()
z.imag().
,
compiler:
std::complex<double> z(3.0,1.0);
// z = 3.0 + 1.0i
z = std::complex<double>(z.real(), 3.7);
// z = 3.0 + 3.7i
z = std::complex<double>(2.3, std::imag(z));
// z = 2.3 + 3.7i
z = 5.0; // or z = std::complex<double>(5.0);
// z = 5.0 + 0.0i
z = std::complex<double>(-1.0, 2.0);
// z = -1.0 + 2.0i
<<
(,)
>>
:
(,)
()
, , typedef (2.5.1).
2.4
C++
( 2.3). -
==
>
>=
!=
<
<=
2.3: C++.
true false. .. 3.0>2.0 true
2.4.
15
2!=1+1 false. . ,
, (==, ) (!=, ). ,
.
C++ !
(NOT), && (AND), || (OR). ,
, not, and or .
&& ||
! :
!
:
! (4 > 3) false.
! (4 < 3) true.
&& true true.
false:
(4 > 3) && (3.0 > 2.0) true
(4 < 3) && (3.0 > 2.0) false
|| true true,
false:
(4 > 3) || (3.0 < 2.0) true
(4 < 3) || (3.0 < 2.0) false
C++, bool:
bool a(3==2);
bool b = ( (i > 0) && (i < max) );
C++:
(short-circuit
evaluation). ..
2.
16
i >= 0 false
i > max.
.
2.5
2.5.1 typedef
, . , ,
typedef. , .. std::complex<double>
complex
:
complex z;
typedef
: .
double. ,
double float. ,
real
2.5.2
,
compiler , ,
.
const
( ) :
2.5.
17
2.5.3
block block
. .
( ) , ,
. , ,
namespace ( global) ,
0 ( ). ,
static (4.9),
compiler .
C++
, C:
int a = 3;
2.3,
(
C++)
. C++
,
int b = 4;
int b(4);
, (.. int) (.. std::complex<double>), :
2.
18
int c = int(3);
// c = 3
int a;
int b;
int a,b;
. ..
int * a,b;
( ), a, , b.
.
2.5.4
, , , 2 } block
.
.
(global) ,
(4.4), ( 6) namespace (2.8),
(
#include).
,
. ,
2
, .
2.6.
19
, .
3
.
block . ..
#include <iostream>
int
main()
{
double x(3.2);
{
// begin block A
// begin block B
int x(5);
std::cout << x;
// prints 5
// end
block B
std::cout << x;
// prints 3.2
return 0;
}
// end
block A
x block x block x
x. block x x.
.
2.6
, , .
(array) ( ) (struct)
, (class).
2.6.1
.. ,
( array)
365 .
2.
20
, , ,
.
C++ :
[_];
_ , .
containers STL, 5.
temperature
365
( int):
double temperature[365];
int const N(155);
int telephone[N];
telephone
.
, .. temperature, 0 D 1
D . , , 0.
..
temperature[0]
temperature[1]
temperature[2]
temperature[3]
temperature[4]
//.........
=
=
=
=
=
14.0;
14.5;
15.5;
13.0;
15.0;
int i(3);
std::cout
std::cout
std::cout
std::cout
std::cout
<<
<<
<<
<<
<<
(index) ,
0 D1 compiler
( !).
( )
.
compiler
.
, , ,
0 ( ):
2.6.
21
// size is 10
// Error
// a == {12,5,4,0,0}
( )
C Fortran
. (
) C C++
( ) .
C++ :
[__1][__2];
.
6 8
, -
int a[6][8];
.. (3,2) a[3][2].
, :
2.
22
C ,
Fortran , , .
, C++ . , Standard
Library (STL)
.
std::vector<> header <vector>: v, 30 .. double
std::vector<double> v(30);
. ,
:
:
#include <vector>
#include <iostream>
int main() {
int N;
std::cin >> N; // get dimension
std::vector<double> v(N);
// v[0], v[1], ..., v[N-1]
}
, v C++.
std::vector<> 5.
2.6.2
(struct)
.. . , , , ,
, .
,
.
C++ std::string header <string>.
,
, :
2.7.
23
struct ChemicalElement {
double mass;
int Z; // atomic number
std::string name;
std::string symbol;
};
(;) }. (
) C++
};.3
ChemicalElement struct , ,
( ) .
. ChemicalElement
:
ChemicalElement oxygen;
, , ..
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++
:
2.
24
+,-: a
.
+,-,*: a,b , .
/ a,b: a/b.
/,%
.
. std::pow() header <cmath>
( 4.1).
C++
(=): a = a + b; a+=b;.
(+=, -=, *=, /=, %=)
=. ,
a
.
C++ ++ -- (
) .
, .. b = ++a + c; 1
a, a
. , .. b = a++ + c;
1 a .
( 1) --.
b = --a + c;
a = a-1;
b = a + c;
b = a-- + c;
b = a + c;
a = a-1;
++ -- , , ,
,
.
2.4 . ,
2.7.
25
. .
( ) compiler
. .. a--b
(a--)b ( ) a-(-b). .
compiler ( , )
. .. int
double int double
. int ( bool char) int
, .
: .. bool
char;
, (
) .
, .. .
. ,
( )
.5
int a = 3.14; // a is 3
short int b = 12121212121.3;
// b = ??
. , (/) .
() /.
static_cast:
int sum = 2 + 3 + 5;
int N = 3;
// Wrong value
double mean1 = sum / N;
// Correct value
5
compiler .
2.
26
C++
/ ( )
/ ( )
bitwise NOT
NOT
/
( )
bitwise AND
bitwise XOR
bitwise OR
AND
OR
4
bitwise AND
bitwise XOR
bitwise OR
.
->
()
[]
++, -sizeof
sizeof()
++, --
&
*
!
+, *
/
%
+
>>, <<
<
<=
>
>=
==
!=
&
^
|
&&
||
?:
=
*=
/=
%=
+=
-=
<<=
>>=
&=
^=
|=
,
2.4: (
) .
.
4
2.7.
27
static_cast<newtype>(variable);
:
(newtype) variable.
.
overloaded ,
. .. , std::sqrt() <cmath> float,
double, long double int
. 4.6,
compiler C++ ,
:
#include <cmath>
int
main() {
int p = 8;
double riza = std::sqrt(p);
// Error, ambiguous
double r = std::sqrt(static_cast<double>(p));
// Correct. Calls sqrt(double).
}
C++
, ..
int a;
int b;
b = a = 3;
//First a = 3; then b = 3;
bool cond;
cond = b < 5;
// First check b < 5; true. Then cond = true.
2.
28
2.7.1
sizeof
sizeof bytes.6
sizeof:
int a;
std::cout << sizeof(int);
// parentheses are necessary
std::cout << sizeof(a);
std::cout << sizeof a;
.
.
sizeof (array) bytes
, ,
. ,
double a[13];
int k = sizeof(a) / sizeof(a[0]);
// k == 13
.
sizeof
, ,
.
sizeof std::size_t, <cstddef>.
.
(,)
(,).
.
bit
bits
, 0 1.
6
, byte
char.
2.8. (NAMESPACE)
29
bit .
(short int, int, long int, bool, char) enum, signed unsigned.
2.5.
<<
>>
&
^
|
<<=
>>=
&=
^=
|=
bitwise NOT
bitwise AND
bitwise XOR
bitwise OR
bitwise AND
bitwise XOR
bitwise OR
expr
expr1 << expr2
expr1 >> expr2
expr1 & expr2
expr1 ^ expr2
expr1 | expr2
expr1 <<= expr2
expr1 >>= expr2
expr1&=expr2
expr1 ^= expr2
expr1 |= expr2
2.8
(namespace)
(
)
. ..
solve, -
30
2.
. C++ namespace ( )
. :
namespace onoma {
......
double a;
......
}
a ( , , , . ) namespace onoma.
namespace : onoma::a. namespace (a).
. ,
namespace .
namespace C++
(2.1.2).
Standard Library (STL) namespace std. cin,
cout, complex std::. , namespace
.. std, using namespace std;
block .
block std::. ..
#include <iostream>
#include <complex>
// "std::" needed here
typedef std::complex<double> complex;
int
main() {
using namespace std;
// "std::" not needed here
complex a(2.0,3.0);
complex<double> b(1.0);
// In the following cout "std::" is not needed
cout << a;
cout << \n;
cout << b;
cout << \n;
2.9. (STREAMS)
31
return 0;
}
( ), namespace
:
using std::cout;
: namespace {...}.
namespace.
, ,
.
main() namespace
global.
2.9
(streams)
2.9.1
std::ifstream inpstr("filename");
stream , inpstr,
"filename". , .
,
std::ofstream outstr("filename");
2.
32
double a(10.0);
outstr << a;
char c;
inpstr >> c;
a
outstr c
inpstr.
.
stream str (..
),
: str.close();. stream str
str.open("filename");.
2.9.2
Strings
(streams) , .
C++ strings, .
header <sstream> , std::istringstream std::ostringstream.
ostringstream C++ string
. string, .
C++ string
"filename_3.dat":
#include <sstream>
int
main() {
2.9. (STREAMS)
33
std::ostringstream os;
os << "filename_";
os << 3;
os << ".dat"; // os contains the string "filename_3.dat"
}
string str(),
ostringstream:
std::ofstream outstr(os.str().c_str());
std::istringstream string
:
#include <sstream>
int
main() {
std::istringstream is("5 6 7 a");
int i,j,k;
is >> i;
is >> j;
is >> k;
// i = 5
// j = 6
// k = 7
char ch;
is >> ch;
// ch = a
2.9.3
,
STL, (stream) standard output, standard
error, string, <<:
std::cout << a;
std::cerr << "Wrong value of b";
std::cin
>>, :
double a;
int b;
2.
34
std::cin >> a;
std::cin >> b;
( ) .
<<, >> . ..
std::cout
std::cout
std::cout
std::cout
std::cout
std::cout
std::cout
<<
<<
<<
<<
<<
<<
<<
bool (2.2.1)
.
int i;
while (inp >> i) {
.....
.....
}
2.9. (STREAMS)
35
, inp >> i
inp. i ,
true while.
streams
get(),
EOF (
eof() true).
is ( 3.2.1)
2.9.4
(manipulators) C++,
boolalpha noboolalpha, , bool. header <ios>
(no)skipws: () .
(no)showpos: () + .
(no)showpoint: () 0 .
scientific: d.dddddd Ddd
fixed: dddd.dd
left/right: / .
header <iomanip>
setprecision() (
) . 6.
setw() ( ) .
0.
setfill()
setw() . .
2.
36
#include <ios>
#include <iomanip>
#include <iostream>
int
main() {
double b = 3.25;
std::cout << b << \n;
std::cout << std::showpoint << b << \n;
std::cout << std::noshowpoint;
// reset
double a = 256.123456789987;
std::cout << "default\t"
<< a << \n;
std::cout << "scientific\t" << std::scientific
<< a << \n;
std::cout << "fixed\t" << std::fixed
<< a << \n;
std::cout << "with 9 digits\t"
<< std::setprecision(9)
<< a << \n;
}
,
, precision, width fill, setprecision,
setw setfill :
#include <iostream>
int
main() {
std::cout.precision(9);
std::cout << 256.123456789987 << \n;
}
2.10
1. , .
C++
.
2.10.
37
2. C++ ;
() const
() johns
() y+z12
() 1stclass
() xyz123
() George
() ThisIsALongOne
() To_onoma_mou
() two-way
() proto
() _posotita
3. C++ stream
std::cin
std::cout
std::cerr
std::clog
4. C++
//
{
;
#
5. ;
int a = 2, b = 3, c = 4;
double x = y = 5;
bool equal = b = 3;
int d = d;
int e = "e";
6. compiler;
;
7.
compiler; ;
2.
38
#include <iostream>
#include <limits>
int
main() {
int a = std::numeric_limits<int>::min() - 10;
int b = std::numeric_limits<int>::max() + 10;
" << b << \n;
std::cout << a << "
return 0;
}
8.
() Euler.
() .
() .
() .
() .
9. C++
:
() 37/(5*2)
() 37/5/2
() 37(5/2)
() 37%(5%2)
() 37%5%2
() 37-5-2
() (37-5)2
10. m = 24 n = 8:
() m-8-n
() m==n-3
() m%n
() m%n++
() m%++n
() ++m=n-() m=n=3
() m+=n-=2
2.10.
39
() m*=++n
() m+=--n==m-11. :
() (50 - 5 * 4) / 10 - 7
() 12 + -5 * 2 + 6 / 3
() 1 + 2 + 3 + 4 + 5 + 1 * 2 * 3 / 4 * 5
() 3 > 7
() (3 > 7) || (4 < 9)
() 135 == 100 + 35
() (true && false) || (true || false)
() (3 > 7) || ((10 < 9) == (3 == 8))
() false || !(3 > 7)
() 3!=6
() 6 / 4 * 5 == 6 * 5 / 4
12.
() 7 / 2
() 7.0f / 2
() ((7 / 2) == (7.0 / 2))
() ((6 * 3) / 80) / (36 - 7 * 5)
13. C++
1 n.
14. a, b
c a.
15.
() ++x+=+a++-+b++
() ++x-=-a+b++
() -x---a---b-16.
; .
17. C++ :
() d.
() r.
2.
40
() d h.
() c
a,b .
18.
:
() a==b||a==c&&c<5
() c=x!=0
() 0<=i<6
() a=b==c++
19. a, b, c a 2 + b2 = c 2
. m, n
m > n,
m 2 n 2 , 2mn, m 2 + n 2 .7 C++
.
20. Gauss
( 2099)
:
.
:
() r1 = 19.
() r2 = 4.
() r3 = 7.
() ra = 19r1 + 16.
() r4 = ra 30.
() rb = 2r2 + 4r3 + 6r4 .
() r5 = rb 7.
() rc = r4 + r5 .
rc 3 , .
C++ .
rc .
2.10.
41
21. , , ,
.
: 200000, : 2 days, 7 hours, 33 min & 20 sec.
42
2.
3.1
3.1.1 if
if
. ()
, . C++
:
if (condition) {
...
// block A
} else {
...
// block B
}
(condition) ,
block {} (block
A). , block
else (block B).
block , ,
.
({}) . ..
if (condition) {
...
}
43
3.
44
block
if. if (condition) {...} else {...} . block
() .
.
if, else . else
if block. ,
, :
if (i == 0)
if (val > max)
max = val;
else
max = 10;
, max = 10; i 0
(val > max) (i == 0).
:
if (i == 0) {
if (val > max)
max = val;
}
else
max = 10;
3.1.2 ?:
(?:) C++.
if (condition)
val = value1;
else
val = value2;
3.1.
45
(?:)
, . (=),
. ,
: (?:) (=)
,
. ,
a = b ? c : d
a = (b ? c : d)
a ? b : c = d
a ? b : (c = d)
3.1.3 switch
switch if. :
switch (i) {
case value1:
...
case value2:
...
...
...
case valueN:
...
default:
...
}
i (char, int, (short int,
long int) signed unsigned ) enum.
.
value1, value2,. . . ,valueN
enum ( ).
, i
value1, value2,. . . ,valueN. , case.
3.
46
case / default ,
break ( .. goto, return,
throw). break switch. value1,
value2,. . . ,valueN block default, .
, } switch.
case default .
:
.
+, -, *, /.
.
#include <iostream>
int
main() {
double a, b, res;
char c;
std::cin >> a >> b;
std::cin >> c;
switch (c) {
case +:
res = a + b;
break;
case -:
res = a - b;
break;
case *:
res = a * b;
break;
case /:
res = a / b;
break;
default:
std::cerr << "wrong character\n";
return -1;
}
std::cout << "the result is " << res << \n;
}
3.1.
47
3.1.4 goto
(label). (.. labelname)
.
labelname : statement;
goto:
goto labelname;
goto
.
goto . C++
(3.2) goto . ,
,
. , goto
.
3.1.5 assert()
C++
header <cassert> macro1 assert().
:
assert(integer_number);
integer_number 0, ,
NDEBUG header. ,
assert()
.
, assert() debugging, 0 false ( , 2.2.1), . .. assert(N<10);,
(N<10).
#define NDEBUG
.
std:: (
std) macro .
1
C++
.
3.
48
3.2
3.2.1 while
while , . :
while (condition) {
...
}
while:
1. condition
,
.
block
{}.
2. block ( break, return, goto,
throw, . . . ), 1 ( ).
.
3.2.2 do while
do while while (3.2.1)
. :
do {
...
} while (condition);
do while:
1. block {}.
2. ( break, return, goto, throw,. . . ),
condition.
,
.
1 ( block).
3.2.3 for
for
. C++ for .
:
3.2.
49
std::size_t i;
for (i = 0; i < 10; ++i)
a[i] = i*10;
// here i is 10
3.2.4 continue
continue for,
while, do while.
, .
3.
50
3.2.5 break
break while,
do while, for, switch.
,
.
3.3
block , , . ({}) .
if while
( ) . .
:
if (int j = 3) max = 10 + j;
j if.
(3) true.
3.4
1.
()
for (;;) {
...
}
() for
while. do while;
2. :
#include <iostream>
int
main() {
int j = 3;
if (j = 4) {
std::cout << "j is " << j << \n;
std::cout << "Should not print this!!!\n";
}
}
; ; .
;
3.4.
51
3. C++
() (n!) .
() N Fibonacci 2 .
f (n + 2) = f (n + 1) + f (n ),
n 0,
f (0) = 0, f (1) = 1 .
() . 3 .
() Lagrange 4 :
( ) .
: n,
a,b,c,d 0 a, b, c, d n.
n = a 2 + b2 + c 2 + d 2 .
4. C++
ex
ex =
X
xn
n =0
n!
sin x
sin x =
X
(1)k x 2k +1
k =0
(2k + 1)!
cos x
cos x =
X
(1)k x 2k
k =0
(2k )!
.
1012 .
5. 8 .
std::rand() <cstdlib> 0 RAND_MAX.
RAND_MAX compiler; std::srand().5
2
http://oeis.org/A000045
http://en.wikipedia.org/wiki/Euclidean_algorithm
4
http://mathworld.wolfram.com/LagrangesFour-SquareTheorem.html
3
3.
52
6.
http://oeis.org/A047948
3.4.
53
10.
a, b, c 12
ax 2 + bx + c.
x1,2 =
b2 4ac
2a
C++ std::sqrt()
<cmath>. .
( a = 0 a =
b = 0;).
( b2 < 4ac).
11. 4 (, , ).
Ferrari 7 .
12. M N K
1 0. 1
.
() ( M = 20, N = 60, K = 400)
, x
o .
() .ppbm
( M = N = 512, K = 150000):
: P1.
: (.
).
1 0
( ).
plain pbm (portable bitmap) .
13. A (M N ) B (N P). M = 10, N = 20, P = 30
A, B matA.dat
matB.dat. ,
. matC.dat
C = A B.
7
http://en.wikipedia.org/wiki/Quartic_function#Ferrari.27s_
solution
3.
54
14. C++
Ax = B Gauss8 .
A B .
15. C++ A Gauss
Jordan 9 .
16.
() 30
f (x ) = x (x 2 + 5 sin(x ))
[5 : 5]. C++ std::sin()
<cmath>.
() C++ f (x )
[5 : 5]
: x1 , x2
x2
f (x )dx
1
2
x1
x (f1 + f2 ) .
Simpson:
x1 , x2 , x3
x3
f (x )dx
1
3
x1
x (f1 + 4f2 + f3 ) .
Boole: x1 ,
x2 , x3 , x4 , x5
x5
f (x )dx
x1
2
45
Durand: n x1 ,
x2 , . . . , xn
xn
f (x )dx x
x1
2
5
f1 +
11
10
f2 + f3 + + fn 2 +
11
10
fn 1 +
2
5
fn .
fi f (xi ) x .
[10 sin(5) 50 cos(5)].
.
8
9
http://mathworld.wolfram.com/GaussianElimination.html
http://mathworld.wolfram.com/Gauss-JordanElimination.html
3.4.
55
http://www.math.com/students/wonders/life/life.html
56
3.
, (,
).
19. 1 , 2 , 5 , 10 ,
20 , 50 , 100 (= 1) 200 (= 2).
. 300 ;
: , 300
, 150 , 60 5
.
300 .
20.
:
: P3.
: (
).
K .
255.
pixels
.
(R), (G), (B) pixel, . pixel
K 0 0 ( K 255
255 0 0). pixel 0 K 0. 0 0 0
K K K. RGB 0 K
.
plain ppm (portable
pixmap) .
france.pppm
, .
21. p(z ). z0 ( p0 (z0 ) , 0)
p(z ), p(z ),
3.4.
57
:
p(zi )
,
zi +1 = zi 0
p (z i )
i = 0, 1, 2, . . . .
, z0 ,
z1 . z2 ,
.,
p(z ). Newton
Raphson , .
p(z ) = z 3 1
a = 1, b = ei2/3 , c = ei2/3 .
( z = 0 + i0) .
. , ..: a
(RGB = (255,0,0)). b
(RGB = (0,255,0)) c
(RGB = (0,0,255)). 0 +i0
RGB = (255,255,255).
() N = 512
[1 : 1] ( ): xi , i = 0, . . . , N
1.
() M = 512
[1 : 1] ( ): yj , j = 0, . . . , M
1.
() z = xi + iyj
.
() pixels (i, j)
newton.pppm plain ppm (
20).
newton.pppm Newton fractal.
58
3.
4.1
C++,
. , , , main(), , ,
. ,
, .
, , , ,
main() , .
, .
, ,
. .., ,
,
, ,
.
,
.
( structured) ( procedural)
C++.
, C++ .
59
4.
60
4.2
(reference) . ,
.., a
int a;
(.. r) a :
int & r = a;
r
a.
, &.
( )
( , , ). ,
.
, a r :
int a;
int & r = a;
a = 3;
r = 2;
// r = 3
// a = 2
int b = a;
// b = 2
int c = r--;
// c = 2, a = 1
int d;
int & r = d;
// Error
const,
:
int const a = 5;
int & r1 = a;
// Error
4.3.
61
. , <limits> std::numeric_limits<double>::digits10. :
#include <limits>
#include <iostream>
int
main() {
int const & digits = std::numeric_limits<double>::digits10;
std::cout << digits << \n;
}
,
.
:
4.3
, , .
,
, (&) .
( )
.
* _;
int a = 3;
&a a
, p,
int * p = &a;
p (*) p. ,
4.
62
, *p
a
*p a. ..
double r = 5.0;
double * q = &r;
*q = 3.0; // r becomes 3.0
void1 :
int
int
p =
int
a = 4;
* p;
&a;
* q = p;
int * q = p; q int
p. , q p , , *q
*p ( a).
int a = 5;
int * p = &a;
void * t = p;
void p, int,
, , a. (*)
p a , ( *) t
. , void
static_cast<> ( )
. ,
int * v = static_cast<int*>(t);
*v = 4;
a 4.
. (*)
.
. ,
( )
.
1
void * .
4.3.
63
0. 0
, , . (null
pointer) (*) (
). (.. ) 0 (
, 2.2.1)
.
: , ,
.
.
(
):
int a;
int
int
int
int
* p1 = &a;
const * p2 = &a;
* const p3 = &a;
const * const p4 = &a;
p1 .
p2 .
*p2.
p3 .
*p3
.
p4 .
.
:
.
:
double x = 1.2;
double * const p = &x;
double y = 0.1;
4.
64
p = &y; // error
double const * q = &x;
*q -= 0.2; // error
int const a = 2;
int * r = &a; // error
p ,
*p. , p . ++,--( )
: T
sizeof(T) . , (.. p+2)
sizeof(T). , , ,
( !) .2
void
, ,
( void *).
. ,
:
int a[10];
int * p = &a[3];
int * q = p + 2;
// q == &a[5]
int a[10];
int * p = &a[0];
*(p+i) a[i] , ,
p+i == &a[i].
.
,
. a[i]
*(a+i). , 2
std::ptrdiff_t <cstddef>.
4.4.
65
.
:
:
double b[10];
double * p = b;
for (int i = 0; i < 10; ++i)
*p++ = 1.0;
double b[10];
for (double * p = b; p != b+10; ++p)
*p = 1.0;
2.6.2 , .. member,
(struct) , , , .. a, :
a.member
, pa,
[ (*) (.), 2.4]
(*pa).member
C++
, :
pa->member
4.4
.
, , 4.7, .
. ,
.
4.4.1
4.
66
__
(__ , __ ,. . . )
{
//
}
void
. ,
(, ,
).
, , void. , ,
(}) .
, :
_ _ [ ]
. ,
,
. , int a[]
int *a .
, ,
. containers STL 5
.
,
. compiler ,
( )
.
.
(
{} ) (;):
__
(__ , __ ,. . . );
.
.
.
,
( ),
, :
4.4.
67
4.4.2
return ;
. main() return: ,
return 0;.
( void) return; ( ). ,
void. return , ,
void
f(int a) {
...
return;
}
void
g(int b) {
return f(b);
}
return, .
.
, ,
.
4.4.3
4.
68
( ).
,
, .
, .. , , .
.
read :
:
#include <iostream>
#include <fstream>
double
func(double a, double b);
// declaration. The definition is elsewhere.
int
read(double & a, char const fname[]) { // definition
std::ifstream file(fname);
file >> a;
return 0; // All ok
}
void
print(char c) { // definition
std::cout << c << \n;
}
int
main() {
double x(3.2);
double y(3.4);
double z = func(x,y);
// Calls func with double, double.
int i(3);
double t = func(x,i);
// Calls func with double, int.
// int is promoted to double.
print(a); // calls a void function.
4.4.
69
double r;
read(r, "input.dat");
// calls function and ignores returned value.
}
( ).
.
.
. ..
#include <iostream>
void add3(double x) {
x+=3.0; }
int
main() {
double z(2.0);
add3(z);
//
z = ???
// z is 2.0
}
add3() ,
: x z
(2.0), 5.0 ,
. z 2.0.
, ..
x+=3.0; }
, ..
4.
70
, , , ,
. ,
(
). ,
const. ,
void
print(double const a[], std::size_t N) {
for (std::size_t i(0); i < N; ++i)
std::cout << a[i] << \n;
}
a, ,
. ,
.
const
( ).
x:
4.4.
71
,
xp, *xp (
)
4.4.4
, headers,
.h,3
#include "name.h"
name.h header,
(, path ). headers ("). , headers
(<>).
headers, compiler
. ,
3
compiler.
4.
72
,
, headers.
:
min/max /
:
min: <
max: <
utilities.h (.. double)
// utilities.h
// declarations
double
dmin(double a, double b);
double
dmax(double a, double b);
utilities.cc
// utilities.cc
#include "utilities.h"
// definitions
double
dmin(double a, double b) { return a<b ? a : b; }
double
dmax(double a, double b) { return a>b ? a : b; }
:
utilities.h , ..
#include <iostream>
#include "utilities.h"
int
main() {
double a, b;
std::cout << "Give two real numbers\n";
std::cin >> a >> b;
std::cout << "Max is " << dmax(a,b) << \n;
std::cout << "Min is " << dmin(a,b) << \n;
}
4.4.
73
compile utilities.cc
main() compiler
,
linking.
(recursive)
C++ . ,
,
.
:
( recursive) :
,
(
n! =
1 2 (n 1) n = (n 1)! n ,
1,
n>0,
n=0.
, n
( n 1).
C++
std::size_t
factorial(std::size_t n) {
std::size_t result;
if (n > 0)
result = n * factorial(n-1);
if (n == 0)
result = 1;
return result;
}
( n
).
factorial()
factorial(n)factorial(n-1) factorial(n-2) . . . (
)
0.
(?:), 3.1.2:
4.
74
std::size_t
factorial(std::size_t n) {
return (n > 0 ? n * factorial(n-1) : 1);
}
4.4.5
, ,
.
f (x )
, (x, y).
#include <iostream>
double f(double x);
int
plot(double low, double high) {
double const step = (high - low) / 100;
for (double x = low; x < high; x+=step)
std::cout << x << " " << f(x) << \n;
return 0;
}
plot()
f (x ) . f (x )
plot .
.
__
(__ , __ ,. . . );
__
(*_)(__ , __
,. . . );
*_ (*) (
) (()) ( ), 2.4. , _
4.4.
75
// declaration of f(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 ) .
// sine
// cosine
// tangent
int
plot(double low, double high, double (*f)(double x));
int
main() {
plot(1.0, 5.0, sin);
plot(1.0, 5.0, cos);
plot(1.0, 5.0, tan);
}
// plot of sine
// plot of cosine
// plot of tangent
typedef ..
, :
4.
76
4.5
// type
main()
, main():
argv[0]
argv[1]
argv[2]
argv[3]
argv[4]
argv[5]
==
==
==
==
==
==
"./a.out";
"12";
"input.dat";
"output.dat";
"4.5";
0;
1 4 . main() .
C++ header <cstdlib> :
4.6. OVERLOADING
77
// C-string to int
// C-string to long int
// C-string to double
#include <cstdlib>
#include <fstream>
int
main(int argc, char *argv[]) {
int n = std::atoi(argv[1]);
// n gets the value of the first argument
double x = std::atof(argv[4]);
// x gets the value of the fourth argument
std::ifstream filein(argv[2]);
// open input file. Name is given in argv[2].
std::ofstream fileout(argv[3]);
// open output file. Name is given in argv[3].
// ..........
}
4.6 overloading
(),
, .
. C++ (overloading)
,
, , .
. C++
double, float long double.
, compiler
( ) . , ,
. , (.. bool, char, short int
int, float double,. . . ). ,
4.
78
4.7
template
C++
templates ().
.
(swap). ,4 (int,
float,. . . ), (,
6). overloading .
:
void
swap(int & a, int & b) {
int const temp = b;
b = a;
a = temp;
}
void
swap(float & a, float & b) {
float const temp = b;
b = a;
a = temp;
}
void
swap(double & a, double & b) {
double const temp = b;
b = a;
a = temp;
}
4
std::swap() <algorithm>.
4.7. TEMPLATE
79
...
...
. C++
compiler ,
(template)
. template
:
double a = 2.0;
double b = 3.0;
swap<double>(a,b);
template
. swap(a,b).
, template
(int, char, bool,. . . ) ,
5
Standard
4.
80
enum.6
, ..,
.
( ) :
bool mult(int a, int b) {
return !(a%b);
}
, mult(a,b). , b
, template:
template<int b>
bool mult(int a) {
return !(a%b);
}
mult<b>(a).
template.
template . header
template.
4.7.1
template (.. )
,
compiler . ..
swap() XOR swap
.
swap() :
template<>
void
swap(int & x, int & y) {
x^=y;
y^=x;
x^=y;
}
, swap<int>(a,b) (, ,
swap ) ,
.
6
4.8. INLINE
81
4.8 inline
,
. C++ compiler
, ,
. . compiler
inline
. ,
:
inline int
max(int a, int b) {
return a > b ? a : b;
}
, , inline main().
inline
compiler , . , header
.
4.9
. ,
.
(0 )
, ,
.
static:
void
func(double a) {
static int howmany = 0;
// .....
++howmany;
}
howmany . func().
4.
82
: compiler static,
( 0 ).
, , , (}), .
, , ,
( ).
( ) 7 .
4.10
C++
C++ .
header <cmath>
float, double, long double. 4.1 double. ,
<cstdlib>. C
C++ .
namespace std.
. compiler
.
,
, .
, errno <cerrno>
EDOM. , errno
ERANGE:
#include
#include
#include
#include
<cerrno>
<cmath>
<limits>
<iostream>
int main() {
errno = 0; // clear error. No error code is 0.
std::sqrt(-1.0);
if (errno == EDOM)
7
std::abort().
cosh(double)
sinh(double)
tanh(double)
exp(double)
log(double)
log10(double)
modf(double d, double *p)
frexp(double d, int *p)
n/d.
n/d.
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.
<cstdlib>
.
.
.
.
(ln).
(log).
d.
x [0.5, 1) y d = x 2y .
x.
d/m.
d 2i .
int abs(int)
div_t div(int n, int d)
double
double
double
double
double
double
double
double
.
arctan(x/y).
double atan(double)
double atan2(double x, double y)
, x i .
.
.
.
.
.
pow(double x, int i)
cos(double)
sin(double)
tan(double)
acos(double)
.
.
.
.
, x a .
<cmath>
double asin(double)
double
double
double
double
double
double sqrt(double)
double pow(double x, double a)
double floor(double)
double abs(double)
double ceil(double)
4.10. C++
83
4.
84
std::cerr <<
"argument out of domain of function.\n";
std::pow(std::numeric_limits<double>::max(), 2.0);
// here errno becomes ERANGE.
if (errno == ERANGE)
std::cerr << "Math result not representable.\n";
}
, std::strerror() header <cstring>. errno
char * ,
.
4.11
4.11.1
, , , :
- .
.
( ) .
.
(
)
.
.
Bubble sort
. O (n 2 ) :
1. , . , .
4.11.
85
2. .
, , .
3.
.
,
.
, !
Insertion sort
. O (n 2 )
( ) O (n ). :
1. ,
.
2. , ,. . .
( ), .
Quicksort
, , .
O (n 2 ) ( )
() O (n log n ). , :
Quicksort
1. , ( ).
2. .
.
3. . , .
.
4. .
5. - .
4.
86
Quicksort
1. , ( ).
2. , .
3.
.
: .
.
4. ,
.
5. ,
(
).
.
6. - ( ).
Mergesort
. O (n log n ).
mergesort:
1. 0 1 , . :
2. .
3. () mergesort.
4. .
4.11.2
1.
() .
4.11.
87
() () .
;
() .
() .
() .
()
.
() [a, b] .
() P
, i ai bi .
2.
() ex
ex =
X
xn
n =0
n!
() sin x
sin x =
X
(1)k x 2k +1
k =0
(2k + 1)!
() cos x
cos x =
X
(1)k x 2k
k =0
(2k )!
.
.
3. C++
Legendre, P` (x ). P` (x ) x [1, 1], .
P0 (x ) = 1 P1 (x ) = x, `
:
`P` (x ) = (2` 1)xP`1 (x ) (` 1)P`2 (x ) .
4.
88
4. Cliff Pickover 8 :
Xn +1 = |100(ln(Xn )
(mod 1))|
X0 = 0.1.
5.
A N 9
det A =
N
X
(1)i +j aij det e
Aij ,
i =1
j, .. 1. A i j
aij , e
Aij A
i j .
6.
Cramer 10 .
7.
( )
n`m (r, , ) = Rn` (r )Y`m (, ) .
,
s
Y`m (, ) =
2` + 1 (` m )!
4
(` + m )!
Legendre, P`m (x ),
` = m
P`m (x ) = (1)m 1 3 5 (2m 1) (1 x 2 )
` = m + 1
m/2
m
P`m (x ) = x (2m + 1)Pm
(x ) ,
http://mathworld.wolfram.com/CliffRandomNumberGenerator.html
http://mathworld.wolfram.com/DeterminantExpansionbyMinors.html
10
http://mathworld.wolfram.com/CramersRule.html
9
4.11.
89
.
Legendre, P`m (x ).
, Y`m (, ).
50 100
Y`m (, ). ylm_data sin cos ,
(, ) (, , x, y, z, )
sin sin , cos , Y`m (, )Y`m
, ` = 2, m = 0 (, d-).
8. Hermite, Hn (x ), x.
:
Hn (x ) 2xHn 1 (x ) + 2(n 1)Hn 2 (x ) = 0 ,
n2,
H0 (x ) = 1, H1 (x ) = 2x.
( m V = kx 2 /2)
( )
s
n (y) =
Hn (y)ey
2n n !
/2
(4.1)
y = x
km/~.
Hermite
( ) (4.1).
n, x. m = k = ~ = 1.
harmonic.dat n = 5 60 x [6 : 6],
x ( , x
).
9. C++ ( )
f (x ) = 0 [xa , xb ] f (x ). :
() 11 . ,
.
11
http://mathworld.wolfram.com/Bisection.html
4.
90
() 12 . ,
,
f (x ).
.
() Brent 13 . ,
, , . .
10. C++ .
,
3 3 , , N N , (.. x o)
(, , N -)
, , . , .
.
. ,
, , , ,
.
x|o|x
--| |o
--o|x|
, , ( )
.
11. C++ four-in-a-row
. , M N ( 7
6 ).
.
, .
, .
12
13
http://mathworld.wolfram.com/MethodofFalsePosition.html
http://mathworld.wolfram.com/BrentsMethod.html
4.11.
91
.
. ,
( ).
, .
12. Sudoku. C++ sudoku.
9 9
, 3 3
1 9, ( ).
, .
:
()
1.
() . , 2, 3, .
. , .
()
. 1 9,
.
, . , , , ...
4.
92
5
6
3
1
9
8
4
7
7
9
6
6
8
3
1
6
3
2
2
4
1
8
9
7
5
9
13. N . N N
N
, .
.
.
.
:
N N .
board. 0
.
N ..
column. ( i
column[i]).
, (, ,
)
board. , ( 0)
( 1).
.
. 1
,
.
.
.
, ,
.
.
4.11.
93
,
, . .
,
(N N , 1 0.).
14. 5 5 .
,
( , ,
). .
. , ,
,
.
( )
. ,
( )
.
.
. .
.
15. fractal : , (x = 0, y = 0),
(x 0 , y0 )
x0
y
= ax +by+e
= cx +dy+f
a, b, c, d, e, f .
fractal (, x 0 x y0 y
(x 0 , y0 )). .
(x, y) , fractal.
:
4.
94
() "in.dat" 4 .
7 : 6
a, b, c, d, e, f p
.
P
. ,
pi ,
1.
() r [0, 1).
. , 0 r < p1
, p1 r < p1 + p2 .
() 1000
"fractal.dat".
"in.dat"
0
0.85
0.2
0.15
0
0.04
0.26
0.28
0.16
0.04 0.85 0
0.23
0.26
0.22
0.24
0
0
0
1.6
1.6
0.44
0.01
0.85
0.07
0.07
0
0.95
0.035
0.04
0
0.005
0.2
0.2
0.25
0.005 0.93
0.16
0.16
0.04
0.04
0.4
0.002
0.09
0.5
0.02
0.12
0.083
0.02
0.84
0.07
0.07
, "fractal.dat" .
16. f (x ), ,
x f (x ) (f (x ) =
0), Mller.
() x0 , x1 , x2
.
()
x2 x1
= (q + 1) (f (x2 ) f (x1 )) + A ,
= (q + 1)f (x2 ) .
x1 x0
()
x3 = x2
2C(x2 x1 )
D
4.11.
95
D
B +
B2 4AC, B B2 4AC.
()
16.
() x0 x1 , x1 x2 , x2 x3 .
16.
() .
, xn , q, A, B, C, D
.
Mller,
f (x ) = x 3 x + 1.
17. C++ .
18. C++ .
.
,
.
19.
std::swap() std::min(), std::max() STL,
5.1.3.
20. std::vector<double> (
<vector>) , ,
(<, ) (=, )
([], subscripting).
21. std::sort() STL <algorithm>.
22. dlasrt() lapack14 .
14
96
4.
Standard Library
C++ ,
, .
( 6) (templates, 4.7, 6.3),
Standard Library (STL).
STL :
containers, , .
. containers
(.. set, map) (.. vector, deque)
(.. map).
iterators, container.
iterators containers , .
container
.
,
, container
. iterators.
, STL (adapters)
(function objects), .
97
5. STANDARD LIBRARY
98
5.1
5.1.1
(Pair)
STL containers .
, header <utility> , ,
std::pair<T1,T2>. class template
T1,T2 .
first second. (..
T1 int T2 double)
:
5.1.
99
, .
, second
.
5.1.2
containers , , ,
, ,
.
(function object functor). ,
. , (())
6.
header <functional>, C++
std . templates
. 5.1
.
.
negate<T>()
plus<T>()
minus<T>()
multiplies<T>()
divides<T>()
modulus<T>()
equal_to<T>()
not_equal_to<T>()
less<T>()
greater<T>()
less_equal<T>()
greater_equal<T>()
logical_not<T>()
logical_and<T>()
logical_or<T>()
1
1 + 2
1 2
1 2
1 / 2
1 % 2
1 == 2
1 != 2
1 < 2
1 > 2
1 <= 2
1 >= 2
!1
1 && 2
1 || 2
5.1: .
(adapters), 5.2. .. plus<T>()
. , ..
5. STANDARD LIBRARY
100
bind1st(functor,value)
bind2nd(functor,value)
not1(functor)
not2(functor)
ptr_fun(function)
functor(value,parameter)
functor(parameter,value)
!functor(parameter)
!functor(parameter1, parameter2)
function functor
5.2: .
constval
std::bind1st() :
std::bind1st(plus<T>(), constval)
,
( )
(!) .
ptr_fun(),
,
, 5.3.
5.1.3
namespace std {
// minimum of a, b
template <typename T>
T const & min(T const & a, T const & b);
// maximum of a, b
template <typename T>
T const & max(T const & a, T const & b);
// b <-> a
template <typename T>
void swap(T& a, T& b);
}
min/max (<) . , ,
T
. 6
.
5.2. (CONTAINERS)
101
T (<)
min/max :
( ). min/max
:
namespace std {
// minimum of a, b based on cmp(a,b) ordering
template <typename T, typename Compare>
T const & min(T const & a, T const & b, Compare cmp);
// maximum of a, b based on cmp(a,b) ordering
template <typename T, typename Compare>
T const & max(T const & a, T const & b, Compare cmp);
}
,
std::min<>, :
template<typename T>
bool cmp(T const & a, T const & b);
, cmp
(()), 6.
5.2
5.2.1
(containers)
containers . container , .
container, ,
C ( C++), (array). C++
( malloc, calloc, realloc,
102
5. STANDARD LIBRARY
new).
, containers.
containers :
sequence containers
.
. ..
container , container . STL
sequence containers: vector,
deque list. , string
containers .
associative containers
. STL
associative containers: set, multiset, map
multimap.
associative container containers
. sequence containers .
containers class template (6.3).
container
. map multimap
. associative containers
.
(true/false)
.
std::less<T> (5.1.2)
(<). , ,
.
container
header: <vector>, <deque>, <list>,
<set> ( set multiset) <map> ( map multimap). containers, STL,
std.
containers
, . ,
5.2. (CONTAINERS)
103
,
, ,
.
container
containers . c ( ) set
v vector :
#include <set>
#include <vector>
#include <complex>
std::set<int> c;
std::vector<std::complex<double> > v;
// use c, v ........
> v
>>.
,
containers:
cntr container (vector, list, map,. . . ).
, <T>
template container ( , , .).
cntr<T> c1;
c1 cntr.
cntr<T> c2;
// fill c2 ....
cntr<T> c3(c2);
c2 cntr, (
) c3 c2,
. c2, c3 .
template.
iterator. ,
.. beg, end iterators () container
beg end,
5. STANDARD LIBRARY
104
container ( ),
[beg,end):
cntr<T1> c4;
// fill c4 ...
// set beg, end on c4
cntr<T2> c5(beg,end);
// creates c5 by copying the elements of c4
// from beg to (one before) end.
T1, T2
T1 T2.
.. T2double, T1int (
int double) T1std::complex<double>.
containers iterators . .. vector :
#include <vector>
double a[5] = {0.1, 0.2, 0.5, 0.3, 7.2};
std::vector<double> v(a, a+5);
(4.3)
n n
. , a a[0] a+5
( a[4]).
, , container.
containers
containers . 5.3. reverse iterator rbegin() reverse iterator rend()
container .
container
(.) container (
). .., vector
c,
std::vector<double> c;
, ,
:
5.2. (CONTAINERS)
105
size()
empty()
.
true/false container .
( size()==0 )
( ).
container
container .
( container ).
iterator
iterators .
.
iterator .
iterator .
reverse iterator .
reverse iterator .
max_size()
swap()
clear()
erase()
insert()
begin()
end()
rbegin()
rend()
c1 = c2;
c1
c2. c1
c2.
.
5. STANDARD LIBRARY
106
container
std::swap() <algorithm>:
std::swap(c1,c2);
, , swap()
c1.swap(c2);
- insert():
c.insert(pos, elem);
elem
( sequence containers) ( associative containers)
iterator pos. associative containers
, ,
.
iterator .
insert() .
:
erase()
:
c.erase(pos);
c.erase(beg,end);
iterator pos iterators [beg,end)
(, , c). c sequence container iterator
associative containers .
clear(). container. ( void):
c.clear();
, container .
5.2.2 Iterators
,
iterators
containers.
5.2. (CONTAINERS)
107
iterator
. iterator
,
(*) iterator
. , *it
, container, iterator it.
, iterator
(&) . STL containers.
, .. it, iterator container (.. vector)
:
std::vector<double>::iterator it;
pointers iterators
. Iterator
:
std::vector<double>::const_iterator it;
, it
const ( ) .
rbegin() rend()
container. (reverse) iterator. ( ) container containers.
iterator. ,
, iterator, .. vector, :
std::vector<double> v(10);
std::vector<double>::reverse_iterator rit = v.rbegin();
, const_reverse_iterator
iterators .
:
container, .. std::vector<double>
v, (
5.3 begin(), end()):
5. STANDARD LIBRARY
108
++crit)
std::cout << *crit << \n;
, .. 3, std::vector<int>
v
std::iterator_traits<InputIterator>::difference_type.
5.2. (CONTAINERS)
109
std::vector<T>::iterator itv;
C::iterator itl; // error
// error
C::iterator
std::vector<T>::iterator . iterators typename:
// correct
5.2.3 vector
vector . sequence container,
. vector . ,
, ,
. :
vector
container. ,
.
5. STANDARD LIBRARY
110
vector .
vector ,
, , , . , , iterators
.
vector (array),
( ) , , / . , ,
.
vector
.
std::vector header
<vector>.
vector .
.
std::vector<T> v;
vector.
std::vector<T> v(N);
v vector N T.
T(), T.2 T
, 0 (2.2).
constructor, 6.2.2.
5.2. (CONTAINERS)
111
std::vector<T> v1(v2);
v1 v2.
std::vector<T> v(beg,end);
v
iterators beg end.
vector vector size(), empty()
max_size() :
capacity()
vector ,
, .
reserve() .
vector .
vector. , ,
N T vector
,
std::vector<T> v;
v.reserve(N);
N push_back() ( ),
std::vector<T> v(N);
v[0], v[1], . . . , v[N-1].
container .
vector.
v1 = v2;
v2 v1 .
5. STANDARD LIBRARY
112
v.assign(N,elem);
v N elem , , v.
v.assign(beg, end);
v container ( ) iterators beg
end. beg
end container,
v beg
end.
v1.swap(v2);
std::swap(v1,v2);
v1, v2.
v.insert(pos, elem);
iterator pos,
elem iterator .
v.insert(pos, N, elem);
, iterator pos, N
elem, .
.
insert() iterators:
5.2. (CONTAINERS)
113
v.push_back(elem);
elem
vector. .
resize() . .
v.resize(N);
v N
.
.
,
v.resize(N,elem);
elem.
vector :
resize() .
clear().
erase(). container
, iterators
c.erase(beg,end);
sequence containers,
iterator, pos:
v.erase(pos);
iterator .
push_back() - pop_back(),
, :
v.pop_back();
, iterators
. , vector
, , iterators.
5. STANDARD LIBRARY
114
, vector :
([])
:
std::vector<double> v(3);
v[0] = 1.0;
v[1] = 3.0;
v[2] = v[1] + 5.0;
at() .
, , ,. . . vector v v.at[0], v.at[1],
v.at[2],. . . . [0:v.size()-1]
.3
.
front() back(). , ,
.
(*) iterator.
const_iterator
.
:
, vector
:
#include <iostream>
#include <vector>
#include <cstddef>
int
main() {
std::vector<double> v(10);
// v = {0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}
// assign values
for (std::size_t i = 0; i < v.size(); ++i)
v[i] = 4.0 * i*i;
3
at().
5.2. (CONTAINERS)
115
std::vector<double> v2(v);
// v2 is a copy of v
// append more values to v2
std::size_t const size = v2.size();
for (std::size_t i = size; i < 2*size; ++i)
v2.push_back(4.0*i*i);
// print v2
std::cout << "v2 is\t";
for (std::vector<double>::const_iterator it = v2.begin();
it != v2.end();
++it)
std::cout << *it << ;
std::cout << \n;
}
5.2.4 deque
deque (double-ended queue)
vector. sequence container , vector,
.
, vector
, deque
. ,
.
std::deque header
<deque>.
deque
.
, vector
. , ,
vector, . deque
. ,
5. STANDARD LIBRARY
116
, iterator , .
deque
vector.
capacity() reserve() vector.
( )
deque , iterators
.
( iterators).
capacity() reserve(),
vector deque. , push_front() ( ) pop_front() ( ),
push_back() pop_back().
:
deque . .
iterator .
#include <deque>
#include <iostream>
int
main() {
std::deque<int> d;
// d is empty
5.2. (CONTAINERS)
117
5.2.5 list
list, sequence container STL,
, vector deque. list
,
( )
, 5.1.
5.1: list.
,
vector deque, . ,
. ,
, sequence
containers ( ).
:
list ( 5.2)
.
, iterators .
6
6
?-
5.2: list.
std::list header <list>.
list
sequence containers. .
std::list<T> c;: .
std::list<T> c1(c2);: , .
118
5. STANDARD LIBRARY
5.2. (CONTAINERS)
119
list c, :
c.pop_back();: .
c.pop_front();: .
c.erase(pos);: iterator pos
iterator .
c.erase(beg,end);:
[beg,end) iterator .
c.clear();: c.
resize().
list :
front() back(). , ,
.
(*) iterator.
const_iterator
.
list, containers, size(), empty()
max_size() (5.2.1),
iterators, , capacity() reserve().
list
sequence containers:
c.remove(val);
c val.
c.remove_if(func);
5. STANDARD LIBRARY
120
c1.splice(pos, c2);
, iterator pos, c2, c2. c1, c2 list.
c1.merge(c2);
c1 c2, c2 c1
, ,
.
5.2. (CONTAINERS)
121
c1.merge(c2, op);
op().
reverse()
list .
:
#include <list>
#include <iostream>
inline bool
lessthan10(double a) {
return a < 10.0;
}
int main() {
std::list<double> c;
c.remove_if(lessthan10);
c.remove_if(std::bind2nd(std::less<double>(), 10.0));
5. STANDARD LIBRARY
122
<functional>. , , lessthan10(),
.
set T
.4 5.2.1
:
std::set<T> c;
set.
std::set<T> c1(c2);
set .
4
5.2. (CONTAINERS)
123
std::set<T> c(beg,end);
set container, , iterators
[beg,end).
, std::less<T> (<) (
). , template
, true/false,
. .. set
124
5. STANDARD LIBRARY
5.2. (CONTAINERS)
125
lower_bound(elem):
elem.
upper_bound(elem):
elem.
equal_range(elem): , , iterators elem.
:
#include <set>
#include <iostream>
#include <functional>
int
main() {
typedef std::set<int, std::greater<int> > Set;
// define empty set.
Set c;
// insert values in random order.
c.insert(5);
c.insert(12);
c.insert(3);
c.insert(6);
c.insert(7);
c.insert(1);
c.insert(9);
// print set
std::cout << "Number of elements in set: "
<< c.size() << \n;
for (Set::const_iterator it = c.begin(); it != c.end(); ++it)
std::cout << *it << " ";
std::cout << \n;
// remove elements with value 4, 6 and print information
int howmany = c.erase(4);
std::cout << "There were " << howmany
<< " elements with value 4\n";
howmany = c.erase(6);
std::cout << "There were " << howmany
<< " elements with value 6\n";
5. STANDARD LIBRARY
126
map .
, template, K,
, T,
.5
5
5.2. (CONTAINERS)
127
std::map<K,T> c;
map.
std::map<K,T> c1(c2);
map , .
std::map<K,T> c(beg,end);
map map, , iterators [beg,end).
, std::less<K>
(<) ( ). , template
, true/false,
.
set, 5.2.6.
map :
c1 = c2;: c2 c1
.
c1.swap(c2); std::swap(c1,c2);:
c1, c2.
c.insert(elem);: map multimap c elem.
elem pair , , (5.1.1). c multimap iterator
. c map ,
iterator bool
.
c.insert(pos,elem);: elem, iterator pos, iterator
.
c.insert(beg,end);: c [beg,end). .
5. STANDARD LIBRARY
128
map c :
c.erase(key);: key
.
c.erase(pos);: pos.
.
c.erase(beg,end);: iterators
[beg,end). .
c.clear();: c.
map .
. ,
.
iterator.
it iterator map (*it).first (, , it->first)
(*it).second (, , it->second) .
.
map (, multimap)
set
( []) . ,
,
. :
c map key c[key]
.
c map key
c[key] = value;
c make_pair(key,value). , ,
, ..
5.2. (CONTAINERS)
129
:
, map .
#include
#include
#include
#include
<iostream>
<string>
<map>
<utility>
int
main() {
typedef std::map<std::string, int> Map;
Map birthyear;
// Empty map.
130
5. STANDARD LIBRARY
upper_bound(key): key.
equal_range(key): , , iterators key.
5.3
(algorithms)
STL . ,
: , , , , .
containers.
iterators , ,
, containers . ,
: container , ,
. containers : , .. , random iterators
(5.2.2). containers.
.
header <algorithm>.
<numeric> . std.
iterators container .
iterator , ,
. iterator
.
container. iterator
container .
,
,
( UnaryFunctor)
( BinaryFunctor)6 .
:
accumulate, count.
5.3. (ALGORITHMS)
131
accumulate()
Type accumulate(Iterator beg, Iterator end, Type value)
Type accumulate(Iterator beg, Iterator end, Type value,
BinaryFunctor op)
[beg,end) value. {a1, a2, a3, . . . }
value + a1 + a2 + a3 + ...
.
<numeric>.
:
std::vector v
:
partial_sum()
Iterator
partial_sum(Iterator beg1, Iterator end1, Iterator beg2)
Iterator
partial_sum(Iterator beg1, Iterator end1, Iterator beg2,
BinaryFunctor op)
132
5. STANDARD LIBRARY
(
) ( ).
:
beg2 beg1
beg2+1 beg2
beg1+1
beg2+2 beg2+1
beg1+2, .
[beg1,end1).
,
op(), ,
beg2+i+1 op(*(beg2+i), *(beg1+i+1)).
beg2 container beg1,
end1.
<numeric>.
inner_product()
Type
inner_product(Iterator beg1, Iterator end1,
Iterator beg2, Type value)
Type
inner_product(Iterator beg1, Iterator end1,
Iterator beg2, Type value,
BinaryFunctor op1, BinaryFunctor op2)
value
[beg1,end1)
beg2. {a1, a2, a3, . . . } {b1, b2, b3,
. . . }
value + a1 * b1 + a2 * b2 + a3 * b3 + ...
, op1(), op2().
value op1 (a1 op2 b1) op1 (a2 op2 b2) op1 (a3 op2 b3) + ...
<numeric>.
for_each()
UnaryFunctor
for_each(Iterator beg, Iterator end, Unaryfunctor op)
5.3. (ALGORITHMS)
133
count()
Difference_type
count(Iterator beg, Iterator end, Type const & value)
Difference_type
count_if(Iterator beg, Iterator end, UnaryFunctor op)
[beg,end)
value. associative containers
.
op() true.
Difference_type 1 .
:
a, std::vector
v , :
std::size_t cnt = 0;
for (std::size_t i = 0; i < v.size(); ++i)
if (v[i] == a)
++cnt;
( )
count :
std::size_t cnt =
std::count_if(v.begin(), v.end(),
std::bind2nd(std::less<double>(), a));
, 5.2, :
std::less<double>()
a std::bind2nd().
134
5. STANDARD LIBRARY
min_element()
Iterator
min_element(Iterator beg, Iterator end)
Iterator
min_element(Iterator beg, Iterator end, BinaryFunctor op)
iterator (
) [beg,end).
(<)
op(), .
max_element()
Iterator
max_element(Iterator beg, Iterator end)
Iterator
max_element(Iterator beg, Iterator end, BinaryFunctor op)
iterator ( ) [beg,end). (<)
op(),
.
find()
Iterator
find(Iterator beg, Iterator end, Type const & value)
Iterator
find_if(Iterator beg, Iterator end, UnaryFunctor op)
iterator
[beg,end) value. associative containers
.
iterator
op() true.
end
.
[beg,end) ,
(lower_bound(), upper_bound(),
equal_range(), binary_search()).
5.3. (ALGORITHMS)
135
equal()
bool
equal(Iterator beg1, Iterator end1, Iterator beg2)
bool
equal(Iterator beg1, Iterator end1, Iterator beg2,
BinaryFunctor op)
true [beg1,end1)
beg2.
, false.
op(), .
, op() false, equal
false true.
copy()
Iterator
copy(Iterator beg1, Iterator end1, Iterator beg2)
[beg1, end1)
beg2. iterator
.
beg2 container
[beg1, end1).
copy_backward()
Iterator
copy_backward(Iterator beg1, Iterator end1, Iterator end2)
[beg1, end1) end2, . iterator
.
end2 container
[beg1, end1).
swap_ranges()
Iterator
swap_ranges(Iterator beg1, Iterator end1, Iterator beg2)
[beg1, end1)
beg2 ( [beg2, beg2+(end1-beg1))).
136
5. STANDARD LIBRARY
transform()
Iterator
transform(Iterator beg1, Iterator end1, Iterator beg2,
UnaryFunctor op)
Iterator
transform(Iterator beg1, Iterator end1, Iterator beg2,
Iterator beg3,
BinaryFunctor op)
op()
[beg1,end1)
beg2. beg1, beg2 .
beg2 (beg1,end1).
op()
[beg1,end1)
beg2
beg3. beg1, beg2, beg3 .
iterator
.
fill()
void
fill(Iterator beg, Iterator end, Type const & value)
void
fill_n(Iterator beg, Size N, Type const & value)
value [beg,end).
value N
beg.
generate()
void
generate(Iterator beg, Iterator end, Functor op)
void
generate_n(Iterator beg, Size N, Functor op)
op() ( ) [beg,end).
op() N
beg.
5.3. (ALGORITHMS)
137
replace()
void
replace(Iterator beg, Iterator end,
Type const & oldvalue, Type const & newvalue)
void
replace_if(Iterator beg, Iterator end,
UnaryFunctor op, Type const & newvalue)
newvalue [beg,end)
oldvalue. op
true.
replace_copy()
void
replace_copy(Iterator beg1, Iterator end1, Iterator beg2,
Type const & oldvalue, Type const & newvalue)
void
replace_copy_if(Iterator beg1, Iterator end1, Iterator beg2,
UnaryFunctor op, Type const & newvalue)
[beg1,end1)
beg2 newvalue oldvalue.
op true.
remove()
Iterator
remove(Iterator beg, Iterator end, Type const & value)
Iterator
remove_if(Iterator beg, Iterator end, UnaryFunctor op)
[beg,end)
value.
op true.
.
iterator . , beg
iterator .
,
associative containers.
(erase()).
138
5. STANDARD LIBRARY
list (remove())
.
reverse()
void
reverse(Iterator beg, Iterator end)
[beg,end).
list .
reverse_copy()
Iterator
reverse(Iterator beg1, Iterator end1, Iterator beg2)
[beg1,end1) beg2.
container.
merge()
Iterator
merge(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3)
Iterator
merge(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3,
BinaryFunctor op)
[beg1,end1)
[beg2,end2) beg3, . op()
true false
.
container.
list .
set_union()
Iterator
set_union(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2, Iterator beg3)
Iterator
5.3. (ALGORITHMS)
139
set_intersection()
Iterator
set_intersection(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator
set_intersection(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3, BinaryFunctor op)
merge()
.
set_difference()
Iterator
set_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator
set_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3, BinaryFunctor op)
merge()
.
set_symmetric_difference()
Iterator
set_symmetric_difference(Iterator beg1, Iterator end1,
Iterator beg2, Iterator end2,
Iterator beg3)
Iterator
140
5. STANDARD LIBRARY
binary_search()
bool
binary_search(Iterator beg, Iterator end, Type const & value)
bool
binary_search(Iterator beg, Iterator end, Type const & value,
BinaryFunctor op)
true false
[beg,end) value.
, op(),
,
.
sort()
void
sort(RandomIterator beg, RandomIterator end)
void
sort(RandomIterator beg, RandomIterator end,
BinaryFunctor op)
[beg,end). ,
(<)
op(),
.
.
random iterators list. list
list.
stable_sort()
void
stable_sort(RandomIterator beg, RandomIterator end)
void
5.4.
141
partial_sort()
void
partial_sort(RandomIterator beg, RandomIterator sortEnd,
RandomIterator end)
void
partial_sort(RandomIterator beg, RandomIterator sortEnd,
RandomIterator end, BinaryFunctor op)
sort()
[beg,sortEnd)
.
random_shuffle()
void
random_shuffle(RandomIterator beg, RandomIterator end)
[beg,end).
random iterators list associative containers.
5.4
1. 1000000
[1000000, 1000000].
2. , container .
() .
() 1234. ;
.
() .
() 0.
() .
() 0.
142
5. STANDARD LIBRARY
() 10000
10000.
() 100 .
template
container;
containers vector, deque, list, set; containers ( clock()7
<ctime>). ;
3.
list: unique(), splice(), merge(), reverse().
4. STL.
, interface, iterators.
. ;
5. quicksort, 4.11.1, container iterators. , ,
template<typename Iterator>
void
quicksort(Iterator beg, Iterator end) {
...
}
6.
5.4.
143
. a
odd.dat b
even.dat.
7.
() std::equal()
equal. , ,
template<typename Iterator>
bool
equal(Iterator beg1, Iterator end1, Iterator beg2) {
.....
}
() std::list,
1, 3, 5, 88, 92, 4, 91
1, 3, 5, 88, 92, 4, 2, 91 .
equal() ( false).
8. .
( )
( , ,
).
9. :
, , ( ), , , .
,
.
144
5. STANDARD LIBRARY
6.1
C++
(object based) (object
oriented programming). , ,
, .
6.1.1
, ,
, , ( ), . ,
(, , .). , , (
, ,
, , .),
( , ,
, , .), . (
)
. .. C++
146
6.
// number of books
( ) , ,
.
,
.
( , , . , , , , ,
.) , , , , . ,
, , .
,
.
,
.
: ,
!
C++
struct, 2.6.2,
struct Student {
std::string name;
int AM;
int Year;
// ......
};
struct Book {
std::string title;
std::string author;
int year;
// ......
};
6.1.
147
, , , .
() :
6.1.2
(encapsulation)
students, books ,
students books. ,
148
6.
. Student Book.
( )
( encapsulation). .
C++ struct
C
, .
, class struct
, (
) , :
,
, .1
class Student {
std::string name;
int AM;
int Year;
// ......
public:
int print() {....}
// the old printStudent
std::string getName() {....}
int getAM() {....}
int getYear() {....}
// ......
};
class Book {
public:
int print() {....} // the old printBook
std::string getTitle() {....}
std::string getAuthor() {....}
int getYear() {....}
// ......
private:
std::string title;
std::string author;
int year;
// ......
1
struct
.
6.1.
149
};
. (
, ) printStudent()
printBook() (
) (
).
struct (.).
. , print()
s Student :
Student s;
// .... give values to s
s.print();
s
print() .
,
public: (
) ( )
. ,
{
private:
.
, ,
.
, ..
class Student {
std::string name;
int AM;
// ......
public:
std::string getName() {return name;}
void setAM(int i) { AM = i;}
// ......
};
6.1.3
, -
150
6.
, , , . . , ,
, ,
. ..,
(, , .) ,
() .
.
. , ,
, , , ( , inheritance) . , ,
. , , ( ), ,
( ),
.
( ) ,
, , ,
. ( polymorphism).
,
.
, ,
. ,
(
)
.
C++ .
6.2.
6.2
151
,
( ), :
.
, . ,
( ).
, 2.5.4, : ()
().
. , ( )
. , ,
.
,
, ,
. .
.
-
- .
.
.
, ,
.
, , Student
.
6.
152
class Student {
public:
Student(char const * onoma, int am, int y)
: name(onoma), AM(am), Year(y) {}
Student() {}
Student(Student const & other);
Student & operator=(Student const & other);
int print() const {
std::cout << name << << AM << << Year << \n;
return 0;
}
std::string const & getName() const {return name;}
int getAM() const {return AM;}
int getYear() const {return Year;}
void setName(char const * s) {name = s;}
void setAM(int am) {AM = am;}
void setYear(int y) {Year = y;}
private:
std::string name;
int AM;
int Year;
};
6.2.1
( , )
class struct,
, {}, (
). (;)
.
, name, AM, Year,
. private:
. , , print(), getName(), getAM(), getYear(), setName(), setAM(), setYear()
, public:.
,
.2 , ,
.
2
protected:, .
6.2.
153
private:
class public: struct.
,
class.
setName(), setAM(), setYear(), .
. ,
.
. , , const
. ,
getName(), getAM(), getYear(),
, const
( ). ( const)
. , s Student,
Student & s1 = s;
Student const & s2 = s;
s1.setYear(2000);
s2.setYear(2000);
// correct
// error
int y = s1.getYear();
int z = s2.getYear();
// correct
// correct
setYear() s1 s2
. getYear()
.
,
const ,
const.
,
, private ,
, public
.
, , , (, ,
public) . ,
154
6.
. ,
Student print() setYear()
:
class Student {
public:
// ............
int print() const;
void setYear(int y);
// ............
private:
std::string name;
int AM;
int Year;
};
int
Student::print() const {
std::cout << name << << AM << << Year << \n;
return 0;
}
inline
void
Student::setYear(int y) {
Year = y;
}
, .
( Student::).
inline, 4.8 ,
inline .
header
(.. Student.h) ( inline
template, 4.8 4.7) (.. Student.cc)
. ,
( #include "Student.h")
header .
6.2.
6.2.2
155
(ConstructorsCopy constructor)
, , ,
:
Student(char const * onoma, int am, int y),
Student()
Student(Student const & other).
Student ( ), ( )
Student ( ).
, .
( ) constructors () copy constructor
( ) .
(constructor)
:
std::string name(onoma);
int AM(am);
int Year(y);
6.
156
,
constructor.
std::string name;
name = onoma;
int AM;
AM = am;
int Year;
Year = y;
: name, AM, Year, name ""
. , . ,
. , const
, .
,
constructor (:)
.
, constructors, ( ), 4.6.
Student(){}.
constructor . , Student,
name "" . Student
:
Student s;
6.2.
157
Student t(s);
t .
, 4.2,
, ,
.
copy constructor
,
copy constructor.
copy constructor
. ,
return3 .
X copy constructor, ,
3
return.
6.
158
6.2.3
(Destructor)
Student(){} destructor ()
Student. static
(4.9),
4 .
destructor .
destructor, X
, X(){}.
, destructor destructors (
) , .
destructor
,
.
6.2.4
(assignment operator)
,
,
(=,+,<, .). =
.
, , . ..
return exception.
6.2.
159
Student &
operator=(Student const & other){
if (this != &other) {
name = other.name;
AM = other.AM;
Year = other.Year;
}
return *this;
}
this
operator=. if
other . , . ,
,
a=b=c=d, .
, : , , .
.
6.2.5
(=) , . , ,
. ,
.
6.
160
operator. 2.4 (
)
(.)
(sizeof).
6.3
template
. ,
X T
template<typename T>:
template<typename T>
class X {
T a;
...
...
};
( , )
T .
, a T. X T :
X<double> x1;
X<int>
x2;
, x1.a x2.a .
template .
.., , Y
,
template<int n>
class Y {
double v[n];
};
Y template:
Y<10> c;
c.v, , 10 .
X
,
template<typename T>
<T>:
6.4.
161
template<typename T>
class X {
T a;
...
void f(T v);
};
template<typename T>
void
X<T>::f(T v) {
...
}
6.4
1. Book .
2.
. date interface
date.h.
:
#include <iostream>
#include "date.h"
int
main() {
date
date
date
date
date
date
date
date
date
date
a;
b(1996);
c(5,2003);
d(14,5,2005);
e(d);
const f(d+3);
g(d+30);
h(d-30);
i(32,5,2000);
j(12,13,2000);
//
//
//
//
//
//
//
//
//
//
a
b
c
d
e
f
g
h
i
j
=
=
=
=
=
=
=
=
=
=
January 1, 2000
January 1, 1996
May 1, 2003
May 14, 2005
d (May 14, 2005)
May 17, 2005
Jun 13, 2005
April 14, 2005
June 1, 2000
January 12, 2001
<< h.day()
std::cout << "h day is "
<< "h month is " << h.month()
<< "h year is " << h.year();
h.add_year(2);
h.add_month(2);
h.add_day(2);
6.
162
<< f.year();
// a = January 2, 2000
// c = April 30, 2003
if (c > a)
std::cout << c.to_string() << "is after "
<< a.to_string() << \n;
if (c == a)
std::cout << c.to_string() << "coincides with "
<< a.to_string()<<\n;
if (c < a)
std::cout << c.to_string() << "is before "
<< a.to_string() << \n;
d += 4;
g -= 3;
i = g;
}
3.
3 . , ,
, , ,
.
4. (,
template<typename T> complex<T> std::complex STL.
. . . !
, , C
. C++
.
1 .
Raymond Cheong 2001, .1.
( ).
Michael Savastio 1995, .2.
429539.
Ken Huffman 1996, .3.
Braille .
#include <stdio.h>
int l;int main(int o,char **O,
int I){char c,*D=O[1];if(o>0){
for(l=0;D[l
];D[l
++]-=10){D
[l++]-=120;D[l]-=
110;while
(!main(0,O,l))D[l]
+=
20;
putchar((D[l]+1032)
/20
)
;}putchar(10);}else{
c=o+
(D[I]+82)%10-(I>l/2)*
(D[I-l+I]+72)/10-9;D[I]+=I<0?0
:!(o=main(c/10,O,I-1))*((c+999
)%10-(D[I]+92)%10);}return o;}
A.1: cheong.c
http://www.ioccc.org
163
. . . . !
164
#include <stdio.h>
lll1l,*ll1l1
;l1l1
llll];};main
(){l111 llll1
l1, *ll1l, *
malloc ( ) ; l1l1
ll11l l11,ll ,l;l1l1 lll11 *lll1,*
=1-1 ;l< 14; ll1ll("\t\"8)>l\"9!.)>vl"
);scanf("%d",&l);l1l1l(l1l) l1l1l(ll11
lll[l1l->lll[1-1]
=1]=l11l;ll1(l11
++l11){l1=ll11;
lll1 = (ll1l=(
lll; lllll =(
l1l=l1)->lll;
);ll1(;ll1l->
lll1l||l11l!=
+=l11**lll1++
;l1ll1 ll111
l1lll lll1=(
ll1l =ll1l->
}}ll1(;l1ll;
){l1ll1 ll111
{ l1lll} } *
lllll=l11l;}
ll1(l=(ll=11);(l<llll)&&
(l1->lll[ l]
!=l11l);++l);
l1->ll1l1,l=
llll){ll1(--l
++ll)printf(
(ll)?((ll%19)
19,"\n%04d")
):"%4d",l1->
A.2: savastio.c
l111 llll1 {
l111 llll1 *
lll11 lll [
*ll11,*l1l,*
ll11l l1ll ;
lllll; ll1(l
[l]^L),++l
) (l1=l1l)->
=1+1;l11<=l;
ll11=l1l))->
ll=(l1ll=1-1
*lll1;){l1ll
(++ll>llll){
lll1l)->lll;
(++ll>=llll)
ll1 (;l1;l1=
;l>=1-1;--l,
?"%04d":(ll=
lll[l] ) ; }
ll1ll(10); }
165
#define x char
#define z else
#define w gets
#define r if
#define u int
#define s main
#define v putchar
#define y while
#define t " A?B?K?L?CIF?MSP?E?H?O?R?DJG?NTQ?????U?V?????X???????Z????W??Y??"
s (
) {
x* c , b[ 5 * 72
]; u a, e , d
[ 9
y (w ( b) ){
r ( 0
[ b] -7 *
*9 *9 ] ;
5
)
{ c =
b
;
y ( (*
c - 6
r ((
-0 ) [ c ] && w ( b
+
* 7 )* * c )c = c+ 1 ;
8 * 5*
3
) && w
(b
+8
*5 * 6) )
{ a
= 0; y
(
a
[
b ]
) {
a [ d ] = ! !
( a[ b]
4 *8 )
; a =
a +
1; }
y (a
< 8 * 5
) d
[
(
a ++ )
* 3
] =
0
; a
=
0;
y(
b [
a + 8 *3
d [ a ]
= a [
d] + ! !( b[
* 5 ] ) {
a+ 40 * 3
] -4 * 8) * 2
;
++ a
;
}
a =
0
;
y (
a
[ b +
6
* 40 ]
) {a [d ] += !
! ( b[ a
+
5 * 6 *
8 ] - 4
*
8
) * 4;
a =
a + 1
;} a=
0;
y (a
<3 *8
) {
r
(
a
[
d
] )
{ e
*5
= 1 ; y
(
e[ a + d] ){
e )
= a[ d
* ( d+ a+
+e - 1] +(
d
[
a +
e ] << (
3* e) )
;e
=
e
+ 1 ;} a
=
a
+
e - 1
; v( !! ( * ( d+
a) %
( 64 ) - 12 * 5
)
+ ( e
> 4
) ?t [
e
>2 ? 2 :a
[ d
] ]
:6 * 8 +( t [ d[
a
]/ 8
/8
] -4 )
%( 10 ) )
; r( ! (2 [a
+ d] + 3 [d +
a ] )
)
v
( 4 *
8
)
; }
a =
a + 1 ; } v
(5 * 2
) ; }
z {c =b ;
e
= 0
;
y (*
c ) {
c +=
- (* c
>
8 *
12
*
)
;
a
= 8
; r (* c
* 32
* 8
>= 48 &&* c<8 *8
-6) {*c =(
* c + 1
)
%( 5
;y( --a >0
&&*
* 2 ) + 65
c- a[ t]
);
d[
(e
++
)]
=4
;(
++) ))= 07
;}z y(a -- >1
* ( d + (e
&&* ct[a ]); d[
( e = e +
1) 1]
=a
%8
;y
(a
/=
8)
d[
(e ++
) ] =
a% 8
; ++ c
; * (
e ++
+d ) =0
;} -- e
;r
(
e >0 ) {a =
1
;
y
( a<
8
) {
c =
b ;y
( c <e +b )
{ v ( *
( c b + d )&
a? 6 *7
:8
) ;
c ++
;} a= a
+
a ;
v ( 2*
* 4
5) ; } v
( 5*
2
)
;
}} }}
}
A.3: huffman.c
166
. . . . !
Fortran C
C++
. compilers ,
.
Fortran 77 C
C.
compilers Fortran 90/95
. Fortran 77 compiler
1 .
,
( main()) compiler C++, , ,
main() ( C)
PROGRAM ( Fortran).
.1
C , , compiler C++. C
C++. ,
4.
compiler C
object file library ( )
1
, Fortran compiler NAG
CHARACTER .
167
168
. FORTRAN C
:
header
. compiler C++
C
extern "C".
:
f,g
int f(double a) {
.....
}
void g(int a) {
.....
}
compiler C. C++
extern "C"
int f(double a);
extern "C"
void g(int a);
, ,
extern "C" {
int f(double a);
void g(int a);
}
C++.
linking object library
. .. UNIX
compilers GNU Project,
prog.cc fg.c,
gcc -c fg.c
g++ prog.cc fg.o
object, .o,
C++ .
compilers .
.2. FORTRAN
.2
169
Fortran
Fortran 77
C.
.
:
Fortran, , blas
lapack. , ( ,
, .).
, . .
dlasrt() .
lapack2
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):
2
170
. FORTRAN C
Fortran
INTEGER
REAL
DOUBLE PRECISION
LOGICAL
CHARACTER
COMPLEX
C++
int
float
double
bool
char
std::complex<float>
dlasrt SUBROUTINE
C++ void.
void dlasrt(char const & id, int const & n, double d[],
int & info);
compiler Fortran C
extern "C". compiler
.
GNU compilers
: _, ,
. compilers
extern "C"
void dlasrt_(char const & id, int const & n, double d[],
int & info);
.2. FORTRAN
171
,
. ( lapack
blas library) ( UNIX)
172
. FORTRAN C
3
3.1. (n!) .
#include <iostream>
// factorial
int
main()
{
int n;
std::cout << "Give non negative integer number ";
std::cin >> n;
double fac = 1.0;
for (int i=1; i<=n; ++i)
fac *= i;
std::cout << "The factorial of " << n
<< " is " << fac << \n;
}
3.2. N Fibonacci.
#include <iostream>
// Fibonacci
int
main()
{
int n;
std::cout << "How many Fibonacci numbers? ";
std::cin >> n;
int f0 = 0;
int f1 = 1;
if (n > 0)
173
174
3.3. .
#include <iostream>
// greatest common divisor, Euclids algorithm: gcd(N,M) = gcd(M, N mod M)
int
main()
{
std::cout << "Give two positive integers: ";
int m,n;
std::cin >> m >> n;
while (n != 0) {
const int temp = m;
m = n;
n = temp % n;
}
std::cout << "The greatest common divisor is " << m << \n;
}
3.4. Lagrange.
#include <iostream>
int
main()
{
std::cout << "Give a positive integer number: ";
int N;
std::cin >> N;
for (int a = 0; a*a <= N; ++a) {
for (int b = a; a*a + b*b <= N; ++b) {
for (int c = b; a*a + b*b + c*c <= N; ++c) {
for (int d = c; a*a + b*b + c*c + d*d <= N; ++d)
if (a*a + b*b + c*c + d*d == N)
std::cout << N << " is "
<< a <<* << a << " + "
<< b <<* << b << " + "
<< c <<* << c << " + "
<< d <<* << d << \n;
}
}
}
}
175
5. 8 .
#include <iostream>
#include <cstdlib>
int
main() {
std::cout <<"RAND_MAX is " << RAND_MAX << \n;
std::srand(12345U);
for (int i = 0; i < 8; ++i)
std::cout << std::rand() << \n;
}
6.1. 1000
[20 : 20].
#include <fstream>
#include <cstdlib>
int
main()
{
std::ofstream random("rndnumbers");
for (int i = 0; i < 1000; ++i)
random << static_cast<int>(-20.0
+ 41.0 * std::rand() / (RAND_MAX+1.0))
<< \n;
}
6.2. C++
, 0
.
#include <fstream>
#include <cstdlib>
#include <iostream>
int
main()
{
std::ifstream random("rndnumbers");
int
int
int
int
r;
neg = 0;
zer = 0;
pos = 0;
176
10. ax 2 + bx + c.
#include
#include
#include
#include
<iostream>
<complex>
<cmath>
<iomanip>
13. .
#include <fstream>
int
main() {
int const M = 10, N = 20, P = 30;
double A[M][N], B[M][P], C[M][P];
std::ifstream matA("matA.dat");
//read A
for (int i=0; i < M; ++i) {
for (int j=0; j < N; ++j) {
matA >> A[i][j];
}
}
177
std::ifstream matB("matB.dat");
//read B
for (int i=0; i < N; ++i) {
for (int j=0; j < P; ++j) {
matB >> B[i][j];
}
}
// compute C
for (int i=0; i < M; ++i) {
for (int j=0; j < P; ++j) {
C[i][j] = 0.0;
for (int k = 0; k < N; ++k) {
C[i][j] += A[i][k] * B[k][j];
}
}
}
std::ofstream matC("matC.dat");
// print C
for (int i=0; i < M; ++i) {
for (int j=0; j < P; ++j) {
matC << C[i][j] << ;
}
}
}
int
main() {
int const M = 512;
int const N = 512;
int const maxgen = 1000; // how many generations
int const digits = 3; // 1+ log10(maxgen-1);
int gen[M][N];
// initial generation; two pairs of diagonal lines
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
if ( (i==j+1) || (i==j-1) || (i==N-1-j-1) || (i==N-1-j+1) ) {
gen[i][j] = 1;
} else {
gen[i][j] = 0;
}
}
}
for (int generation = 0; generation < maxgen; ++generation) {
// save generation
std::ostringstream filename;
filename << "life_"
<< std::setw(digits) << std::setfill(0)
<< generation
<< ".ppbm";
178
std::ofstream out(filename.str().c_str());
out << "P1\n" << N << << M << \n; // P1, width, height
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
out << gen[i][j] << \n;
}
}
// In the last generation dont calculate the new one.
if (generation == maxgen-1) {
break;
}
// new generation
int newgen[M][N];
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
// find number of neighbours
int neigh = 0;
for (int i1 = i-1; i1 <= i+1; ++i1) {
for (int j1 = j-1; j1 <= j+1; ++j1) {
if ( (i1 == i) && (j1 == j) ) {
continue;
}
if ((0 <= i1) && (i1 < M) && (0 <= j1) && (j1 < N)) {
neigh += gen[i1][j1];
}
}
}
// calculate new
if ((neigh == 3)
newgen[i][j]
} else {
newgen[i][j]
}
generation
|| ((gen[i][j] == 1) && (neigh == 2))) {
= 1;
= 0;
}
}
// copy new generation to old
for (int i = 0; i < M; ++i) {
for (int j = 0; j < N; ++j) {
gen[i][j] = newgen[i][j];
}
}
}
}
4
5. A.
#include <vector>
179
void
copy(std::vector<double> const & A, int N, std::vector<double> & Aij,
int row, int col);
double
determinant(std::vector<double> const & A, int N) {
if (N==1) {
return A[0];
}
std::vector<double> Aij((N-1)*(N-1));
int const col = 0;
int sign = 1;
// (-1)^(0+col)
double sum = 0.0;
for (int i = 0; i < N; ++i) {
copy(A, N, Aij, i, col);
sum += sign * A[i+col*N] * determinant(Aij, N-1);
sign = -sign;
}
return sum;
}
void
copy(std::vector<double> const & A, int N, std::vector<double> & Aij,
int row, int col) {
int in = 0;
for (int i = 0; i < N; ++i) {
if (i == row) {
continue;
}
int jn = 0;
for (int j = 0; j < N; ++j) {
if (j == col) {
continue;
}
Aij[in+jn*(N-1)] = A[i+j*N];
++jn;
}
++in;
}
}
. .
// recursive binary search; a[] sorted from low values to high values.
template<typename T>
bool
bsearch(T const a[], int beg, int end, T v) {
if (end-beg == 1) {
return a[beg] == v;
}
int const m = beg + (end-beg)/2;
180
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,
181
there is nothing to do. */
// make b large enough for (n-1) elements above or below the initial.
std::vector<T> b((n-1) + 1 + (n-1));
int const middle = n-1;
int const k = 0; // choose any index in [0, n).
// copy chosen element to middle position of b.
b[middle] = a[k];
// separate low elements of a to upper half of b
// and high elements of a to lower half of b.
int jlow = middle;
int jhig = middle;
for (int i = 0; i < n; ++i) {
if (i == k) // skip i if on the chosen element. It has been copied.
continue;
if (a[i] <= a[k]) {
--jlow;
b[jlow] = a[i];
} else {
++jhig;
b[jhig] = a[i];
}
}
// b[jlow] .. b[jhig] is the new matrix. Copy it to a:
for (int i = 0; i < n; ++i)
a[i] = b[jlow+i];
// sort "low" matrix
// between b[jlow] and b[middle-1] there are (middle-1) - jlow + 1 elements
// The "low" matrix starts at a[0]
quickSort(a, middle - jlow);
// sort "high" matrix
// between b[middle+1] and b[jhig] there are jhig - (middle+1) + 1 elements
// The "high" matrix starts at a[middle-jlow+1]
quickSort(a+middle-jlow+1, jhig-middle);
}
template<typename T>
void
mergesort(T a[], int beg, int end) {
// if there is only one element (or less), the array is already sorted.
if (end-beg <= 1) {
return;
}
//get middle point
int const m = beg + (end-beg)/2;
// sort the two halves
mergesort(a, beg, m);
mergesort(a, m, end);
182
std::vector<T> c(end-beg);
int i1 = beg;
int i2 = m;
for (int i = 0; i < end-beg; ++i) {
bool const cond1 = i1 == m;
bool const cond2 = i2 == end;
int j;
if (cond1) {
j = i2++;
}
if (cond2) {
j = i1++;
}
if (!cond1 && !cond2) {
j = (a[i1] < a[i2] ? i1++ : i2++);
}
c[i] = a[j];
}
for (int i = 0; i < end-beg; ++i) {
a[i+beg] = c[i];
}
}
5
3. STL.
template<typename iterator, typename T>
T
accumulate(iterator beg, iterator end, T value) {
T s = value;
for (iterator it = beg; it != end; ++it) {
s += *it;
}
return s;
}
template<typename iterator, typename T>
T
inner_product(iterator beg1, iterator end1,
iterator beg2, T value) {
T s = value;
iterator it1 = beg1;
iterator it2 = beg2;
while (it1 != end1) {
s += (*it1) * (*it2);
183
++it1;
++it2;
}
return s;
}
184
}
[1] Nicolai M. Josuttis. The C++ Standard Library: A Tutorial and Reference. Addison Wesley, Reading, MA, USA, first edition, September
1999.
[2] Herb Sutter. More Exceptional C++: 40 More Engineering Puzzles, Programming Problems, and Solutions. C++ in Depth Series. Addison Wesley, Reading, MA, USA, January 2002.
[3] Scott Meyers. Effective STL: 50 Specific Ways to Improve the Use of the
Standard Template Library. Professional Computing Series. Addison
Wesley, Reading, MA, USA, July 2001.
[4] Andrei Alexandrescu. Modern C++ Design: Applied Generic and Design
Patterns. C++ In-Depth Series. Addison Wesley, Reading, MA, USA,
January 2001.
[5] Matthew H. Austern. Generic Programming and the STL: Using and
Extending the C++ Standard Template Library. Professional Computing
Series. Addison Wesley, Reading, MA, USA, January 1999.
[6] John J. Barton and Lee R. Nackman. Engineering and Scientific C++:
An Introduction with Advanced Techniques and Examples. Addison Wesley, Reading, MA, USA, 1994.
[7] Dov Bulka and David Mayhew. Efficient C++ Performance Programming
Techniques. Addison Wesley, Reading, MA, USA, November 1999.
[8] Bruce Eckel. Thinking in C++. Introduction to Standard C++, volume 1.
Prentice Hall, second edition, 2000. Also available as electronic book.
[9] Bruce Eckel and Chuck Allison. Thinking in C++. Practical Programming, volume 2. Prentice Hall, second edition, 2003. Also available as
electronic book.
[10] Francis Glassborow. You Can Program in C++: A Programmers Introduction. John Wiley & Sons, 2006.
185
186
187
[26] Herb Sutter. Exceptional C++ Style: 40 New Engineering Puzzles, Programming Problems and Solutions. C++ In-Depth Series. Addison Wesley, Reading, MA, USA, August 2004.
[27] Herb Sutter and Andrei Alexandrescu. C++ Coding Standards: Rules,
Guidelines, and Best Practices. C++ In-Depth Series. Addison Wesley,
Reading, MA, USA, November 2004.
[28] Herb Sutter. Exceptional C++. C++ In-Depth Series. Addison Wesley,
Reading, MA, USA, October 1999.
[29] David Vandevoorde and Nicolai M. Josuttis. C++ Templates: The Complete Guide. Addison Wesley, Reading, MA, USA, December 2002.
[30] David Vandevoorde. C++ Solutions: Companion to the C++ Programming
Language. Addison Wesley, Reading, MA, USA, August 1998.
[31] D. Yang. C++ and Object-Oriented Numeric Computing for Scientists and
Engineers. Springer-Verlag, New York, January 2001.
188
2.1
2.2
2.3
2.4
2.5
C++. .
. . . . . . . .
C++. . . .
.
bit C++. . . . . . . .
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
6
9
14
26
29
. . . . . . . . . . . .
83
5.1 . . . . . . . . . . . .
5.2 . . . . . . . . . . .
5.3 containers STL. . . . . . . .
189
99
100
105
sort(),
!, 15
, 40
int, 10
long int, 10
short int, 10
Fibonacci, 51
, 130
accumulate(), 131
binary_search(), 140
copy(), 135
copy_backward(), 135
count(), 133
equal(), 135
fill(), 136
find(), 134
for_each(), 132
generate(), 136
inner_product(), 132
max_element(), 134
merge(), 138
min_element(), 134
partial_sort(), 141
partial_sum(), 131
random_shuffle(), 141
remove(), 137
replace(), 137
replace_copy(), 137
reverse(), 138
reverse_copy(), 138
set_difference(), 139
set_intersection(), 139
set_symmetric_difference(),
set_union(),
138
140
140
swap_ranges(), 135
transform(), 136
bubble sort, 84
insertion sort, 85
mergesort, 86
quicksort, 85
, reference
, function
object
, 23
, 7
, struct
, 147, 148
, 150
, 52
, 54
Boole, 54
Durand, 54
Simpson, 54
, 150
, 105
, 89
, 90
Brent, 90
, cast
, 150
double, 11
float, 11
stable_sort(),
139
190
191
long double, 11
, 66
, 67
, 67
, 73
, 65
bit
, 29
&, 29
<<, 29
>>, 29
^, 29
|, 29
&&, 15
<<, 33
,, 28
<cerrno>, 82
<limits>, 11
<sstream>, 32
?:, 44
EDOM, 82
ERANGE, 82
NDEBUG, 47
RAND_MAX, 51
*/, 5
/*, 5
//, 5
adapter, 99
bind1st(functor,value),
bind2nd(functor,value),
100
100
ptr_fun(function), 100
assert, 47
bitset, 29
boolalpha, 34
bool, 7, 25, 34
, 15
, 34
vector<bool>, 29
break, 50
case, 45
cast
not1(functor),
not2(functor),
100
100
static_cast, 25
char, 7, 25
class, 148
complex, 12
constructor, 155
continue, 49
copy constructor, 155
deque, 115
destructor, 158
do while, 48, 49, 50
else, 43
encapsulation, 147, 148
enumeration, 12
errno, 82
false, 7, 34
for, 48, 49, 50
function object, 99
divides<T>(), 99
equal_to<T>(), 99
greater<T>(), 99
greater_equal<T>(), 99
less<T>(), 99
less_equal<T>(), 99
logical_and<T>(), 99
logical_not<T>(), 99
logical_or<T>(), 99
minus<T>(), 99
modulus<T>(), 99
multiplies<T>(), 99
negate<T>(), 99
not_equal_to<T>(), 99
plus<T>(), 99
game of life, 55
global, 7, 18
goto, 47
if, 43
istringstream, 32
iterators, 106
bidirectional, 108
random, 108
list, 117
long int, 10
main(), 76
192
map, 126
max(), 100
min(), 100
multimap, 126
multiset, 122
namespace, 29
ostringstream, 32
overloading, 77
plain pbm, 53
plain ppm, 56
rand(), 51
reference, 60
seekg(), 35
seekp(), 35
set, 122
short-circuit evaluation, 15
sizeof, 28
spline fit, 55
srand(), 51
strerror(), 84
struct, 22
swap(), 100
switch, 45, 50
true, 7, 34
typedef, 16
unsigned int, 11
unsigned long int, 11
vector<bool>, 29, 115
vector, 109
void, 11
while, 48, 49, 50
||, 15
bool
, 7
double,
float,
functor, function object
long double,