Sei sulla pagina 1di 51

How to Program in C++

You may copy this file for noncommercial use. The latest version is located at cs.fit.edu/~mmahoney/cse2050/how2cpp.html updated Apr. 14 2010. !lease report errors to "att "ahoney at mmahoney#cs.fit.edu. $eldom%used features have &een deli&erately omitted.

Language Summary
Basic Concepts Statements if, for, while, return, break... Expressions arithmetic, comparison, assignment...

The most important types are int, char, bool, double and the containers string, vector, and map. $ummary of common types'
Built-in int x; char x; double x; bool x; Modifiers const / x; /2 3x; / f!...' 5...6 /8 p; / a:0;; static / x; register / x; volatile / x; Description Fastest integer t pe !"#$%& bits', also short, long, unsigned ($bit character, )*+) to )*xFF) or $"&( to "&, #- bit real . or $ ".(e%+(, "- significant digits, also float true or false Description 0on$modifiable ob1ect 4eference, is an alias for x, which both have t pe / 7efines f as a function returning / 9ointer to / !8p is a / ob1ect' <rra of 0 elements of /, a:+; to a:0$"; 9lace x in data segment !rare' =int to optimi>e for speed !rare' x ma be modified externall

The followin( standard li&rary types and functions re)uire at the &e(innin( of the pro(ram'
?include @headerA using namespace std; Library Type Description istream Standard input !cin' ostream Butput !cout, cerr, clog' ifstream Cnput file ofstream Butput file string SeDuence of char vector@/A Expandable arra Estack of / deDue@/A <rra Edouble ended Dueue list@/A FistEstackEDueue of / map@/",/&A <ssociative mapping of /" to /& set@/"A < map with ke s onl pair@/",/&A /wo ob1ects of t pe /" and /& priorit GDueue@/A Sorted Dueue stack@/A Stack bitset@0A <rra of 0 bool with logical operations valarra @/A <rra with arithmetic operations complex@/A Complex number iterator 9ointer into a container Header iostream iostream fstream fstream string vector deDue list map set map or utilit Dueue stack bitset valarra complex !Cncluded with container'

constGiterator exception

9ointer not allowing element assignment !Cncluded with container' =ierarch of exception t pes stdexcept, exception Header algorithm numeric iterator functional new Header cstdlib cct pe cmath ctime cstring cstdio cassert

C++ Standard Library Functions min!', max!', swap!', sort!', cop !', eDual!' accumulate!', innerGproduct!' backGinserter!' eDualGto!', less!', bind&nd!' setGnewGhandler!' C Library Functions atoi!', atof!', abs!', rand!', s stem!', exit!' isalpha!', isdigit!', tolower!', toupper!' sDrt!', log!', exp!', pow!', sin!', cos!', atan!' clock!', time!' strlen!', memset!', memmove!', memcmp!' printf!', fopen!', getc!', perror!' assert!'

*++ allows you to create your own types and li&raries. The most important type is a class allowin( o&,ect oriented pro(rammin(. A class is an a&stract data type with a hidden representation and a set of pu&lic mem&er functions and types. *lasses can &e or(ani-ed into a hierarchy .inheritance/ and you can write code that accepts any type in this hierarchy .polymorphism/. 0unctions and classes can &e parameteri-ed &y type .templated/.
class / 5...6; 7efines / as a collection of t pes, ob1ects, and member functions template @class /A ... 7efines a set of functions or classes over all / t pedef / H; 7efines t pe H is a s non m for / enum / 5...6; 7efines / as an int, and set of int constants struct / 5...6; Fike a class, except default scope of members is public union / 5...6; < struct with ob1ect members overlapping in memor namespace 0 5...6; 7efines a scope for a collection of t pes, ob1ects, and functions 9rogram Brgani>ation !compiling, linking, make' =istor of C.. Further 4eading

Basics
*++ is a compiled lan(ua(e an upward compati&le superset of * and an .incompati&le/ predecessor to 1ava. *++ compiles * pro(rams &ut adds o&,ect oriented .22/ features .classes inheritance polymorphism/ templates .(eneric functions and classes/ function and operator overloadin( namespaces .pac3a(es/ e4ception handlin( a li&rary of standard data structures .strin( vector map etc./ and formatted te4t 5/2 .istream ostream/. 6nli3e 1ava *++ lac3s a standard (raphical user interface .765/ networ3 interface (ar&a(e collection and threads and allows non%22 pro(rammin( and unchec3ed low%level machine operations with pointers. 8owever *++ e4ecutes faster than 1ava and re)uires no run%time support. A *++ pro(ram is a collection of function o&,ect and type declarations. 9very pro(ram must have a function int main!' 5 ... 6 where the curly &races enclose a &loc3 a se)uence of declarations and statements endin( in semicolons which are e4ecuted in order. A statement is an e4pression &loc3 or control statement that alters the order of e4ecution such as if, while, for, break, return. $ome types .stdIIstring/ o&,ects .stdIIcout/ and functions are defined in header files re)uirin( the line ?include @headerA &efore use. 5tems defined in the standard headers are in the namespace std. The stdII prefi4 may &e dropped after the statement using namespace std;. 0or instance
EE CommentI prints J=ello worldKJ and an BS$independent newline ?include @stringA EE 7efines t pe stdIIstring ?include @iostreamA EE 7efines global ob1ect stdIIcout using namespace std; EE <llow stdII to be dropped int main!' 5 EE Execution starts here string s3J=ello worldK*nJ; EE 7eclares ob1ect s of t pe string cout @@ s; EE <n expression as a statement, @@ is the output operator return +; EE Execution ends here 6

The sym&ol EE denotes a comment to the end of the line. You may also use E8 ... 8E for multiline comments. $pacin( and indentation is used for reada&ility. *++ is mostly free%form e4cept that the end of line is si(nificant after ? and EE. *++ is case sensitive. *++ source code files should &e created with a te4t editor and have the e4tension .cpp. 5f the a&ove is called hello.cpp it may &e compiled and run as follows in a 6:5; shell window'
g.. hello.cpp $o hello $Lall $B .Ehello

The $o option renames the e4ecuta&le file &y default a.out. $Lall turns on all warnin(s .recommended/. $B optimi-es .compiles slower &ut runs faster/. 5n <indows the 7:6 *++ compiler is called =17!!. To compile and run from an "$%=2$ &o4'
gxx hello.cpp $o hello.exe hello

The output file must have a .9;9 e4tension .default is A.9;9/. There is also a .2>1 file which you can delete. To use the networ3 or 765 interface in 6:5; you must use the ; and soc3et li&raries which don?t wor3 in <indows. 5n <indows you must use the <indows A!5 and a compiler that supports them such as from "icrosoft >orland or $ymantec. 765/networ3 pro(rammin( is nonporta&le and outside

the scope of this document. @in3s to free and commercial *++ compilers can &e found at cplusplus.com.

Statements
A pro(ram consists of a collection of functions .one of which must &e int main!' 5...6/ and type and o&,ect declarations. A function may contain declarations and statements. $tatements have the followin( forms where s is a statement and t is a true/false e4pression.
s; ; 5s; s;6 if !t' s; if !t' s; else s; while !t' s; for !s"; t; s&' s; break; return x; tr 5throw x;6 t pe catch !/ ' 5s;6 catch !...' 5s;6 do s; while !t'; continue; switch !i' 5 case CI s; break; defaultI s; 6 labelI goto label; EE EE EE EE EE EE EE EE EE EE Expression or declaration Empt statement < block of + or more statements is a statement Cf t is true then s else is optional Foop + or more times s"; while !t' 5s; s&;6 Mump from while, for, do, switch 4eturn x to calling function /hrow exception, abort if not caught, x has an

EE if x has t pe / then 3x, 1ump to s EE else 1ump here !optional' EE !uncommon' s; while !t' s; EE !uncommon' Start next loop of while, for, do EE !uncommon' /est int expression i to const C EE if !i33C' go here EE optional, else go here EE !rare' Mump to label within a function

A statement may &e a declaration or an e4pression. 2&,ects and types declared in a &loc3 are local to that &loc3. .0unctions cannot &e defined locally/. 5t is normal .&ut not re)uired/ to show statements on separate lines and to indent statements enclosed in a &loc3. 5f &races are optional we indent anyway. 0or instance
5 6 int a:"+;, i3+, 1; a:i.&;3%; EE EE EE EE start of block declaration expression end of block, a, i, and 1 are destro ed

declares the array of int a with elements a:+; throu(h a:N; .whose values are initially undefined/ i with initial value 0 and 1 with an undefined initial value. These names can only &e used in scope which is from the declaration to the closin( &race. The for loop is normally used for iteration. 0or instance the followin( &oth e4it the loop with i set to the inde4 of the first element of a such that a:i; is 0 or to 10 if not found.
for !i3+; i@"+; i3i."' 5 if !a:i;33+' 5 break; 6 6 i3+; while !i@"+' 5 if !a:i;33+' break; i3i."; 6

The &races in the for loop are optional &ecause they each enclose a sin(le statement. 5n the while loop the outer &races are re)uired &ecause they enclose 2 statements. All statements are optional' for !;;' loops forever. The first statement in a for loop may declare a varia&le local to the loop.
for !int i3+; i@"+; i3i."'

5t is only possi&le to break from the innermost loop of a nested loop. continue in a for loop s3ips the rest of the &loc3 &ut e4ecutes the iteration .s2/ and test &efore startin( the ne4t loop. return x; causes the current function to return to the caller evaluatin( to 4. 5t is re)uired e4cept in functions returnin( void in which case return; returns without a value. The value returned &y main!' has no effect on pro(ram &ehavior and is normally discarded. 8owever it is availa&le as the Astatus in a 6:5; csh script or 9BB2B@9C9@ in a <indows .>AT file.
int sum!int x, int return x. ; 6 int main!' 5 int a3sum!",&'; return +; 6 ' 5 EE Function definition

EE a3%; EE B convention, non>ero indicates an error

A test of several alternatives usually has the form if !t' s; else if !t' s; else if !t' s; ... else s;. A switch statement is an optimi-ation for the special case where an int e4pression is tested a(ainst a small ran(e of constant values. The followin( are e)uivalent'
switch !i' 5 case "I 13"; break; case &I EE fall thru case %I 13&%; break; defaultI 13+; 6 if !i33"' 13"; else if !i33& OO i33%' EE OO means Jor elseJ 13&%; else 13+;

throw x ,umps to the first catch statement of the most recently e4ecuted tr &loc3 where the parameter declaration matches the type of 4 or a type that 4 can &e converted to or is .... At most one catch &loc3 is e4ecuted. 5f no matchin( catch &loc3 is found the pro(ram a&orts .6ne4pected e4ception/. throw; with no e4pression in a catch &loc3 throws the e4ception ,ust cau(ht. 94ceptions are (enerally used when it is inconvenient to detect and handle an error in the same place.
void f!' 5 throw %; 6 int main!' 5 tr 5 f!'; 6 catch!int i' 5 throw; 6 catch!...' 5 6 6

EE Execute this block with i 3 % EE throw % !not caught, so program aborts' EE Catch an other t pe

Expressions
There are 1D levels of operator precedence listed hi(hest to lowest. 2perators at the same level are evaluated left to ri(ht unless indicted Thus aE&+c means aE.&+c/ &ecause + is hi(her than E and a%&%c means .a%&/%c. 2rder of evaluation is undefined e.(. for sin!x'.cos!x' we cannot say whether sin./ or cos./ is called first. The meanin( of an e4pression depends on the types of the operands. !x, ' denotes a comma separated list of 0 or more o&,ects e.(. !' !x' or !",&,%,-'.
1 PIIm IIm Qember m of namespace or class P Rlobal name m when otherwise hidden b a local declaration

2 p:i; i)th element of container p !arra , vector, string' x.m Qember m of ob1ect x p$Am Qember m of ob1ect pointed to b p f!x, ' Call function f with + or more arguments i.. <dd " to i, result is original value of i i$$ Subtract " from i, result is original value of i staticGcast@/A!x' Convert x to t pe / using defined conversions constGcast@/A!x' !rare' Convert x to eDuivalent but non$const / reinterpretGcast@/A!x' !rare, dangerous' 9retend x has t pe / d namicGcast@/A!x' !rare' Convert base pointer or reference to derived if possible t peid!x' !rare' Cf x is t pe /, then t peid!x'33t peid!/' !in @t peinfoA' 3 ri!"t to left# 8p Contents of pointer p, or p:+;. Cf p is t pe /8, 8p is / 2x <ddress of !pointer to' x. Cf x is t pe /, 2x is /8 $a 0egative of numeric a Ki 0ot i, true if i is false or + Si Bitwise compliment of i, $" $ i !/'x Convert !cast' ob1ect x to t pe / !b static, const, or reinterpret' /!x, ' Convert, initiali>ing with + or more arguments new / Create a / ob1ect on heap, return its address as /8 new /!x, ' Create, initiali>ing with + or more arguments new!p' / !rare' Cnitiali>e / at address p without allocating from heap new!p' /!x, ' !rare' Cnitiali>e / with + or more arguments at p new /:i; Create arra of i ob1ects of t pe /, return /8 pointing to first element delete p 7estro ob1ect pointed to b p obtained with new / or new /!' delete:; p 7estro arra obtained with new /:; ..i <dd " to i, result is the new i $$i Subtract " from i, result is the new i si>eof x Si>e of ob1ect x in b tes si>eof!/' Si>e of ob1ects of t pe / in b tes $ x.8p D$A8p T a8b aEb !rare' Bb1ect in x pointed to b pointer to member p !rare' Bb1ect in 8D pointed to b pointer to member p Qultipl numeric a and b 7ivide numeric a and b, round toward + if both are integer

iU1 % a.b a$b & x@@ xAA ' x@ xA x@3 xA3 ( x33 xK3 1) i21 11 iV1 12 iO1 13 i221 1$ iOO1

Cnteger remainder i$!iE1'81 <ddition, string concatenation Subtraction Cnteger x shifted Cnteger x shifted bits to left, or output bits to right, or input to ostream x from istream x

Fess than Rreater than Fess than or eDual to Rreater than or eDual to EDuals 0ot eDuals Bitwise <07 of integers i and 1 Bitwise PB4 of integers i and 1 Bitwise B4 of integers i and 1 i and then 1 !evaluate 1 onl i or else 1 !evaluate 1 onl if i is trueEnon>ero' if i is falseE>ero'

1* ri!"t to left# x3 <ssign to x, result is new value of x x.3 x3x. , also $3 83 E3 U3 23 O3 V3 @@3 AA3 1% iWxI 1& throw x 1' x, Cf i is trueEnon>ero then x else /hrow exception x !an Evaluate x and !an t pe' t pes', result is

94pressions that don?t re)uire creatin( a new o&,ect such as a3b, ..a, p:i;, p$Am, x.m, aWbIc, a,b etc. are lvalues meanin( they may appear on the left side of an assi(nment. 2ther e4pressions and conversions create temporary o&,ects to hold the result which are const .constant/. An e4pression used as a statement discards the final result.
int a, b, c; a.b; EE Fegal, add a and b, discard the sum a3b3c; EE Fegal, assign c to b, then assign the new b to a !a.3b'.3c; EE Fegal, add b to a, then add c to a

a.b3c; EE Error, a.b is const double!a'3b; EE Error, double!a' is const

static+cast,T- .# converts 4 to type T if a conversion is defined. 6sually the value of 4 is preserved if possi&le. *onversions are defined &etween all numeric types .includin( char and &ool/ from 0 to pointer pointer to &ool or voidF istream to &ool ostream to &ool charF to strin( from a derived class to &ase class .includin( pointers or references/ and from type T to type 6 if class 6 has a constructor ta3in( T or class T has a mem&er operator H!'. A conversion will &e implicit .automatically applied/ whenever an otherwise invalid e4pression assi(nment or function ar(ument can &e made le(al &y applyin( one e4cept for T to 6 where 6?s constructor ta3in( T is declared explicit for e4ample the constructor for vector ta3in( int.
double d; d3staticGcast@doubleA!%'; d3%; d3sDrt!%'; vector@intA v!T'; v3T; v3staticGcast@vector@intA A!T'; EE EE EE EE EE EE Explicit % to %.+ Cmplicit conversion Cmplicit %.+, sDrt!' expects double /his constructor is explicit Error, no implicit conversion BX

const+cast,T- .# allows an o&,ect to &e modified throu(h a const pointer or reference. 5t must always &e e4plicit.
int x3%; const int2 r3x; r3-; constGcast@int2A!r'3-; const int8 p32x; 8p3T; 8constGcast@int8A!p'3T; EE EE EE EE Error, r is const BX, x3Error, 8p is const BX, x3T

5f 4 were const then this code would still &e allowed &ut it is undefined whether 4 actually chan(es. reinterpret+cast,T- .# turns off normal type chec3in( &etween int and different pointer types which are normally incompati&le. The only safe conversion is to convert a pointer &ac3 to its ori(inal type. *onversion is always e4plicit.
int x3%, 8p32x; 8p3T; 8reinterpretGcast@double8A!p'3T; EE BX, x3T EE Crash, writing ( b tes into -

The e4pression !/'x applies whatever com&ination of static const and reinterpret casts are needed to convert 4 to type T. /!x' is a staticGcast.
const char8 s3JhelloJ; int!8s'; !char8's; !const int8's; !int8's; EE EE EE EE staticGcast constGcast reinterpretGcast reinterpretGcast and constGcast

Declarations
A declaration creates a type o&,ect or function and (ives it a name. The synta4 is a type name followed &y a list of o&,ects with possi&le modifiers and initiali-ers applyin( to each o&,ect. A name consists of upper or lowercase letters di(its and underscores .G/ with a leadin( letter. .@eadin( underscores are allowed &ut may &e reserved/. An initiali-er appends the form 3x where 4 is an e4pression or .4 y/ for a list of one or more e4pressions. 0or instance

string s", s&3JxxxJ, s%!JxxxJ', s-!%,)x)', 8p, a:T;, nextGLord!';

declares s1 to &e a strin( with initial value HH s2 sI and s4 to &e strin(s with initial value H444H p to &e a pointer to strin( a to &e an array of 5 strin(s .aJ0K to aJ4K with initial values HH/ and nextGLord to &e a function that ta3es no parameters and returns a strin(.

Built-in Types
All &uilt%in types are numeric. They are not automatically initiali-ed to 0 unless (lo&al or static.
int a, b3+; static double x; EE a)s value is undefined EE +.+

Types and their usual ran(es are listed &elow. Actual ran(es could &e different. The most important types are int &ool char and dou&le.
/nte!er types bool signed char unsigned char char short unsigned short int unsigned int long unsigned long Floatin! point types float double long double Bits " ( ( ( "# "# %& %& %&$#%&$#Bits %& ##-$(+ 0an!e false !+' or true !"' )*x(+) to )*x,f) !$"&( to "&,' )*x++) to )*PFF) !+ to &TT' Hsuall signed $%&,#( to %&,#, +u to #TT%TH Hsuall $&"-,-(%#-( to &"-,-(%#-, Hsuall + to -&N-N#,&NTH <t least $&"-,-(%#-(l to &"-,-(%#-,F +ul to at least -&N-N#,&NTFH 0an!e $".,e%(f to ".,E%(F, # significant digits $".(e%+( to ".(E%+(, "- significant digits <t least double

There are implicit conversions &etween all types. <hen types are mi4ed in an e4pression &oth operands are converted to the type that has the hi(her upper &ound &ut at least to int. This conversion only loses representation when mi4in( si(ned and unsi(ned types.
,E,.+E)*x+T).true %H A $" EE EE EE EE ", int division rounds toward + ".,T, implicit double!-' 3 -.+ #, implicit int!)*x+T)' 3 T, int!true' 3 " false, implicit !unsigned int'!$"' 3 &%&$"

*onversion from a floatin( point type to an inte(er type drops the decimal part and rounds toward 0. 5f the value is outside the ran(e of the tar(et then the result is undefined.
int!$%.(' EE $%

*onversion of one inte(er type to another is performed modulo the ran(e of the tar(et. 0or a >%&it num&er .e4cept &ool/ we add or su&tract 2> to &rin( the value within ran(e. .5n terms of a 2?s complement num&er we drop the most si(nificant &its and reinterpret the si(n &it without chan(in( any &its/. 0or &ool any non-ero value is true.
!unsigned char'!$"' bool!%' short a3x"&%-T#,(; EE )*xff) !&TT' EE true EE xT#,( hex

Integer Types
int is the most common inte(er type normally the underlyin( word si-e of the computer or I2 &its representin( num&ers from %2I1 to 2I1%1 .%214L4DIM4D to 214L4DIM4L/. 2n some older systems such as real mode =2$ it may &e 1M &its .%I2LMD to I2LML/. You should use int unless you need the ran(e of some other type. An int value may &e written in decimal .e.(. 255/ he4adecimal with a leadin( ; .e.(. 4ff or ;00/ or octal .&ase D/ with a leadin( 0 .e.(. 0ILL/. A trailin( @ denotes lon( .e.(. 255@ or 255l/ and 6 denotes unsi(ned. These may &e com&ined .e.(. 255lu or 2556@ is unsi(ned lon(/. "ost inte(er operations translate to a sin(le machine instruction and are very fast.
. $ 8 E U $i 3 33 K3 @ @3 A A3 ..i i.. $$i i$$ 2 O V Si @@ AA .3 $3 83 E3 U3 23 22 OO Ki <dd, subtract, multipl , divide, mod, unar negation <ssignment Comparison, returns true or false 9reEpost increment and decrement Bitwise and, or, xor, not, left shift, right shift O3 V3 @@3 AA3 Bperate and assign, e.g. x.3 means x3x. Fogical and then, or else, not

=ivision rounds toward 0 e.(. L/4 is 1 %L/4 is %1. 4Ny is the remainder with the si(n of 4 e.(. %LN4 is %I. =ivision or mod &y 0 is a run time error and should &e avoided. 2perations that yield results outside the ran(e of an int are converted modulo 2I2 or more (enerally 2> for a > &it num&er. 0or instance M55I5FM55IL is %1 not 2I2%1. Assi(nment returns the value assi(ned e.(. 4EyE0 assi(ns 0 to y and the new y to 4. The result is an lvalue e.(. .4Ey/E0 is also le(al .&ut useless/. 5t assi(ns y to 4 then 0 to 4. ++i and i++ &oth add 1 to i. 8owever ++i returns the new value and i++ returns the old value. @i3ewise for decrement %%i and i%% which su&tracts 1. The pre forms ++i %%i are lvalues. >itwise operators treat an int as a 2?s compliment >%&it &inary num&er .>EI2/ with wei(hts %2>%1 2>%2 2>%I ... D 4 2 1. The leftmost &it is ne(ative and serves as the si(n &it. Thus 0 is all -ero &its and %1 is all 1 &its. >itwise operators 4Oy 4Py 4Qy and ~4 perform > simultaneous lo(ical operations on the &its of 4 and y. 0or instance if y is a power of 2 then 4O.y%1/ has the effect 4Ny &ut is usually faster and the result is always positive in the ran(e 0 to y%1. 4RRy returns 4 shifted left &y y places shiftin( in -eros. The result is 4F2y. 4SSy returns 4 shifted ri(ht &y y places shiftin( in copies of the si(n &it .or -eros if unsi(ned/. The result is 4/2y &ut roundin( ne(ative instead of toward 0. 0or instance %100SSI is %1I. y must &e in the ran(e 0 to >%1 .0 to I1/. $hiftin( is usually faster than F and /. Any &inary arithmetic or &itwise operator may &e com&ined with assi(nment. The result is an lvalue. e.(. !x.3&'83%; has the effect 4E4+2T 4E4FIT @o(ical operators treat 0 as false and any other value as true. They return true .1/ or false .0/ as do comparisons. The OO and PP operators do not evaluate the ri(ht operand if the result is 3nown from the left operand.
if !iA3+ 22 i@n 22 a:i;33x' if !x3%' true EE 7o bounds check on i before indexing arra a EE Fegal but probabl wrong, assign % to x and test

c"ar
A char is a one &yte value. 6nli3e other numeric types it prints as a character althou(h it can &e used in arithmetic e4pressions. *haracter constants are enclosed in sin(le )uotes as )a). A &ac3slash has special meanin(. ?Un? is a newline ?UU? is a sin(le &ac3slash ?U?? is a sin(le )uote ?UH? is a dou&le )uote. A &ac3slash may &e followed &y I octal di(its .?UILL?/ or an ; and 2 he4 di(its .?U400?/ .&ut not decimal/. "ost computers use A$*55 conversion as follows'
($"%I %&$-,I -($#%I #-$NTI N#$"&#I *b*t*n*v*f*r !bell, tab, newline, K*J?YU2*)!'8.,$.E +"&%-T#,(NI;@3A*W Z<BC7EFR=CMXFQ0B9[4S/H\LP]^:**;VG _abcdefghi1klmnopDrstuvwx >5O6S vertical tab, formfeed, return' !%&3space, *) and *J are one char' !*W is one char' !** is one char'

Floating Point Types


A num&er with a decimal point is dou&le .e.(. I.L/ unless a trailin( 0 is appended .e.(. I.Lf or I.L0/ in which case it is float. =ou&le is preferred. A dou&le may &e written in the form 4ey meanin( 4F10y e.(. I.L9%2 .0.0IL/ or 1e4 .10000.0/. A dou&le is usually represented as a M4 &it num&er with a si(n &it an 11 &it e4ponent and 52 &it mantissa. Therefore it can only represent num&ers of the form "F29 e4actly where %252 R " R 252 and 2%10 R 9 R 210. This is a&out + or % 1.LVLeI0D with a&out 15 decimal di(its of precision. Therefore num&ers li3e 1e14 and 0.5 have e4act representations &ut 1e20 and 0.1 do not.
+." 8 "+ 33 " EE false, the differ b about "+$"T

There are no &itwise or lo(ical operators N ++ or %%


. $ 8 E $x 3 .3 $3 83 E3 33 K3 @ @3 A A3 <dd, subtract, multipl , divide, unar negation !no U' <ssignment, ma be combined with operators Comparison, however onl @ and A are meaningful

2perations may produce values outside the ran(e of a dou&le resultin( in infinity %infinity or :a: .not a num&er/. These values cannot &e written in *++. Additional mathematical functions .s)rt./ lo(./ pow./ etc./ can &e found in RcmathS.

o!i"iers
5n a declaration modifiers &efore the type name apply to all o&,ects in the list. 2therwise they apply to sin(le o&,ects.
int8 p, D; const int a3+, b3+; EE p is a pointer, D is an int EE a and b are both const

const
const o&,ects cannot &e modified once created. They must &e initiali-ed in the declaration. >y convention const o&,ects are 6!!9B*A$9 when used (lo&ally or as parameters.
const double 9C3%."-"TN&#T%TN; EE <ssignment to 9C not allowed

#e"erences
A reference creates an alias for an o&,ect that already e4ists. 5t must &e initiali-ed. A reference to a const o&,ect must also &e const.
int i3%; int2 r3i; EE r is an alias for i r3-; EE i3-; double2 pi39C; EE Error, would allow 9C to be modified const double2 pi39C; EE BX

Functions
A function has a list of parameter declarations a return type and a &loc3 of statements. 94ecution must end with a return statement returnin( an e4pression that can &e converted to the return type unless void in which case there is an implied return; at the end. Ar(uments passed to a function must match the parameters or allow implicit conversion .such as int to dou&le/. 0unctions must &e defined &efore use or have a matchin( declaration that replaces the &loc3 with a semicolon and may optionally omit parameter names. 0unctions are always (lo&al .not defined in other functions/.
void f!double x, double'; EE 7eclaration double g!' 5 EE 7efinition return %; EE Cmplied conversion to double !%.+' 6 int main!' 5 EE Execution starts with function main f!g!', T'; EE Calls g, then f with implicit T.+ return +; EE 4eturn H0CP Ystatus or Lindows E44B4FE\EF 6 void f!double x, double ' 5 EE 7efinition must match declaration cout @@ x. ; return; EE Bptional 6

*ommand line ar(uments may &e passed to main!int argc, char88 argv' where argv is an array of argc elements of type charF .?U0? terminated array of char/ one element for each word .separated &y white spaces/. 5n 6:5; the command line is e4panded &efore &ein( passed .F &ecomes a

directory listin( etc/. The followin( pro(ram prints the command line.
EE echo.cpp ?include @iostreamA using namespace std; int main!int argc, char88 argv' 5 for !int i3+; i@argc; ..i' cout @@ argv:i; @@ endl; return +; 6 !++ ec"o1cpp 12a1out "ello 3orld .Ea.out hello world

0unction parameters have local scope. They are initiali-ed &y copyin( the ar(ument which may &e an e4pression. Beference parameters are not copiedT they &ecome references to the ar(uments passed which must &e o&,ects that the function may modify. 5f the reference is const then the ar(ument may &e an e4pression. *onst reference is the most common for passin( lar(e o&,ects &ecause it avoids the run time overhead of copyin(.
void assignGif!bool cond, string2 to, const string2 from' 5 EE value reference const reference if !cond' to3from; 6 int main!' 5 string s; assignGif!true, s, JaJ'; EE BX, s3JaJ assignGif!false, JbJ, s'; EE ErrorI to refers to a const

0unctions returnin( a reference must return an o&,ect which can &e assi(ned to and that o&,ect must e4ist after returnin( .(lo&al or static &ut not local/. The function may &e called on the left side of an assi(nment. 0unctions returnin( &y value ma3e a temporary copy which is const.
int a3"; int f!' 5return a;6 int2 g!' 5return a;6 int2 h!' 5return a.";6 int2 i!' 5int b; return b;6 int2 1!' 5static int b; return b;6 int main!' 5 f!'3&; EE Error, assignment to g!'3f!'; EE BX, a3"; return +; 6 EE EE EE EE EE EE Rlobal BX, returns cop of a BX, g!' is alias for a Error, reference to const Error, b destro ed after return BX, static has global lifespan

const

0unctions with the same name may &e overloaded &y matchin( the ar(uments to the parameters.
int abs!int'; double abs!double'; int main!' 5 abs!%'; EE int abs!%.+'; EE double abs!J%J'; EE Error, no match

abs!)a)'; return +;

EE Error, ambiguous, could convert char to int or double

"ost operators ; can &e overloaded &y definin( a function named operator P!' ta3in( the operands as ar(uments. At least one ar(ument has to &e a class type.
string operator $ !const string2 s, int i'; string operator $ !const string2 s'; EE 7efines s$i EE 7efines $s

2perators . II WI and si>eof cannot &e overloaded. 2perators 3 :; $A cannot &e overloaded e4cept as class mem&ers. !ostfi4 .. $$ are overloaded as &inary operators with a second dummy int parameter to distin(uish from the prefi4 form.
string2 operator..!const string2 s'; EE defines ..s string operator..!const string2 s, int'; EE defines s..

0unctions may have default ar(uments &y initiali-in( the parameters. =efaults should &e specified only once. =efaulted parameters must appear after all non%default parameters.
void f!int i, int 13+, int k3+'; void g!int i3+, int 1'; int main!' 5 f!", &'; EE f!", &, +'; f!"'; EE f!", +, +'; f!'; EE Error return +; 6 void f!int i, int 1, int k' 56 EE BX EE Error

EE 7efaults not specified again

A template overloads a function for all types. The declaration template @class /, class HA &efore a function definition allows T and 6 to &e used in the code as types. The compiler will fi(ure out appropriate su&stitutions from the ar(uments. A non%templated overloaded function ta3es precedence over a template.
template @class /A void swap!/2 a, /2 b' 5 / tmp3a; a3b; b3tmp; 6 void swap!string2 a, string2 b'; EE Bverrides the case /3string int main!' 5 int i3", 13&; string a, b; swap!i, 1'; EE BX, / is int swap!a, b'; EE BX, calls non$templated swap swap!i, a'; EE Error, cannot resolve / swap!cout, cerr'; EE Error, ostream does not allow 3

inline is a hint to the compiler to optimi-e for speed &y e4pandin( the code where it is called savin( a call and return instruction. 6nli3e a macro semantics are preserved. 2nly short functions should &e inlined.
inline int min"!int a, int b' 5return a@bWaIb;6 ?define min&!a,b' !!a'@!b'W!a'I!b''

int main!' 5 min"!f!', +'; min&!f!', +';

EE calls f!' once EE calls f!' twice, expands to !!f!''@!+'W!f!''I!+''

Pointers
A pointer stores the address of another o&,ect and unli3e a reference may &e moved to point elsewhere. The e4pression 2x means Haddress of 4H and has type Hpointer to 4H. 5f x has type / then 2x has type /8. 5f p has type /8 then 8p is the o&,ect to which it points which has type /. The F and O operators are inverses e.(. 82x 33 x. Two pointers are e)ual if they point to the same o&,ect. All pointer types are distinct and can only &e assi(ned pointers of the same type or 0 .:6@@/. There are no run time chec3s a(ainst readin( or writin( the contents of a pointer to invalid memory. This usually causes a se(mentation fault or (eneral protection fault.
int i3%, 8p32i; 8p3T; p3new int!#'; p3new char!)a)'; p3#; p3+; p3i$T; 8p3,; int 8D; 8D; memor EE EE EE EE EE EE EE EE EE p points to i, 8p 33 % i3T BX, p points to an int with value # Error, even though char converts to int Error, no conversion from int to pointer BX Error, compiler can)t know this is + Segmentation faultI writing to address + Segmentation faultI D is not initiali>ed, reading random

A pointer to a const o&,ect of type T must also &e const of type const /8 meanin( that the pointer may &e assi(ned to &ut its contents may not.
const double 9C3%."-"TN&#T%T(N(; double8 p329C; EE Error, would allow 8p3- to change 9C const double8 p329C; EE BX, can)t assign to 8p !but ma assign to p' double8 const p329C; EE Error, ma assign to 8p !but not to p' const double8 const p329C; EE BX, both 8p and p are const

A function name used without parenthesis is a pointer to a function. 0unction pointers can &e assi(ned values and called.
int f!double'; int g!double'; int 8h!double'; int !8p'!double'; int int main!' 5 p3f; p!%.+'; p3g; p!%.+'; p3h; EE functions f and g take double and return int EE function h takes double and returns pointer to int EE p is a pointer to a function that takes double and returns EE calls f!%.+' EE calls g!%.+' EE Error, t pe mismatch

94plicit pointer conversions are allowed &ut usually unsafe.


int i, 8p32i; i3int!%.+'; EE BX, rounds %.+ 8!double8'p 3 %.+; EE Crash, writes be ond end of i

8!double8'29C 3 -; EE Bverwrites a const

These may also &e written .with the same results/'


i3staticGcast@intA!%.+'; 8reinterpretGcast@double8Ap 3 %.+; 8constGcast@double8A29C 3 -; EE <ppl standard conversions EE 9retend p has t pe double8 EE Same t pe except for const

$rrays
The si-e of an array must &e specified &y a constant and may &e left &lan3 if the array is initiali-ed from a list. Array &ounds start at 0. There are no run time chec3s on array &ounds. "ulti%dimensional arrays use a separate &rac3et for each dimension. An array name used without &rac3ets is a pointer to the first element.
int a:;35+,",&,%,-6; EE <rra with elements a:+; to a:-; int b:T;35#,,6; EE Cmplied 35#,,,+,+,+6; int c:T;; EE 0ot initiali>ed, c:+; to c:-; could have an int d:&;:%;355",&,%6,5-,T,#66; EE Cnitiali>ed &$7 arra int i3d:";:&;; EE # d:$";:,;3+; EE 0ot checked, program ma crash values

The &are name of an array is a const pointer to the first element. 5f p is a pointer to an array element then p+i points i elements ahead to pJiK. >y definition pJiK is F.p+i/.
int a:T;; int8 p3a.&; p:";; p$a; pAa; p$" 33 a." 8a; a3p; EE EE EE EE EE EE EE EE a:+; through a:-; 8p is a:&; a:%; & true because p$a A + true, both are 2a:"; a:+; or p:$&; Error, a is const !but not 8a'

A literal strin( enclosed in dou&le )uotes is an unnamed static array of const char with an implied ?U0? as the last element. 5t may &e used either to initiali-e an array of char or in an e4pression as a pointer to the first char. $pecial chars in literals may &e escaped with a &ac3slash as &efore. @iteral strin(s are concatenated without a + operator .convenient to span lines/.
char s:;3JabcJ; const char8 p3JaJ Jb*nJ; arra Jab*n*+J const char8 answers:&;35JnoJ,J esJ6; cout @@ answers:";; cout @@ answers:";:+;; JabcJ:"; EE char s:-;35)a),)b),)c),)*+)6; EE 9oints to the )a) in the - element EE EE EE EE <rra of pointers to char prints es !t pe const char8' prints !t pe const char' )b)

Arrays do not support copyin( assi(nment or comparison.


int a:T;, b:T;3a; b3a; b33a; JabcJ33JabcJ EE EE EE EE ErrorI ErrorI false, false, can)t initiali>e b this wa can)t assign arra s comparing pointers, not contents comparing pointers to & different locations

The si-e of an array created with new:; may &e an e4pression. The elements cannot &e initiali-ed with a list. There is no run time chec3 a(ainst accessin( deleted elements.
int n, 8p; cin AA n; p3new int:n;; delete:; p; p:+; 3 "; EE Elements p:+; to p:n$"; with values initiall undefined EE Hse delete with new or new!', delete:; with new:; EE Qa crash

static
:ormally o&,ects are placed on the stac3. "emory is allocated &y (rowin( the stac3 at the topT thus o&,ects are destroyed in the reverse order in which they are created. An o&,ect?s life span is the same as its scope. 5f an o&,ect comes into scope more than once then it is reinitiali-ed each time and destroyed when leavin( its scope.
.$$$$$$$$$$. O O O =eap O <llocated with new until deleted or program exits. O O .VVVVVVVVVV. O Stack O Focal ob1ects, parameters, temporaries, function return addresses. .$$$$$$$$$$. .$$$$$$$$$. O 7ata O @$$ O 7ata O Cnitial values for static and global ob1ects. .$$$$$$$$$$. .$$$$$$$$$. O Code O @$$ O Code O Executable machine instructions. .$$$$$$$$$$. .$$$$$$$$$. !Cannot be read or written b program.' O 4eserved O a.out on disk O for BS O O and otherO Cannot be read or written b program, will cause segmentation O programs O fault or general protection fault. .$$$$$$$$$$. Qemor

static o&,ects are placed in the data se(ment. They are initiali-ed from values stored in the e4ecuta&le file and therefore these values must &e 3nown at compile time. 5nitiali-ation occurs only once. Calues are maintained when the o&,ect is out of scope .e.(. &etween function calls/ and it is safe to return a pointer or reference to them. :umeric values not e4plicitly initiali-ed are set to 0.
int2 f!' 5 cop static int s3"; ..s; return s; 6 int main!' 5 cout @@ f!'; cout @@ f!'; f!'3T; s3#; EE 4eturn b reference, f!' is an alias for s, not a temporar once reference EE Cnitiali>ed onl EE Safe to return b EE EE EE EE

& % BX, s3T; Error, s is not in scope

re!ister
.Bare/ A hint to the compiler to optimi-e an int or pointer for speed. 5t is no lon(er used &ecause most optimi-ers can do a &etter ,o&.
register int x;

4olatile
.Bare/ 5ndicates that an o&,ect mi(ht &e modified from outside the pro(ram .e.(. a hardware input port/ and that the optimi-er should not ma3e copies of it. 5ts use is machine dependent.
const volatile unsigned short2 port38!const short8'+xfffe; EE "# bit port at address xfffe

Stan!ar! Li%rary Types


$tandard li&rary types .strin( vector map.../ and o&,ects .cin cout.../ re)uire a ?include @headerA and must &e e4tracted from namespace std either with a using namespace std; statement or &y usin( the fully )ualified names preceded with stdII as in stdIIcout.
?include @iostreamA int main!' 5 stdIIcout @@ J=ello*nJ; return +; 6 ?include @iostreamA using namespace std; int main!' 5 cout @@ J=ello*nJ; return +; 6

&iostream'
The header RiostreamS defines (lo&al o&,ect cin of type istream and (lo&al o&,ects cout, cerr, clog of type ostream. cin represents standard input normally the 3ey&oard unless redirected to a file or piped on the command line. cout represents standard output which is normally the screen unless redirected or piped. <ritin( to cerr or clog &oth write to the screen even if output is redirected. The difference is that writin( a newline .?Un?/ flushes any &uffered output to cerr &ut not to cout or clog. 5n the followin( in is an istream .cin/ out is an ostream .cout cerr clo(/ i is int c is char and cp is charF.
in AA x; in.get!'; in.get!c'; in.unget!'; in.getline!cp, i'; return in in.getline!cp, i, c'; getline!in, s'; in.good!'; bool!in'; in.bad!'; in.clear!'; in.eof!'; in.fail!'; out @@ x; out @@ endl; EE EE EE EE EE EE EE EE EE EE EE EE EE 4ead " word to numeric, string, or char8 x, return in 4ead " char !+$&TT' or EBF !$"' as an int 4ead " char into c, return in 9ut back last char read, return in 4ead up to i chars into char cp:i; or until )*n), 4ead to c instead of )*n), return in 4ead up to )*n) into string s, return in true if no error or EBF in.good!'; true if unexpected char in formatted input <llow more input after bad, or throw an iosIIfailure true if end of file true if s stem input error EE Formatted output, redirected with A EE 9rint )*n) and flush

5nput with SS reads a conti(uous se)uence of non%whitespace characters. 5f 4 is numeric and the ne4t word contains invalid characters .such as H1.5H or HfooH for an int/ then the first offendin( character remains unread in.&ad./ is set and no further input can occur until in.clear./ is called. 5nput into a charF array is not &ounds chec3ed. 5nput returns the istream to allow chainin( and has a conversion to &ool to test for success. 2utput also returns the ostream to allow chainin(.
EE 4ead and print pairs of strings and ints until something goes wrong EE CnputI hi % there T this is " test EE ButputI hi % there T string s; int i;

while !cin AA s AA i' cout @@ s @@ J J @@ i @@ endl; cin.clear!';

The (et./ methods read one character includin( whitespace. The various (etline./ functions read up throu(h the ne4t newline character and discard the newline. The methods good!', bad!', eof!', fail!', clear!' and implicit conversion to &ool are availa&le in ostream ,ust as in istream &ut are seldom used.

&iomanip'
=efines manipulators for formatted output of numeric types. They have no effect on strin(s. setw!' applies only to the ne4t o&,ect printed &ut the others remain in effect until chan(ed.
out @@ setw!i'; out @@ setfill!c'; out @@ setprecision!i'; EE 9ad next output to i chars, then back to + EE 9ad with c !default ) )' EE Hse i significant digits for all float, double

cout @@ setw!#' @@ setprecision!%' @@ setfill!)+)' @@ %."; EE print J++%."+J

&"stream'
=efines types ifstream and ofstream representin( input and output files respectively. ifstream is derived from istream inheritin( all its operations .such as SS/. 5n addition
ifstream in!cp'; EE Bpen file named cp for reading ifstream in!cp, iosIIin O iosIIbinar '; EE Bpen in binar mode bool!in'; EE true if open successful

cp is the file name. 5t must &e a charF not strin( .use s.cGstr!' to convert strin( s/. 5nput is normally in te4t mode. 5n <indows carria(e returns .?Ur?/ are discarded and an A$*55 2M .?U0I2?/ si(nals end of file. 5n &inary mode and in 6:5; no such translation occurs. The file is closed when the ifstream is destroyed.
5 ifstream f!Jinput.datJ, iosIIin O iosIIbinar '; if !Kf' cerr @@ JFile not found*nJ; else 5 int i3f.get!'; EE First b te or EBF if empt 6 6 EE f closed here

ofstream is derived from ostream inheritin( all its operations .such as RR/. 5n addition
ofstream os!cp'; EE Bpen file named cp for writing ofstream os!cp, iosIIout O iosIIbinar '; EE Bpen in binar mode

5n te4t mode in <indows writin( ?Un? actually writes HUrUnH. The file named cp is overwritten if it e4ists or created otherwise. The file is flushed and closed when the ofstream is destroyed.

&string'
A string is li3e an array of char &ut it also supports copyin( assi(nment and comparison and its si-e may &e set or chan(ed at run time. ?U0? has no special meanin(. There is implicit conversion from charF to strin( in mi4ed type e4pressions.
string!' string!cp' string!n, c' s3s& s"@s& s.si>e!' stringIIsi>eGt pe s.empt !' s:i; EE EE EE EE EE EE EE EE EE Empt string Convert char8 cp to string string of n copies of char c <ssign char8 or string s& to string s <lso 33, K3, A, @3, A3, either s" or s& ma be char8 Fength of string s / pe of s.si>e!', usuall unsigned int /rue if s.si>e!' 33 + i)th char, + @3 i @ s.si>e!' !unchecked', ma be assigned

to

s.at!i' EE s:i; with bounds check, throws outGofGrange s".s& EE Concatenate strings, either s" or s& ma be char or char8 s.3s& EE <ppend string, char, or char8 s& to string s s.cGstr!' EE string s as a const char8 with trailing )*+) s.substr!i, 1' EE Substring of string s of length 1 starting at s:i; s.substr!i' EE Substring from s:i; to the end s.find!s&' EE Cndex of char, char8, or string s& in s, or stringIInpos if not found s.rfind!s&' EE Cndex of last occurrence of s& in s s.findGfirstGof!s&' EE Cndex of first char in s that occurs in s& s.findGlastGof!s&' EE Cndex of last char in s that occurs in s& s.findGfirstGnotGof!s&' EE Cndex of first char in s not found in s& s.findGlastGnotGof!s&' EE Cndex of last char in s not found in s& s.replace!i, 1, s&' EE 4eplace s.substr!i, 1' with s&

s.si>e!' should &e converted to int to avoid unsi(ned comparison.


string s!%,)a)'; EE JaaaJ s .3 JbJ.s; EE JaaabaaaJ for !int i3+; iK3int!s.si>e!''; ..i' 5 EE print s one char at a time cout @@ s:i;; s.si>e!' A $"; EE falseK $" is converted to unsigned

string supports standard container operations with re(ard to iterators. string iterators are random supportin( all the pointer operators of char8. The notation :b,e' means the se)uence such that pointer or iterator & points to the first element and e points one past the last element.
s.begin!' EE Cterator pointing to s:+; s.end!' EE Cterator pointing " past last char stringIIiterator EE Cterator t pe, like char8 stringIIconstGiterator EE / pe if s is const, like const char8 string!b, e' EE string initiali>ed from seDuence :b,e' s.erase!b' EE 4emove char in s pointed to b b s.erase!b, e' EE 4emove substring :b,e' from s s.replace!b, e, s&' EE 4eplace substring :b,e' with string s&

*onversion from iterator to constGiterator is allowed &ut not the other way. constGiterator should &e used if the strin( is not (oin( to &e modified.
char8 cp3J<BC7EJ; string s!cp, cp.T'; EE J<BC7EJ

string s&!s.begin!'.", s.end!'$"'; EE JBC7J for !stringIIconstGiterator p3s.begin!'; pK3s.end!'; ..p' at a time cout @@ 8p; EE or p:+;

EE 9rint s one char

As with arrays and pointers inde4in( and iterator dereferencin( are not chec3ed at run time. *reatin( a strin( with a ne(ative or very lar(e si-e is also trou&le.
string s!$", )x)'; string s&!s.end!', s.begin!''; s:$";3)x); 8s.end!'3)x); stringIIiterator p; 8p3)x); EE EE EE EE EE Crash, Crash, Crash, Crash, Crash, negative si>e negative si>e out of bounds out of bounds dereferencing uninitiali>ed iterator

&(ector'
A vector@/A is li3e an array of T &ut supports copyin( assi(nment and comparison. 5ts si-e can &e set and chan(ed at run time and it can efficiently implement a stac3 .2.1/ time to push or pop/. 5t has random iterators li3e string which &ehave li3e type TF .or const TF if the vector is const/. 5f T is numeric elements are initiali-ed to 0. 5t is not possi&le to have an initiali-ation list such as W1 2 IX.
vector@/A!' vector@/A!n' vector@/A!n, x' vector@/A v&3v; v&3v; v&@v vector@/A!b, e' v.si>e!' vector@/AIIsi>eGt pe v.empt !' v:i; assigned to v.at!i' v.begin!', v.end!' vector@/AIIiterator v.back!' v.pushGback!x' v.popGback!' v.front!' v.resi>e!n' v.insert!d, x' b " v.insert!d, n, x' v.insert!d, b, e' v.erase!d' v.erase!d, e' v.clear!' v.reserve!n' v.capacit !' EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE Empt vector, elements of t pe / n elements, default initiali>ed n elements each initiali>ed to x Cop v to v& <ssignment <lso A, 33, K3, @3, A3 if defined for / Cnitiali>e to seDuence :b, e' n / pe of v.si>e!', usuall unsigned int true if v.si>e!' 33 + i)th element, + @3 i @ v.si>e!' !unchecked', ma

be

v:i; with bounds check, throws outGofGrange Cterators :b, e' Cterator t pe, also constGiterator v:v.si>e!'$"; !unchecked if empt ' Cncrease si>e b ", cop x to last element 7ecrease si>e b " !unchecked if empt ' v:+; !unchecked' Change si>e to n A3 + !unchecked' Cnsert x in front of iterator d, shift, increase si>e Cnsert n copies of x in front of d Cnsert cop of :b, e' in front of d 4emove 8d, shift, decrease si>e b " 4emove subseDuence :d, e' v.erase!v.begin!', v.end!'' <nticipate that v will grow to si>e n A3 v.si>e!' 4eserved si>e

0or insert and erase d and e must point into v .and d RE e/ or the pro(ram may crash. 9lements from Fd to the end are shifted and the si-e is chan(ed as needed. $aved copies of iterators may &ecome invalid after any chan(e of si-e or capacity .not chec3ed/. To implement pushGback!' efficiently a vector typically dou&les the reserved space when it runs

out in order to minimi-e memory reallocation and copyin(. reserve!' allows this strate(y to &e optimi-ed.
EE 4ead words from input into a stack, print in reverse order string s; vector@stringA v; while !cin AA s' v.pushGback!s'; while !Kv.empt !'' 5 cout @@ v.back!' @@ endl; v.popGback!'; 6

&!e)ue'
A deDue .dou&le ended )ueue/ is ,ust li3e a vector &ut optimi-ed for addin( and removin( elements at either end in 2.1/ time. 5t lac3s reserve!' and capacit !' and adds
v.pushGfront!x' v.popGfront!' EE v.insert!v.begin!', x' EE v.erase!v.begin!''

&list'
A list is li3e a de)ue &ut optimi-ed for insert and erase at any point at the cost of random access. 5t lac3s JK .inde4in(/ and its iterators are bidirectional not supportin( JK + % R S RE or SE. list adds
v.splice!d, v&, b'; EE Qove 8b from list v& to in front of d in v v.splice!d, v&'; EE Qove all elements of list v& to in front of d in v v.splice!d, v&, b, e'; EE Qove :b,e' in v& to in front of d at v v.remove!x'; EE 4emove all elements eDual to x v.removeGif!f'; EE 4emove elements x where f!x' is true v.sort!'; EE Sort list v.sort!f'; EE Sort list using function bool f!x, ' instead of x @ v.merge!v&'; EE Qerge sorted list v& into sorted list v v.merge!v&, f'; EE Qerge using f!x, ' instead of x @ to sort v v.uniDue!'; EE 4emove duplicates from sorted list v.uniDue!f'; EE Hse f!x, ' instead of x 33 v.reverse!'; EE 4everse order of elements

5terators can only &e moved one element at a time usin( ++ or %% and compared usin( EE or YE.
char8 cp3J<BC7EJ; list@charA v!cp, cp.T'; EE v.si>e!' is T for !list@charAIIconstGiterator p3v.begin!'; pK3v.end!'; ..p' cout @@ 8p; EE 9rint <BC7E

&map'
A map@X,\A m is a set of 3ey%value pairs with uni)ue sorted 3eys of type Z and values of type C. mJ3K efficiently .2.lo( n/ time/ returns the value associated with 3 .as an lvalue/ or creates a default value .0 if C is numeric/ if 3 is used for the first time. A map iterator points to a pair@const X, \A which has mem&ers first of type const Z and second of type C.
pair@X,\A x!k,v'; EE Create a pair x containing copies of k and v

x.first x.second x3makeGpair!k,v'

EE k EE v EE x.first3k; x.second3v;

map@X,\A m; EE map sorted b @ on X map@X,\,fA!' EE map sorted b f!x, ' instead of x@ on X m:k;3v; EE <ssociate v !t pe \' with uniDue ke k of t pe X m:k; EE 4etrieve v, or associate \!' with k if new m.si>e!' EE 0umber of uniDue ke s m.empt !' EE true if m.si>e!' 33 + map@X,\AIIiterator EE bidirectional, points to a pair@const X, \A map@X,\AIIconstGiterator EE points to a pair@const X, const \A m.begin!' EE 9oints to first pair !lowest k' m.end!' EE 9oints " past last pair m.find!k' EE 9oints to pair containing k or m.end!' if not found m.erase!k' EE 4emove ke X and its associated value m.erase!b' EE 4emove pair pointed to b iterator b m.erase!b, e' EE 4emove seDuence :b, e' m.clear!' EE Qake empt I m.erase!m.begin!', m.end!'' m33m& EE Compare maps, also K3, @, @3, A, A3

<e use m.find!k' rather than mJ3K when we wish to loo3 up 3 without increasin( the si-e of m if 3 is not found.
EE 4ead words, print an alphabetical index of words with their counts string s; map@string, intA m; while !cin AA s' ..m:s;; for !map@string, intAIIconstGiterator p3m.begin!'; pK3m.end!'; ..p' cout @@ p$Afirst @@ J J @@ p$Asecond @@ endl;

A multimap is a map that allows duplicate 3eys. 5t support all map operations e4cept JK. 9lements are added &y insertin( a pairRZ CS and retrieved &y m.eDualGrange!k' which returns a pair of iterators definin( the se)uence of pairs matchin( 3.
multimap@X,\,fA m; EE f defaults to @ on X m.insert!makeGpair!k,v'' EE Cnsert a pair pair@multimap@X,\,fAIIiterator, multimap@X,\,fAIIiteratorA p 3 m.eDualGrange!k' EE SeDuence with ke k is :p$Afirst, p$Asecond'

f .when used as a template ar(ument/ is a functoid .or function o&,ect/ a class that loo3s li3e a function &y overloadin( ./. 0or e4ample'
template @class /A class Rreater/han 5 publicI bool operator!'!const /2 a, const /2 b' const 5return b @ a;6 6; map@string, int, Rreater/han@/A A m; EE ke s sorted in reverse order

$ome function o&,ects can &e found in RfunctionalS.

&set'
A set@XA and multiset@XA are li3e a map and multimap &ut without values. 5terators point to a Z

rather than a pair. There is no JK operator.


set@XA m; m.insert!k' m.erase!k' m.find!k'K3m.end!' EE EE EE EE Elements are sorted b <dd an element 4emove an element /est if k is in m @ on X

&)ueue'
A Dueue is a container in which elements are inserted at the &ac3 and removed from the front. This could also &e done with a deDue or list so no new capa&ilities are provided. A Dueue does not support iterators or inde4in(.
Dueue@/A D; D.si>e!' D.empt !' D.push!x' x3D.back!' x3D.front!' D.pop!' EE EE EE EE EE EE EE [ueue of t pe / 0umber of items in D true if D.si>e!' 33 + 9ut x in the back /he item last pushed, ma /he next item to pop, ma 4emove the front item

be assigned to be assigned to

A priorit GDueue is more useful. 5t sorts the items as they are pushed so that the lar(est is on top and removed first.
priorit GDueue@/A D; EE Element t pe is / priorit GDueue@/, vector@/A, fA D; EE Hse functoid f!x, ' instead of x @ sort D.si>e!', D.empt !' EE <s before D.push!x' EE Cnsert x x3D.top!' EE Fargest item in D, cannot be assigned to D.pop!' EE 4emove top item to

&stac*'
5tems are popped from the top of a stack in the reverse order in which they were pushed. 5t does not provide any new functionality &eyond a vector de)ue or list and does not support iterators or inde4in(.
stack@/A s; s.si>e!', s.empt !' s.push!x'; x3s.top!'; s.pop!'; EE EE EE EE EE Stack with elements of t pe / <s with Dueue 9ut x on top Fast item pushed, ma be assigned to 4emove the top item

&%itset'
A bitset@0A is li3e a vector@boolA with fi4ed si-e : &ut without iterators and supportin( lo(ical operators li3e an :%&it int. 5ts elements have the values 0 or 1. 5t is implemented efficiently with D elements per &yte.
bitset@0A b; bitset@0A b3x; b:i; b.si>e!' EE EE EE EE 0$bit bitset, 0 must be a compile time constant Cnitiali>e b:+;..b:%"; from bits of long x i)th bit, + @3 i @ 0 or throw outGofGrange!' 0, cannot be changed

b.set!i' EE b:i; 3 " b.reset!i' EE b:i; 3 + b.flip!i' EE b:i; 3 " $ b:i; b.test!i' EE true if b:i; 33 " b.set!' EE Set all bits, also b.reset!', b.flip!' b 2 b& EE Bitwise <07, also O V S @@ AA 23 O3 V3 @@3 AA3 33 K3 b.count!' EE 0umber of bits set to " b.an !' EE true if b.count!' A + b.none!' EE true if b.count!' 33 + cin AA b EE 4ead bits as )+) and )") e.g. J"+"+"J cout @@ b EE Lrite bits as )+) and )") bitset@0A b!s'; EE Cnitiali>e from string s of )+) and )") or throw invalidGargument!' s3b.template toGstring@charA!' EE Convert to string x3b.toGulong!' EE Convert to unsigned long, throw overflowGerror!' if bits A %" set

&(alarray'
A valarra is li3e a fi4ed si-ed array or vector that supports arithmetic operations on all the elements at once. 0or instance if 4 and y are valarrays of the same si-e then 4+y is a valarray containin( the sums of the correspondin( elements. @i3ewise yEs)rt.4/ assi(ns yJiKEs)rt.4JiK/ to each element of y. 5n mi4ed type e4pressions a scalar .element of type T/ is promoted to a valarray of the same si-e &y duplicatin( it e.(. 4+1 adds 1 to all elements of 4.
valarra @/A v!n'; valarra @/A v!x, n'; valarra @/A v!a, n'; valarra @/A v; v.si>e!' v:i; v.3x, v.3v @@3 AA3 v.v, v.x, x.v sDrt!v' x3v.sum!' v.shift!n' v.cshift!n' v.resi>e!n' v.resi>e!n, x' EE EE EE EE EE EE EE EE EE EE EE EE EE EE n elements of t pe /, initiall /!' or + n copies of x !note arguments are backwards' Cnitiali>e from arra a:+;..a:n$"; si>e is + 0umber of elements, n i)th element, + @3 i @ n, not checked <dd x or v:i; to all v:i;, also 3 $3 83 E3 U3 V3 23 O3 <lso $ 8 E U V 2 O @@ AA and unar . $ S K <lso all functions in cmath Sum of all elements Qove all v:i; to v:i.n;, shift in + Qove v:i; to v:!i.n' U v.si>e!'; Change si>e to n, but reset all elements to + Change si>e to n, set all elements to x

&complex'
A complex supports comple4 arithmetic. 5t has real and ima(inary parts of type T. "i4ed type e4pressions promote real to comple4 .e.(. dou&le to comple4Rdou&leS and lower precision to hi(her precision .e.(. comple4RintS to comple4Rdou&leS/.
complex@/A x; EE complex@/A x3r; EE complex@/A x!r, i'; EE x3polar@/A!rho, theta'; x.real!' EE x.imag!' EE abs!x' EE arg!x' EE !+,+', / is a numeric t pe !r,+', convert real r to complex !r,i' EE 9olar notationI radius, angle in radians r i rho 3 sDrt!r8r.i8i' tan!theta' 3 iEr

norm!x' con1!x' x. sin!x' pow!x, ' cout @@ x cin AA x

EE EE EE EE

abs!x'8abs!x' !r,$i' <lso $ 8 E 33 K3 3 .3 $3 83 E3 and unar . $ <lso sinh, sDrt, tan, tanh, cos, cosh, exp, log, log"+,

EE 9rints in format J!r,i'J EE Expects JrJ, J!r'J, or J!r,i'J

&st!except'+ &exception'
The standard li&rary provides a hierarchy of e4ception types. :ot all of them are used &y the li&rary &ut any may &e thrown.
Type exception logicGerror lengthGerror domainGerror outGofGrange index out of bounds' invalidGargument runtimeGerror rangeGerror overflowGerror underflowGerror badGalloc badGcast to derived' badGt peid badGexception iosGbaseIIfailure ostreamIIclear!' Header stdexcept, exception stdexcept stdexcept stdexcept stdexcept stdexcept, bitset stdexcept stdexcept stdexcept stdexcept new t peinfo t peinfo exception ios, iostream, fstream T"ro3n by

.at!i' !vectorEstringEdeDue bitset!JxxxJ' !not )+) or )")'

new, new:; !out of memor ' d namicGcast@/2A !can)t convert t peid!8p' when p33+ istreamIIclear!',

*atchin( a &ase class catches all derived classes thus catch!exception e' catches all of the a&ove types. 8owever *++ allows throwin( e4ceptions not derived from exception so this may not catch everythin(. All e4ceptions provide the followin( interface'
throw exception!msg' EE /hrow exception with char8 or string msg throw exception!'; EE 7efault msg catch!exception e' 5e.what!';6 EE msg as a char8

:ew e4ceptions may &e derived from e4istin( types to maintain this interface .see inheritance/.
class Q ErrorI public exception 5 publicI Q Error!const string2 msg3JJ'I exception!msg' 56 6

C++ Stan!ar! Li%rary Functions


"any *++ standard li&rary functions operate on se)uences denoted &y iterators or pointers. Iterators are a family of types that include pointers. They are classified &y the operators they support. input, ..p, p.., p3D, p33D, pK3D, 8p .read%only/ output, p3D, p33D, pK3D, 8p.. 3 x .alternatin( write/increment/ "orwar!, input and output and p$Am, 8p .multiple read%write/ %i!irectional, forward and $$p, p$$ implemented &y list map multimap set multiset. ran!om, &idirectional and p@D, pAD, p@3D, pA3D, p.i, i.p, p$i, p$D, p:i; implemented &y arrays .as pointers/ strin( vector de)ue.

$ome al(orithms re)uire certain iterator types &ut will accept more powerful types. 0or e4ample cop !b, e, d' re)uire & and e to &e at least input iterators and d to &e at least an output iterator. >ut it will accept forward &idirectional or random iterators &ecause these all support input and output operations. sort!' re)uires random iterators and will accept no other type. The notation J& e/ denotes the se)uence of e%& o&,ects from &J0K to eJ%1K i.e. & points to the &e(innin( of the se)uence and e points one past the end. 0or most containers v the se)uence is Jv.&e(in./ v.end.//. 0or an array of n elements the se)uence is Ja a+n/.

&algorit-m'
5n the followin( & and e are input iterators and d is an output iterator unless otherwise specified. !arameters e) and lt are optional and default to functions that ta3e 2 ar(uments 4 and y and return 4EEy and 4Ry respectively e.(. bool eD!x, ' 5return x33 ;6. 4 and y are o&,ects of the type pointed to &y the iterators. p is a pair of iterators. f is a function or function o&,ect as noted.
EE Bperations on ordinar swap!x", x&'; min!x", x&'; max!x", x&'; EE 9roperties of seDuences eDual!b, e, b&, eD'; lexicographicalGcompare!b, i3minGelement!b, e'; i3maxGelement!b, e'; n3count!b, e, x'; n3countGif!b, e, f'; ob1ects EE Swap values of & ob1ects of the same t pe EE Smaller of x" or x&, must be same t pe EE Farger of x" or x&, must be same t pe !input iterators' EE true if :b,e'33:b&,...' e, b&, e&, lt'; EE true if :b,e'@:b&,e&' EE 9oints to smallest in :b,e' EE 9oints to largest EE 0umber of occurrences of x in :b,e' EE 0umber of f!x' true in :b,e'

EE Searching, i points to found item or end !e' if not found i3find!b, e, x'; EE Find first x in :b,e' i3findGif!b, e, f'; EE Find first x where f!x' is true i3search!b, e, b&, e&, eD';EE Find first :b&,e&' in :b,e' !forward' i3findGend!b, e, b&, e&, eD'; EE Find last :b&,e&' in :b,e' !forward' i3searchGn!b, e, n, x, eD';EE Find n copies of x in :b,e' !forward' p3mismatch!b, e, b&, eD'; EE Find first 8p.first in :b,e' K3 8p.second in :b&,.' !forward' i3ad1acentGfind!b, e, eD'; EE Find first of & eDual elements !forward' EE Qodif ing elements i3cop !b, e, d'; fill!d, i, x'; i3fillGn!d, n, x'; EE Cop :b,e' to :d,i' EE Set all in :d,i' to x !forward' EE Set n elements in :d,i' to x

generate!d, i, f'; EE Set :d,i' to f!' !e.g. rand' !forward' i3generateGn!d, n, f'; EE Set n elements in :d,i' to f!' f3forGeach!b, e, f'; EE Call f!x' for each x in :b,e' i3transform!b, e, d, f'; EE For x in :b,e', put f!x' in :d,i' i3transform!b, e, b&, d, f'; EE For x in :b,e', in :b&,.', put f!x, ' in :d,i' replace!b, e, x, ' EE 4eplace x with in :b,e' replaceGif!b, e, f, '; EE 4eplace with in :b,e' where f!x' is true i3replaceGcop !b, e, d, x, '; EE Cop :b,e' to :d,i' replacing x with i3replaceGcop Gif!b, e, d, f, '; EE Cop replacing with where f!x' is true EE 4earranging seDuence elements sort!b, e, lt'; EE Sort :b,e' b @ !random' stableGsort!b, e, lt'; EE Sort slower, maintaining order of eDual elements !random' partialGsort!b, m, e, lt'; EE Sort faster but leave :m,e' unsorted !random' nthGelement!b, m, e, lt'; EE Sort fastest but onl 8m in proper place !random' iterGswap!b, e'; EE swap!8b, 8e' !forward' i3swapGranges!b, e, b&'; EE swap :b,e' with :b&,i' !forward' i3partition!b, e, f'; EE Qoves f!x' true to front, :i,e' is f!x' false !bidirectional' i3stableGpartition!b, e, f'; EE Qaintains order within each partition i3remove!b, e, x'; EE Qove all x to end in :i,e' !forward' i3removeGif!b, e, f'; EE Qove f!x' true to front in :b,i' !forward' i3removeGcop !b, e, d, x'; EE Cop elements matching x to :d,i' i3removeGcop Gif!b, e, d, f'; EE Cop elements x if f!x' is false to :d,i' replace!b, e, x", x&'; EE 4eplace x" with x& in :b,e' i3replaceGcop !b, e, d, x", x&'; EE Cop :b,e' to :d,i' replacing x" with x& reverse!b, e'; EE 4everse element order in :b,e' !bidirectional' i3reverseGcop !b, e, d'; EE Cop :b,e' to :d,i' reversing the order !b,e bidirectional' rotate!b, m, e'; EE Qove :b,m' behind :m,e' !forward' i3rotateGcop !b, m, e, d'; EE 4otate into :d,i' randomGshuffle!b, e, f'; EE 4andom permutation, f!' defaults to rand!' nextGpermutation!b, e, lt';EE 0ext greater seDuence, true if successful !bidirectional' prevGpermutation!b, e, lt';EE 9revious permutation, true if successful !bidirectional' EE Bperations on sorted seDuences i3uniDue!b, e, eD'; EE Qove uniDue list to :b,i', extras at end i3uniDueGcop !b, e, d, eD'; EE Cop one of each in :b,d' to :d,i' i3binar Gsearch!b, e, x, lt'; EE Find i in :b,e' !forward' i3lowerGbound!b, e, x, lt'; EE Find first x in :b,e' or where to insert it !forward' i3upperGbound!b, e, x, lt'; EE Find " past last x in :b,e' or where to insert it !forward' p3eDualGrange!b, e, x, lt'; EE p.first 3 lower bound, p.second 3 upper bound !forward' includes!b, e, b&, e&, lt'; EE true if :b,e' is a subset of :b&,e&' i3merge!b, e, b&, e&, d, lt'; EE Qerge :b,e' and :b&,e&' to :d,i' inplaceGmerge!b, m, e, lt'; EE Qerge :b,m' and :m,e' to :b,e' !bidirectional' i3setGunion!b, e, b&, e&, d, lt'; EE :d,i' 3 uniDue elements in either :b,e' or :b&,e&' i3setGintersection!b, e, b&, e&, d, lt'; EE :d,i' 3 uniDue elements in both i3setGdifference!b, e, b&, e&, d, lt'; EE :d,i' 3 uniDue elements in :b,e' but not :b&,e&' i3setGs mmetricGdifference!b, e, b&, e&, d, lt'; EE :d,i' 3 elements in one but

not both

Al(orithms never chan(e the si-e of a container. <hen copyin( the destination must &e lar(e enou(h to hold the result.
int a:T;35%,",-,",#6; vector b!T'; cop !a, a.T, v.begin!''; remove!a, a.T, "'; sort!a, a.-'; EE Cop a to v EE 5%,-,#,","6, returns a.% EE 5",%,-,#,"6

&numeric'
5n the followin( plus, minus, and times are optional functions ta3in( 2 ar(uments 4 and y that return 4+y 4%y and 4Fy respectively e.(. int plus!int x, int ' 5return x. ;6
x3accumulate!b, e, x, plus'; x3innerGproduct!b, e, b&, x, plus, times'; ad1acentGdifference!b, e, minus'; partialGsum!b, e, plus'; EE EE EE EE x . x . for for sum over :b,e' sum :b,e'8:b&,e&' i in !b,e' 8i $3 i:$"; i in :b,e' 8i .3 sum :b,i'

&iterator'
An inserter is an output iterator that e4pands the container it points to &y callin( pushG&ac3./ pushGfront./ or insert./. The container must support this operation. A stream iterator can &e used to do formatted input or output usin( SS or RR
backGinserter!c'; EE frontGinserter!c'; EE inserter!c, p'; EE ostreamGiterator@/A!out, cp'; EE !default J J' istreamGiterator@/A!in'; EE istream <n iterator that appends to container c Cnserts at front of c Cnserts in front of p Lrites to ostream separated b char8 cp <n input iterator that reads / ob1ects from

The most common use is to copy to an empty vector de)ue or list.


vector@intA from!"+', to; cop !from.begin!', from.end!', backGinserter!to'';

This header also defines ta( types to &e used for creatin( iterator types that wor3 with al(orithms. $ee definin( iterators.

&"unctional'
0unctions in RfunctionalS create function objects which are o&,ects that &ehave li3e functions &y overloadin( operator!'. These can &e passed to al(orithms that ta3e function ar(uments e.(.
vector@intA v!"+'; sort!v.begin!', v.end!', greater@intA!''; EE Sort v in reverse order int x3accumulate!v.begin!', v.end!', ", multiplies@/A'; EE 9roduct of elements

The followin( create function o&,ects that ta3e one or two parameters 4 and y of type T and return the indicated e4pression i.e. eDualGto@intA!'!%,-' returns false.

EE 9redicates !return bool' eDualGto@/A!' notGeDualGto@/A!' greater@/A!' less@/A!' greaterGeDual@/A!' lessGeDual@/A!' logicalGand@boolA!' logicalGor@boolA!' logicalGnot@boolA!'

EE EE EE EE EE EE EE EE EE

x33 xK3 xA x@ xA3 x@3 x22 xOO Kx !unar '

EE <rithmetic operations !return /' plus@/A!' EE x. minus@/A!' EE x$ multiplies@/A!' EE x8 divides@/A!' EE xE modulus@/A!' EE xU negate@/A!' EE $x !unar '

A binder converts a 2%ar(ument function o&,ect into a 1%ar(ument o&,ect &y &indin( a fi4ed value c to the other ar(ument e.(. bind&nd!less@intA!', "+' returns a function ob1ect that takes one argument x and returns true if x@"+.
bind"st!f, c' bind&nd!f, c' EE <n ob1ect computing f!c, ' EE <n ob1ect computing f!x,c' EE Find first +

i3findGif!v.begin!', v.end!', bind&nd!eDualGto@intA!', +'';

/he following convert ordinar functions and member functions into function ob1ects. <ll functions must be converted to be passed to bind"st and bind&nd. Qember functions must also be converted to be passed to algorithms.
ptrGfun!f' memGfun!2/IIf' memGfunGref!/IIf' EE Convert ordinar function f to ob1ect EE Convert member function of class / EE Same EE SDuare

i3findGif!v.begin!', v.end!', memGfun!2stringIIempt ''; EE Find JJ transform!v.begin!', v.end!', v.begin!', bind&nd!ptrGfun!pow', &.+''; elements

not"!' and not&!' ne(ate a unary or &inary function o&,ect.


not"!f' not&!f' EE Bb1ect computing Kf!x' EE Bb1ect computing Kf!x, ' EE Find

i3findGif!v.begin!', v.end!', not"!bind&nd!eDualGto@intA!', +'''; non>ero

&new'
The default &ehavior of new is to throw an e4ception of type badGalloc if out of memory. This can &e chan(ed &y writin( a function .ta3in( no parameters and returnin( void/ and passin( it to setGnewGhandler!'.
void handler!' 5throw badGalloc!';6 EE /he default

setGnewGhandler!handler';

new!nothrow' may &e used in place of new. 5f out of memory it returns 0 rather than throw &adGalloc.
int8 p 3 new!nothrow' int:"+++++++++;; EE p ma be +

C Li%rary Functions
The * li&rary is provided for &ac3wards compati&ility with the * lan(ua(e. >ecause * lac3ed namespaces all types and functions were defined (lo&ally. 0or each * header *++ provides an additional header &y prefi4in( HcH and droppin( the H.hH suffi4 which places everythin( in namespace std. 0or instance @stdio.hA &ecomes @cstdioA.

&cst!li%'
"iscellaneous functions. s is type charF n is int
atoi!s'; atol!s'; atof!s';EE atof!J%.TJ' abs!x'; labs!x'; EE rand!'; EE %&,#,' srand!n'; EE s stem!s'; EE getenv!s'; EE getenv!J9</=J'; exit!n'; EE void8 p 3 malloc!n'; EE use new. p 3 calloc!n, "'; EE p 3 realloc!p, n'; EE free!p'; EE Convert char8 s to int, long, double e.g. <bsolute value of numeric x as int, long 9seudo$random int from + to 4<07GQ<P !at least Cnitiali>e rand!', e.g. srand!time!+''; Execute BS command s, e.g. s stem!JlsJ'; Environment variable or + as char8, e.g. Xill program, return status n, e.g. exit!+'; <llocate n b tes or + if out of memor . Bbsolete, <llocate and set to + or return 0HFF. Bbsolete. Enlarge to n b tes or return 0HFF. Bbsolete. Free memor . BbsoleteI use delete

&cctype'
*haracter tests ta3e a char c and return &ool.
isalnum!c'; EE isalpha!c'; isdigit!c'; EE islower!c'; isupper!c'; EE isgraph!c'; isprint!c'; EE isspace!c'; iscntrl!c'; EE ispunct!c'; EE isxdigit!c'; EE c3tolower!c'; c3toupper!c'; Cs c a letter or digitW Cs c a letterW 7igitW Cs c lower caseW Hpper caseW 9rinting character exceptEincluding spaceW Cs whitespaceW Cs a control characterW Cs printing except space, letter, or digitW Cs hexadecimal digitW EE Convert c to lowerEupper case

&cmat-'
0unctions ta3e dou&le and return dou&le.
sin!x'; cos!x'; tan!x'; EE asin!x'; acos!x'; atan!x';EE atan&! , x'; EE sinh!x'; cosh!x'; tanh!x';EE exp!x'; log!x'; log"+!x'; EE pow!x, '; sDrt!x'; EE ceil!x'; floor!x'; EE fabs!x'; fmod!x, '; EE /rig functions, x in radians Cnverses atan! Ex' = perbolic e to the x, log base e, log base "+ x to the , sDuare root 4ound up or down !as a double' <bsolute value, x mod

&ctime'
0unctions for readin( the system cloc3. timeGt is an inte(er type .usually lon(/. tm is a struct.
clock!'ECFBCXSG9E4GSEC; EE /ime in seconds since program started timeGt t3time!+'; EE <bsolute time in seconds or $" if unknown tm8 p3gmtime!2t'; EE + if HC/ unavailable, else p$AtmGP where P isI sec, min, hour, mda , mon !+$""', ear !$"N++', wda , da , isdst asctime!p'; EE J7a Qon dd hhImmIss *nJ asctime!localtime!2t''; EE Same format, local time

&cstring'
0unctions for performin( strin(%li3e operations on arrays of char mar3ed with a terminatin( ?U0? .such as JDuoted literalsJ or as returned &y stringIIcGstr!'. "ostly o&soleted &y type string.
strcp !dst, src'; EE Cop src to dst. 0ot bounds checked strcat!dst, src'; EE Concatenate to dst. 0ot bounds checked strcmp!s", s&'; EE Compare, @+ if s"@s&, + if s"33s&, A+ if s"As& strncp !dst, src, n'; EE Cop up to n chars, also strncat!', strncmp!' strlen!s'; EE Fength of s not counting *+ strchr!s,c'; strrchr!s,c';EE <ddress of firstElast char c in s or + strstr!s, sub'; EE <ddress of first substring in s or + EE mem... functions are for an pointer t pes !void8', length n b tes memcp !dst, src, n'; EE Cop n b tes from src to dst memmove!dst, src, n'; EE Same, but works correctl if dst overlaps src memcmp!s", s&, n'; EE Compare n b tes as in strcmp memchr!s, c, n'; EE Find first b te c in s, return address or + memset!s, c, n'; EE Set n b tes of s to c

&cst!io'
The stdio li&rary is made mostly o&solete &y the newer iostream li&rary &ut many pro(rams still use it. There are facilities for random access files and (reater control over output format error handlin( and temporary files. "i4in( &oth 5/2 li&raries is not recommended. There are no facilities for strin( 5/2. 7lo&al o&,ects stdin, stdout, stderr of type FCFE8 correspond to cin, cout, cerr. s is type charF c is char n is int f is 05@9F.
FCFE8 f3fopen!JfilenameJ, JrJ'; EE Bpen for reading, 0HFF !+' if error EE Qode ma also be JwJ !write' JaJ append, Ja.J random access readEappend, EE JrbJ, JwbJ, JabJ, Ja.bJ are binar fclose!f'; EE Close file f fprintf!f, Jx3UdJ, %'; EE 9rint Jx3%J Bther conversionsI JUTd Uu U$(ldJ EE int width T, unsigned int, long left 1ustified JUo Ux UP UlxJ EE octal, hex, =EP, long hex JUf UT."fJ EE doubleI "&%.++++++, "&%.+ JUe UgJ EE ".&%e&, use either f or g JUc UsJ EE char, char8 JUUJ EE U sprintf!s, Jx3UdJ, %'; EE 9rint to arra of char s printf!Jx3UdJ, %'; EE 9rint to stdout !screen unless redirected' fprintf!stderr, ... EE 9rint to standard error !not redirected' getc!f'; EE 4ead one char !as an int, +$&TT' or EBF !$"' from f

ungetc!c, f'; EE 9ut back one c to f getchar!'; EE getc!stdin'; putc!c, f' EE fprintf!f, JUcJ, c'; putchar!c'; EE putc!c, stdout'; fgets!s, n, f'; EE 4ead line including )*n) into char s:n; from f. 0HFF if EBF gets!s' EE fgets!s, C0/GQ<P, f'; no )*n) or bounds check fread!s, n, ", f'; EE 4ead n b tes from f to s, return number read fwrite!s, n, ", f'; EE Lrite n b tes of s to f, return number written fflush!f'; EE Force buffered writes to f fseek!f, n, SEEXGSE/'; EE 9osition binar file f at n EE or SEEXGCH4 from current position, or SEEXGE07 from end ftell!f'; EE 9osition in f, $"F if error rewind!f'; EE fseek!f, +F, SEEXGSE/'; clearerr!f'; feof!f'; EE Cs f at end of fileW ferror!f'; EE Error in fW perror!s'; EE 9rint char8 s and last CEB error message to stderr clearerr!f'; EE Clear error code for f remove!JfilenameJ'; EE 7elete file, return + if BX rename!JoldJ, JnewJ'; EE 4ename file, return + if BX f 3 tmpfile!'; EE Create temporar file in mode Jwb.J tmpnam!s'; EE 9ut a uniDue file name in char s:FGtmpnam;

94ample' input file name and print its si-e


char filename:"++;; EE Cannot be a string printf!JEnter filename*nJ'; EE 9rompt gets!filename, "++, stdin'; EE 4ead line ending in J*n*+J filename:strlen!filename'$";3+; EE Chop off )*n); FCFE8 f3fopen!filename, JrbJ'; EE Bpen for reading in binar mode if !f' 5 EE Bpen BXW fseek!f, +, SEEXGE07'; EE 9osition at end long n3ftell!f'; EE Ret position printf!JUs has Uld b tes*nJ, filename, n'; fclose!f'; EE Br would close when program ends 6 else perror!filename'; EE fprintf!stderr, JUsI not found*nJ, filename'; EE or permission denied, etc.

printf!', fprintf!' and sprintf!' accept a varia&le num&er of ar(uments one for each HNH in the format strin( which must &e the appropriate type. The compiler does not chec3 for this.
printf!JUd Uf UsJ, &, &.+, J&J'; EE BX printf!JUsJ, T'; EE CrashI expected a char8 arg, read from address T printf!JUsJ'; EE Crash printf!JUsJ, string!JhiJ''; EE CrashI use JhiJ or string!JhiJ'.cGstr!'

&cassert'
!rovides a de&u((in( function for testin( conditions where all instances can &e turned on or off at once. assert!false'; prints the asserted e4pression source code file name and line num&er then a&orts. *ompilin( with !++ -D5D6B78 effectively removes these statements.
assert!e'; EE Cf e is false, print message and abort

?define 07EBHR

EE !before ?include @assert.hA', turn off assert

Classes
*lasses provide data a&straction the a&ility to create new types and hide their implementation in order to improve maintaina&ility. A class is a data structure and an associated set of member functions .methods/ and related type declarations which can &e associated with the class or instances .o&,ects/ of the class. A class is divided into a public interface visi&le wherever the class or its instances are visi&le and a private implementation visi&le only to mem&er functions of the class.
class / 5 privateI !default' publicI EE / pe, ob1ect, 6; /IIm; / x; x.m; /8 p32x; p$Am; EE Create a new t pe / EE Qembers are visible onl to member functions of /

EE Qembers are visible wherever / is visible and function declarations EE EE EE EE Qember Create Qember Qember m of t pe / ob1ect x of t pe / m of ob1ect x m of ob1ect pointed to b

Typically the data structure is private and functionality is provided &y mem&er functions. "em&er function definitions should &e separated from the declaration and written outside the class definition or else they are assumed to &e inline .which is appropriate for short functions/. A mem&er function should &e declared const .&efore the openin( &race/ if it does not modify any data mem&ers. 2nly const mem&er functions may &e called on const o&,ects.
class Complex 5 EE 4epresents imaginar numbers privateI double re, im; EE 7ata members, represents re . im 8 sDrt!$"' publicI void set!double r, double i' 5re3r; im3i;6 EE Cnlined member function definition double real!' const 5return re;6 EE const $ does not modif data members double imag!' const; EE 7eclaration for non$inlined function 6; double ComplexIIimag!' const 5return im;6 EE 7efinition for imag!' int main!' 5 Complex a, b3a; EE Bb1ects of t pe Complex a.set!%, -'; EE Call a member function b3a; EE <ssign b.re3a.re; b.im3a.im b33a; EE Error, 33 is not defined cout @@ a.re; EE Error, re is private cout @@ a.real!'; EE BX, % cout @@ Complex!'.real!'; EE BX, prints an undefined value Complex!'.set!T, #'; EE Error, non$const member called on const ob1ect

A class has two special mem&er functions a constructor which is called when the o&,ect is created and a destructor called when destroyed. The constructor is named classIIclass has no return type or value may &e overloaded and have default ar(uments and is never const. 5t is followed &y an

optional initiali-ation list listin( each data mem&er and its initial value. 5nitiali-ation ta3es place &efore the constructor code is e4ecuted. 5nitiali-ation mi(ht not &e in the order listed. "em&ers not listed are default%initiali-ed &y callin( their constructors with default ar(uments. 5f no constructor is written the compiler provides one which default%initiali-es all mem&ers. The synta4 is'
classIIclass!parameter list'I member!value', member!value' 5 code...6

The destructor is named classIISclass has no return type or value no parameters and is never const. 5t is usually not needed e4cept to return shared resources &y closin( files or deletin( memory. After the code e4ecutes the data mem&ers are destroyed usin( their respective destructors in the reverse order in which they were constructed.
class Complex 5 publicI Complex!double r3+, double i3+'I re!r', im!i' 56 EE Constructor SComplex!' 56 EE 7estructor EE Bther members... 6; Complex a!",&', b!%', c3-, d; EE !",&' !%,+' !-,+' !+,+'

A constructor defines a conversion function for creatin( temporary o&,ects. A constructor that allows 1 ar(ument allows implicit conversion wherever needed such as in e4pressions parameter passin( assi(nment and initiali-ation.
Complex!%, -'.real!'; a 3 T; EE % EE Cmplicit a 3 Complex!T' or a 3 Complex!T, +'

void assignGif!bool, Complex2, const Complex2'; assignGif!true, a, #'; EE Cmplicit Complex!#' passed to third parameter assignGif!true, #, a'; EE Error, non$const reference to Complex!#', which is const

2perators may &e overloaded as mem&ers. The e4pression aPb for operator ; can match either operator P!a, b' .(lo&al/ or a.operator P!b' .mem&er function/ &ut not &oth. 6nary operators omit &. 2perators E JK and %S can only &e overloaded as mem&er functions.
class Complex 5 publicI Complex operator . !const Complex2 b' const 5 EE const because a.b doesn)t change a return Complex!re.b.re, im.b.im'; 6 EE ... 6; Complex operator $ !const Complex2 a, const Complex2 b' 5 return Complex!a.real!'$b.real!', a.imag!'$b.imag!''; 6 Complex a!", &', b!%, -'; a.b; EE a$b; EE a."+; EE "+.a; EE a$"+; EE "+$a; EE BX, a.operator.!b' 33 Complex!-, #' BX, operator$!a, b' 33 Complex!$&, $&' BX, Complex!", "&', implicit a.Complex!"+, +' Error, "+ has no member operator.!Complex' BX, Complex!", $(' BX, Complex!,, $-'

The mem&er function .+/ has the advanta(e of private access .includin( to other o&,ects of the same class/ &ut can only do implicit conversions on the ri(ht side. The (lo&al function .%/ is symmetrical &ut lac3s private access. A friend declaration .in either the private or pu&lic section/ allows private access to a (lo&al function.
class Complex 5 friend Complex operator$!const Complex2, const Complex2'; friend class /; EE <ll member functions of class / are friends EE ... 6;

A conversion operator allows implicit conversion to another type. 5t has the form of a mem&er function named operator /!' const with implied return type T. 5t is (enerally a (ood idea to allow implicit conversions in only one direction prefera&ly with constructors so this mem&er function is usually used to convert to pre%e4istin( types.
class Complex 5 publicI operator double!' const 5return re;6 EE ... 6 Complex a!", &'; a$"+; a$Complex!"+'; double!a'$"+; EE Error, double!a'$"+ or a$Complex!"+' W EE Complex!$N, &'; EE $N

An explicit constructor does not allow implicit conversions.


class Complex 5 explicit Complex!double r3+, double i3+'; EE ... 6; Complex a3"; Complex a!"'; a$"+; a$Complex!"+'; EE EE EE EE Error BX BX, double!a'$"+ 3 $N BX, Complex!$N, +'

A class or mem&er function may &e template!. The type parameter must &e passed in the declaration for o&,ects of the class.
template @class /A class Complex 5 / re, im; publicI / real!' const 5return re;6 / imag!' const 5return im;6 Complex!/ r3+, / i3+'; friend Complex@/A operator $ !const Complex@/A2, const Complex@/A2'; 6; template @class /A Complex@/AIIComplex!/ r, / i'I re!r', im!i' 56 Complex@intA a!", &'; Complex@doubleA b!".+, &.+'; EE Complex of int EE Complex of double

a3a$Complex@intA!%, -'; Complex@Complex@doubleA A c!b, b'; c.real!'.imag!';

EE Complex@intA!$&, $&' EE 0ote space, not AA EE &.+

Templates can have default ar(uments and int parameters. The ar(ument to an int parameter must &e a value 3nown at compile time.
template @class /, class H3/, int n3+A class \ 56; \@double, string, %A v"; \@charA v&; EE \@char, char, +A

*lasses define default &ehavior for copyin( and assi(nment which is to copy/assi(n each data mem&er. This &ehavior can &e overridden &y writin( a copy constructor and operator3 as mem&ers &oth ta3in( ar(uments of the same type passed &y const reference. They are usually re)uired in classes that have destructors such as the vector@/A%li3e class &elow. 5f we did not overload these the default &ehavior would &e to copy the data pointer resultin( in two Cectors pointin( into the same array. The assi(nment operator normally returns itself .8this/ &y reference to allow e4pressions of the form a3b3c; &ut is not re)uired to do so. this means the address of the current o&,ectT thus any mem&er m may also &e called this$Am within a mem&er function.
template @class /A class \ector 5 privateI /8 data; EE <rra of n elements int n; EE si>e!' publicI t pedef /8 iterator; EE \ectorIIiterator means /8 t pedef const /8 constGiterator; EE Cterators for const \ector int si>e!' const 5return n;6 EE 0umber of elements /2 operator:;!int i' 5return data:i;;6 EE i)th element const /2 operator:;!int i' const 5return data:i;;6 EE i)th element of const \ector iterator begin!' 5return data;6 EE First, last." elements iterator end!' 5return data.si>e!';6 constGiterator begin!' const 5return data;6 EE Const versions constGiterator end!' const 5return data.si>e!';6 \ector!int i3+'I data!new /:i;', n!i' 56 EE Create with si>e i S\ector!' 5delete:; data;6 EE 4eturn memor \ector!const \ector@/A2 v'I data!new /:v.n;', n!v.n' 5 EE Cop constructor cop !v.begin!', v.end!', begin!''; 6 \ector2 operator3!const \ector2 v' 5 EE <ssignment if !2v K3 this' 5 EE <ssignment to selfW delete:; data; EE Cf not, resi>e and cop data3new /:n3v.n;; cop !v.begin!', v.end!', begin!''; 6 return 8this; EE <llow a3b3c; 6 template @class 9A \ector!9 b, 9 e'I data!new /:e$b;', n!e$b' 5 EE /emplated member cop !b, e, data'; EE Cnitiali>e from seDuence :b, e' 6 6;

A type defined in a class is accessed throu(h classIIt pe

\ector@intAIIiterator p; EE / pe is int8 \ector@intAIIconstGiterator cp; EE / pe is const int8

"em&er functions may &e overloaded on const. 2verloaded mem&er functions need not have the same return types. const mem&er functions should not return non%const references or pointers to data mem&ers.
\ector@intA v!"+'; const \ector@intA cv!"+'; cv3v; v:T;3cv:T;; cv:T;3v:T;; p3cv.begin!'; cp3cv.begin!'; EE EE EE EE EE EE EE Hses non$const :;, begin!', end!' Hses const :;, begin!', end!' Error, non$const operator3 called on cv BX. assigns to int2 Error, assigns to const int2 Error, would allow 8p3x to write into cv BX because can)t assign to 8cp

De"ining Iterators. $ometimes a container?s iterator types must &e defined as nested classes overloadin( the usual pointer operations rather than typedef?ed to pointers. 5n order to wor3 properly with functions defined in Ral(orithmS iterators should define the followin( 5 pu&lic typedefs' iteratorGcategor ' one of the followin( .defined in @iteratorA/' outputGiteratorGtag .if se)uential writin( is supported/ inputGiteratorGtag .if se)uential readin( is supported/ forwardGiteratorGtag .if &oth are supported/ bidirectionalGiteratorGtag .if the iterator can &e decremented/ randomGaccessGiteratorGtag .if all pointer operations are supported/ valueGt pe' the type of the elements for e4ample / differenceGt pe' the result of iterator su&traction usually ptrdiffGt .a si(ned int type/ pointer' the type returned &y operator$A!' usually /8 or const /8 reference' the type returned &y operator8!' usually /2 or const /2 2perator %S should &e overloaded as a unary function returnin( a pointer to a class to which %S will &e applied i.e. x$Am is interpreted as x.operator$A!'$Am. :ested class mem&ers are named 2uter''5nner''mem&er. 2uter and inner classes cannot access each other?s private mem&ers. Templated mem&ers defined outside the class need their own template declarations.
template @class /A class \ector 5 publicI EE 4everse iterator for \ector, i.e. ..p goes to the previous element. class reverseGiterator 5 privateI /8 p; EE 9oints to current element publicI EE t pedefs needed to work with @algorithmA functions t pedef stdIIrandomGaccessGiteratorGtag iteratorGcategor ; EE 7efined in @iteratorA t pedef / valueGt pe; EE / pe of element t pedef ptrdiffGt differenceGt pe; EE 4esult of iterator subtraction, usuall int t pedef /8 pointer; EE / pe returned b operator $A t pedef /2 reference; EE / pe returned b operator 8

reverseGiterator!/8 a3+'I p!a' 56 iterator iterator base!' const 5return p;6

EE Cmplicit conversion from /8 and EE Convert to normal iterator

EE Forward operators reverseGiterator2 operator..!' 5$$p; return 8this;6 EE prefix reverseGiterator operator..!int'; EE postfix, we pretend it)s binar reference operator8!' const 5return 8p;6 pointer operator$A!' const 5return p;6 EE Le pretend it)s unar bool operator33!\ector@/AIIreverseGiterator b' const 5return p33b.p;6 bool operatorK3!\ector@/AIIreverseGiterator b' const 5return pK3b.p;6 EE <lso, bidirectional and random operators 6; reverseGiterator rbegin!' 5return end!'$";6 reverseGiterator rend!' 5return begin!'$";6 EE Bther members... 6; EE Code for postfix .. template @class /A inline \ector@/AIIreverseGiterator \ectorIIreverseGiteratorIIoperator..!int dumm ' 5 \ector@/AIIreverseGiterator result 3 8this; ..8this; return result; 6; EE 9rint a \ector in reverse order int main!' 5 \ector@intA a!"+'; for !\ector@intAIIreverseGiterator p3a.rbegin!'; pK3a.rend!'; ..p' cout @@ 8p @@ endl;

vector@/A supplies random reverseGiterator and constGreverseGiterator as a&ove. *onst iterators would typedef pointer as const /8 and reference as const /2. A static data mem&er is shared &y all instances of a class. 5t must &e initiali-ed in a separate declaration not in the class definition or in the constructor initiali-ation list. A static mem&er function cannot refer to this or any non%static mem&ers .and therefore it ma3es no sense to ma3e them const/. $tatic mem&ers may &e referenced either as object.member or classIImember.
class Counter 5 static int count; EE 0umber of Counters that currentl exist !private' publicI static int get!' 5return count;6 Counter!' 5..count;6 SCounter!' 5$$count;6 Counter!const Counter2 c' 5..count;6 EE 7efault would be wrong Counter2 operator3!const Counter2 c' 5return 8this;6 EE 7efault would be BX 6; int CounterIIcount 3 +; EE Cnitiali>e here, BX if private main!' 5 Counter a, b, c; cout @@ b.get!'; EE % cout @@ CounterIIget!'; EE % 6

In-eritance
5nheritance is used to write a speciali-ed or enhanced version of another class. 0or e4ample an ofstream is a type of ostream. class DI public B defines class = as derived from .su&class of/ base class .superclass/ > meanin( that = inherits all of >?s mem&ers e4cept the constructors destructor and assi(nment operator. The default &ehavior of these special mem&er functions is to treat the &ase class as a data mem&er.
class StringI public \ector@charA 5 publicI String!const char8 s3JJ'I \ector@charA!strlen!s'' 5 cop !s, s.strlen!s', begin!''; EE Cnherits \ector@charAIIbegin!' 6 6; String a3JhelloJ; EE Calls \ector@charAII\ector!T'; a.si>e!'; EE T, inherits \ector@charAIIsi>e!' a:+;3)1); EE J1elloJ, inherits \ector@charAIIoperator:; String b3a; EE 7efault cop constructor uses \ector)s cop constructor on base part b3a; EE 7efault 3 calls \ector)s assignment operator on base part

The default destructor StringIISString!' 56 is correct since in the process of destroyin( a $trin( the &ase is also destroyed callin( \ector@charAIIS\ector!' 5delete data:;;6. $ince there is no need to write a destructor there is no need to redefine copyin( or assi(nment either. Althou(h String inherits \ector@charAIIdata it is private and inaccessi&le. A protected mem&er is accessi&le to derived classes &ut private elsewhere.
class B 5 protectedI int x; 6 b; b.x3"; class 7I public B 5 void f!' 5x3";6 6;

EE 7eclare class B and ob1ect b EE Error, x is protected EE BX

>y default a &ase class is private ma3in( all inherited mem&ers private. !rivate &ase classes are rare and typically used as implementations rather than speciali-ations .A strin( is a vector &ut a stac3 is not/.
class StackI \ector@intA 5 EE or class StackI private \ector@intA publicI bool empt !' const 5return si>e!'33+;6 EE BX 6 s; s.si>e!'; EE Error, private s.empt !'; EE BX, public

A class may have more than one &ase class .called multiple inheritance/. 5f &oth &ases are in turn derived from a third &ase then we derive from this root class usin( virtual to avoid inheritin( its mem&ers twice further on. Any indirectly derived class treats the virtual root as a direct &ase class in the constructor initiali-ation list.
class ios 5...6; class fstreambaseI public virtual ios 5...6; EE good!', binar , ... EE open!', close!', ...

class istreamI public virtual ios 5...6; operatorAA!', ... class ifstreamI public fstreambase, public istream 5 ifstream!'I fstreambase!', istream!', ios!' 5...6 omitted 6;

EE get!', EE Bnl " cop of ios EE 0ormall ios!' would be

Polymorp-ism
!olymorphism is the techni)ue of definin( a common interface for a hierarchy of classes. To support this a derived o&,ect is allowed wherever a &ase o&,ect is e4pected. 0or e4ample
String s3J=elloJ; \ector@charA v3s; EE 7iscards derived part of s to convert \ector@charA8 p32s; EE p points to base part of s tr 5throw s;6 catch!\ector@charA x' 56 EE Caught with x set to base part of s s3\ector@charA!T'; EE Error, can)t convert base to derived EE <llow output of \ector@charA using normal notation ostream2 operator @@ !ostream2 out, const \ector@charA2 v' 5 cop !v.begin!', v.end!', ostreamGiterator@charA!out, JJ''; return out; EE /o allow !cout @@ a' @@ b; 6 cout @@ s; EE BX, v refers to base part of s ofstream f!Jfile.txtJ'; f @@ s; EE BX, ofstream is derived from ostream

EE 9rint v to out

A derived class may redefine inherited mem&er functions overridin( any function with the same name parameters return type and const%ness .and hidin( other functions with the same name thus the overridin( function should not &e overloaded/. The function call is resolved at compile time. This is incorrect in case of a &ase pointer or reference to a derived o&,ect. To allow run time resolution the &ase mem&er function should &e declared virtual. $ince the default destructor is not virtual a virtual destructor should &e added to the &ase class. 5f empty no copy constructor or assi(nment operator is re)uired. *onstructors and E are never virtual.
class Shape 5 publicI virtual void draw!' const; virtual SShape!' 56 6; class CircleI public Shape 5 publicI void draw!' const; EE Qust use same parameters, return t pe, and const 6; Shape s; s.draw!'; Circle c; c.draw!'; Shape2 r3c; r.draw!'; Shape8 p32c; p$Adraw!'; p3new Circle; p$Adraw!'; delete p; EE EE EE EE EE EE ShapeIIdraw!' CircleIIdraw!' CircleIIdraw!' if CircleIIdraw!' if CircleIIdraw!' if CircleIISCircle!'

virtual virtual virtual if virtual

An abstract &ase class defines an interface for one or more derived classes which are allowed to instantiate o&,ects. A&stractness can &e enforced &y usin( protected .not private/ constructors or usin( pure virtual mem&er functions which must &e overridden in the derived class or else that class is

a&stract too. A pure virtual mem&er function is declared 3+; and has no code defined.
class Shape 5 protectedI Shape!'; EE Bptional, but default would be public publicI virtual void draw!' const 3 +; EE 9ure virtual, no definition virtual SShape!' 56 6; EE Circle as before Shape s; Circle c; Shape2 r3c; r.draw!'; Shape8 p3new Circle!'; EE EE EE EE Error, protected constructor, no ShapeIIdraw!' BX BX, CircleIIdraw!' BX

#un time type i!enti"ication *++ provides for run time type identification althou(h this usually indicates a poor desi(n. d namicGcast@/A.4/ chec3s at run time whether a &ase pointer or reference is to a derived o&,ect and if so does a conversion. The &ase class must have at least one virtual function to use run time type chec3in(.
?include @t peinfoA t peid!8p'33t peid!/' d namicGcast@/8A!p' d namicGcast@/2A!r' badGcast!' EE EE EE EE For t peid!' true if p points to a / Convert base pointer to derived /8 or +. Convert base reference to derived /2 or throw

0or e4ample
B class B 5publicI virtual void f!'566; class 7I public B 5publicI int x;6 d; EE Bad design, public member in 7 but not EE Error, no BIIx EE Error, can)t convert B8 to 78 EE BX, but reinterpretGcast, no run time EE BX

B8 p32d; p$Ax; 78 D3p; D$Ax; D3!78'p; D$Ax; check D3d namicGcast@78A!p'; if !D' D$Ax;

.t-er Types
typedef defines a synonym for a type.
t pedef char8 Str; Str a, b:T;, 8c; char8 d3a; EE Str is a s non m for char8 EE char8 a; char8 b:T;; char88 c; EE BX, reall the same t pe

enu9 defines a type and a set of sym&olic values for it. There is an implicit conversion to int and e4plicit conversion from int to enum. You can specify the int e)uivalents of the sym&olic names or they default to successive values &e(innin( with 0. 9nums may &e anonymous specifyin( the set of sym&ols and possi&ly o&,ects without (ivin( the type a name.
enum Leekda 5QB0,/HE3",LE7,/=H,F4C6; enum Leekda toda 3LE7; toda 33& toda 3Leekda !%'; enum 503"+6; int a:0;; enum 5S</,SH06 weekend3S</; EE EE EE EE EE EE EE / pe declaration Bb1ect declaration, has value & true, implicit int!toda ' /=H, conversion must be explicit <non mous enum, onl defines 0 BX, 0 is known at compile time Bb1ect of anon mous t pe

A struct is a class where the default protection is pu&lic instead of private. A struct can &e initiali-ed li3e an array.
struct Complex 5double re, im;6; Complex a, b35",&6, 8p32b; a.re 3 p$Aim; EE 7eclare t pe EE 7eclare ob1ects EE <ccess members

A union is a struct whose fields overlap in memory. 6nions can also &e anonymous. They may &e used to implement variant records.
union H 5int i; double d;6; H u; u.i3%; EE si>eof!H' is larger of int or double EE overwrites u.d

EE < variant record class /oken 5 enum 5C0/, 7BHBFE6 t pe; EE which field is in useW union 5int i; double d;6 value; EE <n anon mous union publicI void print!' const 5 if !t pe33C0/' cout @@ value.i; else cout @@ value.d; 6 6;

An enum struct class or union type and a list of o&,ects may &e declared to(ether in a sin(le statement.
class Complex 5publicI double re, im;6 a, b35",&6, 8p32b;

Program .rgani/ation
0or *++ pro(rams that only use one source code file and the standard li&rary the only rule is to declare thin(s &efore usin( them' type declarations &efore o&,ect declarations and function declarations or definitions &efore callin( them. 8owever implicitly inlined mem&er functions may use mem&ers not yet declared and templates may use names as lon( as they are declared &efore instantiation.
class Complex 5 double real!' const 5return re;6 double re, im; 6; EE BX

7lo&al and mem&er functions .unless inlined or templated/ and (lo&al or class static o&,ects are separately compila&le units and may appear in separate source code ..cpp/ files. 5f they are defined and used in different files then a declaration is needed. To insure that the declaration and definition are consistent the declaration should &e in a shared header file. A shared header conventionally has a .h e4tension and is inserted with a ?include Jfilename.hJ usin( dou&le )uotes to indicate that the file is in the current directory. 7lo&al varia&les are declared with extern without initiali-ation.
EE prog.h extern int x; int f!'; EE prog".cpp ?include Jprog.hJ int x3+; int main!' 5 f!'; return +; 6 EE prog&.cpp ?include Jprog.hJ int f!' 5 return x; 6

To compile
!++ pro!11cpp pro!21cpp -o pro!

This produces two o&,ect files .prog".o, prog&.o/ and then lin3s them to produce the e4ecuta&le prog. (++ also accepts .o files which are lin3ed only savin( time if the .cpp file was not chan(ed. To compile without lin3in( use $c. To optimi-e .compile slower &ut run faster/ use $B. The 6:5; make command updates the e4ecuta&le as needed &ased on the timestamps of source and .o files. 5t re)uires a file named Qakefile containin( a set of dependencies of the form'
file: files which should be older than file !tab' commands to update file

=ependencies may &e in any order. The "a3efile is e4ecuted repeatedly until all dependencies are satisfied.
? Qakefile comment progI prog".o prog&.o g.. prog".o prog&.o $o prog prog".oI prog".cpp prog.h g.. $c prog".cpp prog&.oI prog&.cpp prog.h g.. $c prog&.cpp

*ompiler options for (++. 2ther compilers may vary.

g.. g.. g.. g.. g.. g.. g.. g.. g.. gxx

file".cpp file".cpp file&.o $Lall $c file".cpp $o file" $B $v $7P3] $$help file".cpp

Compile, produce executable a.out in H0CP Compile .cpp and link .o to executable a.out /urn on all warnings Compile to file".o, do not link 4ename a.out to file" Bptimi>e executable for speed \erbose mode EDuivalent to ?define P ] Show all g.. options Compile in Lindows QS$7BS box !7MR99' to <.EPE

Anythin( which is not a separately compila&le unit may appear in a header file such as class definitions .&ut not function code unless inlined/ templated classes .includin( function code/ templated functions and other ?include statements.

Creating Li%raries 0namespaces1


@i&raries usually come in the form of a header and an o&,ect ..o/ file. To use them ?include Jheader.hJ and lin3 the .o file usin( (++. 5f the .o was compiled in * rather than *++ then indicate this with extern JCJ 56 to turn off name man(lin(. *++ encodes or Hman(lesH overloaded function names to allow them to &e lin3ed &ut * does not since it doesn?t allow overloadin(.
extern JCJ 5 ?include Jheader.hJ 6 EE /urn off name mangling EE Lritten in C

<hen writin( your own li&rary use a uni)ue namespace name to prevent conflicts with other li&raries. A namespace may span multiple files. Types o&,ects and functions declared in a namespace : must &e prefi4ed with :'' when used outside the namespace or there must &e a using namespace 0; in the current scope. Also to (uard a(ainst possi&le multiple inclusions of the header file ?define some sym&ol and test for it with [ifndef ... [endif on the first and last lines. =on?t have a using namespace std; since the user may not want std visi&le.
?ifndef Q]FCBG= EE m lib.h, or use ?if Kdefined!Q]FCBG=' ?define Q]FCBG= ?include @stringA EE 0o using statement namespace m lib 5 class B 5 publicI stdIIstring f!'; EE 0o code 6 6 ?endif EE m lib.cpp, becomes m lib.o ?include @stringA ?include Jm lib.hJ using namespace std; EE BX namespace m lib 5 string BIIf!' 5return JhiJ;6 6

?define could &e used to create constants throu(h te4t su&stitution &ut it is &etter to use const to allow type chec3in(. ?define P ] has the effect of replacin( sym&ol ; with ar&itrary te4t Y &efore compilin( e)uivalent to the (++ option $7P3]. 9ach compiler usually defines a different set of sym&ols which can &e tested with ?if, ?ifdef, ?ifndef, ?elsif, ?else and ?endif.
?ifdef unix EE ... ?else EE ... ?endif EE 7efined b most H0CP compilers

!reprocessor statements are one line .no semicolon/. They perform te4t su&stitutions in the source code prior to compilin(.
?include @headerA ?include Jheader.hJ ?define P ] ?define f!a,b' a??b ?define P * ?ifdef P ?ifndef P ?if Kdefined!P' ?else ?endif EE EE EE EE EE EE EE EE EE EE Standard header Cnclude header file from current director 4eplace P with ] in source code 4eplace f!",&' with "& Continue a ? statement on next line /rue if P is ?defined False if P is ?defined Same Bptional after ?if... 4eDuired

History o" C++


*++ evolved from * which in turn evolved from > written &y Zen Thompson in 1VL0 as a variant of >*!@. * was developed in the 1VL0?s &y >rian Zerni(han and =ennis Bitchie as a Hporta&le assem&ly lan(ua(eH to develop 6:5;. * &ecame widely availa&le when they pu&lished HThe * !ro(rammin( @an(ua(eH in 1VDI. C lacked standard containers .strin( vector map/ iostreams &ool const references classes e4ceptions namespaces new/delete function and operator overloadin( and o&,ect%oriented capa&ilities. 5/2 was done usin( @stdio.hA. Strings were implemented as fixed sized char[] arrays requiring functions to assign or compare them strcpy !" strcmp !!. Structs could not be assigned" and had to be copied using memcpy !. #unction arguments were not type checked. #unctions could only modify arguments by passing their addresses. $emory allocation was done using malloc !" which requires the number of bytes to allocate and returns an untyped pointer or %&'' if it fails. The lan(ua(e allowed unsafe implicit conversions such as int to pointers. Caria&les had to &e declared &efore the first statement. (here was no inline" so macros were often used in place of small functions) *ardware was slow and optimizers were not very good" so it was common to declare register variables. (here were no ++ style comments) 0or instance

8E 8E 8E 8E 8E 8E 8E 8E 8E

E8 Cop argv:"; to buf and print it 8E ?include @stdio.hA E8 0o cout, use printf!' ?include @string.hA ?include @stdlib.hA main!argc, argv' int argc; char88 argv; 5 char8 buf; E8 0o string t pe, use char8 E8 0o newEdelete, use mallocEfree E8 4eturn t pe defaults to int 8E E8 Bld st le parameter declaration, no t pe checking E8 0o namespace std E8 <ll declarations before the first statement E8 Cast optional

if !argcA"' 5 buf3!char8'malloc!!strlen!argv:";'."'8si>eof!char''; strcp !buf, argv:";'; printf!JUs*nJ, buf'; free!buf';

E8 Can)t assign, no range check E8 <rguments not t pe checked E8 0o delete 8E

6 8E 6 E8 4eturn value is undefined !unchecked'

The A:$5 * standard was finished in 1VDD. 5t added const new style function declaration with type chec3in( struct assi(nment strict type chec3in( of pointer assi(nments and specified the standard * li&rary which until now was widely used &ut with minor annoyin( variations. 8owever many compilers did not &ecome A:$5 compliant until the early 1VV0?s. 5n the 1VD0?s >,arne $troustrup at ATOT developed H* with *lassesH later *++. 9arly implementations were availa&le for 6:5; as cfront .cc/ a *++ to * translator around 1VV0. 5t added o&,ect oriented pro(rammin( with classes inheritance and polymorphism also references the iostream li&rary and minor enhancements such as // style comments and the a&ility to declare varia&les anywhere. >ecause there were no namespaces the iostream header was named Riostream.hS and no using statement was re)uired. 6nli3e * pro(rams which always have a .c e4tension *++ didn?t say so .cpp .cc and .* were all common and .hpp for headers. 7:6 (cc and (++ which compiled * and *++ directly to machine code were developed in the early 1VV0?s. Templates were added in 1VVI. 94ceptions were added in 1VV4. The standard container li&rary .ori(inally called the standard template li&rary or $T@/ was developed &y researchers at 8ewlett% !ac3ard and made availa&le free as a separate download in the mid 1VV0?s and ported to several compilers. A:$5 standard *++ compilers &ecame availa&le in 1VVD. This added $T@ to the standard li&rary added multiple inheritance namespaces type &ool and run time type chec3in( .dynamicGcast typeid/. The .h e4tension on headers was dropped. *++ most li3ely succeeded where other early o&,ect oriented lan(ua(es failed .$imulaML Actor 9iffel $mallTal3/ &ecause it was &ac3wards compati&le with * allowin( old code to &e used and &ecause * pro(rammers could use it immediately without learnin( the new features. 8owever there are a few incompati&ilities. 2ld style function declarations are not allowed. *onversion from void8 .returned &y malloc!'/ re)uires a cast. There are many new reserved words. There are also some incompati&ilities &etween old .&efore 1VVD/ and new versions of *++. new was chan(ed to throw type badGalloc if out of memory instead of returnin( 0. The scope of a varia&le declared in a for loop was chan(ed to &e local to the loop and not &eyond it .not yet implemented &y "icrosoft Cisual *++/ (++ does not yet implement all A:$5 *++ features. 0or instance Type ostringstream allowin( formatted writin( to strin(s. Bun time &ounds chec3in( of vector inde4es usin( v.at.i/ The lar(est inte(er type is I2 &its in most implementations &ut as M4 &it machines &ecome common it

is possi&le that type long could &ecome a M4 &it type .as in 1ava/ in the future. (++ supports the nonstandard M4%&it inte(er type long long e.(.
unsigned long long big>ero3+FFH;

"ost implementations of time!' return the num&er of seconds since 1an. 1 1VL0 as a timeGt normally a si(ned I2%&it long. !ro(rams that use this implementation will fail on 1an. 1V 20ID at I'14'0D A" as this value overflows and &ecomes ne(ative.

Potrebbero piacerti anche