· 5 years ago · Jul 13, 2020, 05:32 PM
1How to Program in C++ -- CodeBlocks is absolutely free to use for this
2You may copy this file for noncommercial use.
3
4Language Summary
5Basic Concepts
6
7Statements if, for, while, return, break...
8
9Expressions arithmetic, comparison, assignment...
10
11The most important types are int, char, bool, double, and the containers string, vector, and map. Summary of common types:
12
13Built-in Description
14int x; Fastest integer type (16-32 bits), also short, long, unsigned
15char x; 8-bit character, '\0' to '\xFF' or -128 to 127
16double x; 64 bit real + or - 1.8e308, 14 significant digits, also float
17bool x; true or false
18
19Modifiers Description
20const T x; Non-modifiable object
21T& y=x; Reference, y is an alias for x, which both have type T
22T f(...) {...} Defines f as a function returning T
23T* p; Pointer to T (*p is a T object)
24T[N] a; Array of N elements of T, a[0] to a[N-1]
25static T x; Place x in data segment
26register T x; (rare) Hint to optimize for speed
27volatile T x; (rare) x may be modified externally
28The following standard library types and functions require at the beginning of the program:
29 #include <header>
30 using namespace std;
31
32Library Type Description Header
33istream Standard input (cin) iostream
34ostream Output (cout, cerr) iostream
35ifstream Input file fstream
36ofstream Output file fstream
37string Sequence of char string
38vector<T> Expandable array/stack of T vector
39deque<T> Array/double ended queue deque
40list<T> List/stack/queue of T list
41map<T1,T2> Associative mapping of T1 to T2 map
42pair<T1,T2> Two objects of type T1 and T2 map or utility
43priority_queue<T> Sorted queue queue
44stack<T> Stack stack
45bitset<N> Array of N bool with logical operations bitset
46valarray<T> Array with arithmetic operations valarray
47complex<T> Complex number complex
48iterator Pointer into a container (Included with container)
49const_iterator Pointer not allowing element assignment (Included with container)
50exception Hierarchy of exception types stdexcept, exception
51
52C++ Standard Library Functions Header
53min(), max(), swap(), sort(), copy(), equal() algorithm
54accumulate(), inner_product() numeric
55back_inserter() iterator
56equal_to(), less(), bind2nd() functional
57set_new_handler() new
58
59C Library Functions Header
60atoi(), atof(), abs(), rand(), system(), exit() cstdlib
61isalpha(), isdigit(), tolower(), toupper() cctype
62sqrt(), log(), exp(), pow(), sin(), cos(), atan() cmath
63clock(), time() ctime
64strlen(), memset(), memmove(), memcmp() cstring
65printf(), fopen(), getc(), perror() cstdio
66assert() cassert
67C++ allows you to create your own types and libraries. The most important type is a class, allowing object oriented programming. A class is an abstract data type with a hidden representation and a set of public member functions and types. Classes can be organized into a hierarchy (inheritance), and you can write code that accepts any type in this hierarchy (polymorphism). Functions and classes can be parameterized by type (templated).
68
69class T {...}; Defines T as a collection of types, objects, and member functions
70template <class T> ... Defines a set of functions or classes over all T
71typedef T U; Defines type U is a synonym for T
72enum T {...}; Defines T as an int, and set of int constants
73struct T {...}; Like a class, except default scope of members is public
74union T {...}; A struct with object members overlapping in memory
75namespace N {...}; Defines a scope for a collection of types, objects, and functions
76
77Program Organization (compiling, linking, make)
78History of C++
79Further Reading
80Basics
81C++ is a compiled language, an upward compatible superset of C and an (incompatible) predecessor to Java. C++ compiles C programs but adds object oriented (OO) features (classes, inheritance, polymorphism), templates (generic functions and classes), function and operator overloading, namespaces (packages), exception handling, a library of standard data structures (string, vector, map, etc.) and formatted text I/O (istream, ostream). Unlike Java, C++ lacks a standard graphical user interface (GUI), network interface, garbage collection, and threads, and allows non-OO programming and unchecked low-level machine operations with pointers. However, C++ executes faster than Java and requires no run-time support.
82
83A C++ program is a collection of function, object, and type declarations. Every program must have a function int main() { ... } where the curly braces enclose a block, a sequence of declarations and statements ending in semicolons which are executed in order. A statement is an expression, block, or control statement that alters the order of execution, such as if, while, for, break, return. Some types (std::string), objects (std::cout), and functions are defined in header files, requiring the line #include <header> before use. Items defined in the standard headers are in the namespace std. The std:: prefix may be dropped after the statement using namespace std;. For instance,
84
85 // Comment: prints "Hello world!" and an OS-independent newline
86 #include <string> // Defines type std::string
87 #include <iostream> // Defines global object std::cout
88 using namespace std; // Allow std:: to be dropped
89 int main() { // Execution starts here
90 string s="Hello world!\n"; // Declares object s of type string
91 cout << s; // An expression as a statement, << is the output operator
92 return 0; // Execution ends here
93 }
94The symbol // denotes a comment to the end of the line. You may also use /* ... */ for multiline comments. Spacing and indentation is used for readability. C++ is mostly free-form, except that the end of line is significant after # and //. C++ is case sensitive.
95
96C++ source code files should be created with a text editor and have the extension .cpp. If the above is called hello.cpp, it may be compiled and run as follows in a UNIX shell window:
97
98 g++ hello.cpp -o hello -Wall -O
99 ./hello
100The -o option renames the executable file, by default a.out. -Wall turns on all warnings (recommended). -O optimizes (compiles slower but runs faster).
101In Windows, the GNU C++ compiler is called DJGPP. To compile and run from an MS-DOS box:
102
103 gxx hello.cpp -o hello.exe
104 hello
105The output file must have a .EXE extension (default is A.EXE). There is also a .OBJ file which you can delete.
106To use the network or GUI interface in UNIX, you must use the X and socket libraries, which don't work in Windows. In Windows, you must use the Windows API and a compiler that supports them, such as from Microsoft, Borland, or Symantec. GUI/network programming is nonportable and outside the scope of this document.
107
108Links to free and commercial C++ compilers can be found at cplusplus[.]com.
109
110Statements
111A program consists of a collection of functions (one of which must be int main() {...}) and type and object declarations. A function may contain declarations and statements. Statements have the following forms, where s is a statement, and t is a true/false expression.
112
113s; // Expression or declaration
114; // Empty statement
115{s; s;} // A block of 0 or more statements is a statement
116if (t) s; // If t is true then s
117if (t) s; else s; // else is optional
118while (t) s; // Loop 0 or more times
119for (s1; t; s2) s; // s1; while (t) {s; s2;}
120break; // Jump from while, for, do, switch
121return x; // Return x to calling function
122try {throw x;} // Throw exception, abort if not caught, x has any type
123 catch (T y) {s;} // if x has type T then y=x, jump to s
124 catch (...) {s;} // else jump here (optional)
125do s; while (t); // (uncommon) s; while (t) s;
126continue; // (uncommon) Start next loop of while, for, do
127switch (i) { // (uncommon) Test int expression i to const C
128 case C: s; break; // if (i==C) go here
129 default: s; // optional, else go here
130}
131label: goto label; // (rare) Jump to label within a function
132A statement may be a declaration or an expression. Objects and types declared in a block are local to that block. (Functions cannot be defined locally). It is normal (but not required) to show statements on separate lines and to indent statements enclosed in a block. If braces are optional, we indent anyway. For instance,
133
134{ // start of block
135 int a[10], i=0, j; // declaration
136 a[i+2]=3; // expression
137} // end of block, a, i, and j are destroyed
138declares the array of int a with elements a[0] through a[9] (whose values are initially undefined), i with initial value 0, and j with an undefined initial value. These names can only be used in scope, which is from the declaration to the closing brace.
139The for loop is normally used for iteration. For instance, the following both exit the loop with i set to the index of the first element of a such that a[i] is 0, or to 10 if not found.
140
141 for (i=0; i<10; i=i+1) { i=0;
142 if (a[i]==0) { while (i<10) {
143 break; if (a[i]==0)
144 } break;
145 } i=i+1;
146 }
147The braces in the for loop are optional because they each enclose a single statement. In the while loop, the outer braces are required because they enclose 2 statements. All statements are optional: for (;;) loops forever. The first statement in a for loop may declare a variable local to the loop.
148 for (int i=0; i<10; i=i+1)
149It is only possible to break from the innermost loop of a nested loop. continue in a for loop skips the rest of the block but executes the iteration (s2) and test before starting the next loop.
150
151return x; causes the current function to return to the caller, evaluating to x. It is required except in functions returning void, in which case return; returns without a value. The value returned by main() has no effect on program behavior and is normally discarded. However it is available as the $status in a UNIX csh script or ERRORLEVEL in a Windows .BAT file.
152
153 int sum(int x, int y) { // Function definition
154 return x+y;
155 }
156 int main() {
157 int a=sum(1,2); // a=3;
158 return 0; // By convention, nonzero indicates an error
159 }
160A test of several alternatives usually has the form if (pr) s; else if (pr) s; else if (pr) s; ... else s;. A switch statement is an optimization for the special case where an int expression is tested against a small range of constant values. The following are equivalent:
161
162 switch (i) { if (i==1)
163 case 1: j=1; break; j=1;
164 case 2: // fall thru else if (i==2 || i==3) // || means "or else"
165 case 3: j=23; break; j=23;
166 default: j=0; else
167 } j=0;
168throw x jumps to the first catch statement of the most recently executed try block where the parameter declaration matches the type of x, or a type that x can be converted to, or is .... At most one catch block is executed. If no matching catch block is found, the program aborts. throw; with no expression in a catch block throws the exception just caught. Exceptions are generally used when it is inconvenient to detect and handle an error in the same place.
169
170 void f() {
171 throw 3;
172 }
173
174 int main() {
175 try {
176 f(); // Jump to first catch with i = 3
177 throw "abc"; // Not reached, but would execute second catch block
178 }
179 catch(int i) {
180 }
181 catch(...) {
182 throw; // Would throw "abc" and abort (no try)
183 }
184 f(); // Abort (no try)
185 }
186Expressions
187There are 18 levels of operator precedence, listed highest to lowest. Operators at the same level are evaluated left to right unless indicted, Thus, a=b+c means a=(b+c) because + is higher than =, and a-b-c means (a-b)-c. Order of evaluation is undefined, e.g. for sin(x)+cos(x) we cannot say whether sin() or cos() is called first.
188
189The meaning of an expression depends on the types of the operands. (x,y) denotes a comma separated list of 0 or more objects, e.g. (), (x), or (1,2,3,4).
190
1911
192X::m Member m of namespace or class X
193::m Global name m when otherwise hidden by a local declaration
194
1952
196p[i] i'th element of container p (array, vector, string)
197x.m Member m of object x
198p->m Member m of object pointed to by p
199f(x,y) Call function f with 0 or more arguments
200i++ Add 1 to i, result is original value of i
201i-- Subtract 1 from i, result is original value of i
202static_cast<T>(x) Convert x to type T using defined conversions
203const_cast<T>(x) (rare) Convert x to equivalent but non-const T
204reinterpret_cast<T>(x) (rare, dangerous) Pretend x has type T
205dynamic_cast<T>(x) (rare) Convert base pointer or reference to derived if possible
206typeid(x) (rare) If x is type T, then typeid(x)==typeid(T) (in <typeinfo>)
207
2083 (right to left)
209*p Contents of pointer p, or p[0]. If p is type T*, *p is T
210&x Address of (pointer to) x. If x is type T, &x is T*
211-a Negative of numeric a
212!i Not i, true if i is false or 0
213~i Bitwise compliment of i, -1 - i
214(T)x Convert (cast) object x to type T (by static, const, or reinterpret)
215T(x,y) Convert, initializing with 0 or more arguments
216new T Create a T object on heap, return its address as T*
217new T(x,y) Create, initializing with 0 or more arguments
218new(p) T (rare) Initialize T at address p without allocating from heap
219new(p) T(x,y) (rare) Initialize T with 0 or more arguments at p
220new T[i] Create array of i objects of type T, return T* pointing to first element
221delete p Destroy object pointed to by p obtained with new T or new T()
222delete[] p Destroy array obtained with new T[]
223++i Add 1 to i, result is the new i
224--i Subtract 1 from i, result is the new i
225sizeof x Size of object x in bytes
226sizeof(T) Size of objects of type T in bytes
227
2284
229x.*p (rare) Object in x pointed to by pointer to member p
230q->*p (rare) Object in *q pointed to by pointer to member p
231
2325
233a*b Multiply numeric a and b
234a/b Divide numeric a and b, round toward 0 if both are integer
235i%j Integer remainder i-(i/j)*j
236
2376
238a+b Addition, string concatenation
239a-b Subtraction
240
2417
242x<<y Integer x shifted y bits to left, or output y to ostream x
243x>>y Integer x shifted y bits to right, or input y from istream x
244
2458
246x<y Less than
247x>y Greater than
248x<=y Less than or equal to
249x>=y Greater than or equal to
250
2519
252x==y Equals
253x!=y Not equals
254
25510
256i&j Bitwise AND of integers i and j
257
25811
259i^j Bitwise XOR of integers i and j
260
26112
262i|j Bitwise OR of integers i and j
263
26413
265i&&j i and then j (evaluate j only if i is true/nonzero)
266
26714
268i||j i or else j (evaluate j only if i is false/zero)
269
27015 (right to left)
271x=y Assign y to x, result is new value of x
272x+=y x=x+y, also -= *= /= %= &= |= ^= <<= >>=
273
27416
275i?x:y If i is true/nonzero then x else y
276
27717
278throw x Throw exception x (any type)
279
28018
281x,y Evaluate x and y (any types), result is y
282Expressions that don't require creating a new object, such as a=b, ++a, p[i], p->m, x.m, a?b:c, a,b etc. are lvalues, meaning they may appear on the left side of an assignment. Other expressions and conversions create temporary objects to hold the result, which are const (constant). An expression used as a statement discards the final result.
283 int a, b, c;
284 a+b; // Legal, add a and b, discard the sum
285 a=b=c; // Legal, assign c to b, then assign the new b to a
286 (a+=b)+=c; // Legal, add b to a, then add c to a
287 a+b=c; // Error, a+b is const
288 double(a)=b; // Error, double(a) is const
289static_cast<T>(x) converts x to type T if a conversion is defined. Usually the value of x is preserved if possible. Conversions are defined between all numeric types (including char and bool), from 0 to pointer, pointer to bool or void*, istream to bool, ostream to bool, char* to string, from a derived class to base class (including pointers or references), and from type T to type U if class U has a constructor taking T or class T has a member operator U(). A conversion will be implicit (automatically applied) whenever an otherwise invalid expression, assignment, or function argument can be made legal by applying one, except for T to U where U's constructor taking T is declared explicit, for example, the constructor for vector taking int.
290
291 double d; d=static_cast<double>(3); // Explicit 3 to 3.0
292 d=3; // Implicit conversion
293 d=sqrt(3); // Implicit 3.0, sqrt() expects double
294 vector<int> v(5); // This constructor is explicit
295 v=5; // Error, no implicit conversion
296 v=static_cast<vector<int> >(5); // OK
297const_cast<T>(x) allows an object to be modified through a const pointer or reference. It must always be explicit.
298
299 int x=3;
300 const int& r=x; r=4; // Error, r is const
301 const_cast<int&>(r)=4; // OK, x=4
302 const int* p=&x; *p=5; // Error, *p is const
303 *const_cast<int*>(p)=5; // OK, x=5
304If x were const, then this code would still be allowed but it is undefined whether x actually changes.
305reinterpret_cast<T>(x) turns off normal type checking between int and different pointer types, which are normally incompatible. The only safe conversion is to convert a pointer back to its original type. Conversion is always explicit.
306
307 int x=3, *p=&x; *p=5; // OK, x=5
308 *reinterpret_cast<double*>(p)=5; // Crash, writing 8 bytes into 4
309The expressions T(x) and (T)x apply whatever combination of static, const, and reinterpret casts are needed to convert x to type T.
310 const char* s="hello";
311 int(*s); // static_cast
312 (char*)s; // const_cast
313 (const int*)s; // reinterpret_cast
314 (int*)s; // reinterpret_cast and const_cast
315Declarations
316A declaration creates a type, object, or function and gives it a name. The syntax is a type name followed by a list of objects with possible modifiers and initializers applying to each object. A name consists of upper or lowercase letters, digits, and underscores (_) with a leading letter. (Leading underscores are allowed but may be reserved). An initializer appends the form =x where x is an expression, or (x,y) for a list of one or more expressions. For instance,
317
318 string s1, s2="xxx", s3("xxx"), s4(3,'x'), *p, a[5], next_Word();
319declares s1 to be a string with initial value "", s2, s3, and s4 to be strings with initial value "xxx", p to be a pointer to string, a to be an array of 5 strings (a[0] to a[4] with initial values ""), and next_Word to be a function that takes no parameters and returns a string.
320Built-in Types
321All built-in types are numeric. They are not automatically initialized to 0 unless global or static.
322 int a, b=0; // a's value is undefined
323 static double x; // 0.0
324Types and their usual ranges are listed below. Actual ranges could be larger in the future. The most important types are int, bool, char, and double.
325 Integer types Bits Range
326 bool 1 false (0) or true (1)
327 signed char 8 '\x80' to '\x7f' (-128 to 127)
328 unsigned char 8 '\x00' to '\XFF' (0 to 255)
329 char 8 Usually signed
330 short 16 -32768 to 32767
331 unsigned short 16 0u to 65535U
332 long 32 -2147483648l to 2147483647L
333 unsigned long 32 0ul to 4294967295LU
334 int 16-32 Usually long, could be short
335 unsigned int 16-32 Usually unsigned long, could be unsigned short
336
337 Floating point types Bits Range
338 float 32 -1.7e38f to 1.7E38F, 6 significant digits
339 double 64 -1.8e308 to 1.8E308, 14 significant digits
340 long double 64-80 At least double
341There are implicit conversions between all types. When types are mixed in an expression, both operands are converted to the type that has the higher upper bound, but at least to int. This conversion only loses representation when mixing signed and unsigned types.
342 7/4 // 1, int division rounds toward 0
343 7.0/4 // 1.75, implicit double(4) = 4.0
344 '\x05'+true // 6, implicit int('\x05') = 5, int(true) = 1
345 3U > -1 // false, implicit (unsigned int)(-1) = 232-1
346Conversion from a floating point type to an integer type drops the decimal part and rounds toward 0. If the value is outside the range of the target, then the result is undefined.
347 int(-3.8) // -3
348Conversion of one integer type to another is performed modulo the range of the target. For a B-bit number (except bool), we add or subtract 2B to bring the value within range. (In terms of a 2's complement number, we drop the most significant bits and reinterpret the sign bit without changing any bits). For bool, any nonzero value is true.
349 (unsigned char)(-1) // '\xff' (255)
350 bool(3) // true
351 short a=x12345678; // x5678 hex
352Integer Types
353int is the most common integer type, normally the underlying word size of the computer or 32 bits, representing numbers from -231 to 231-1 (-2147483648 to 2147483647). On some older systems such as real mode DOS, it may be 16 bits (-32768 to 32767). You should use int unless you need the range of some other type.
354An int value may be written in decimal (e.g. 255), hexadecimal with a leading X (e.g. xff or XFF) or octal (base 8) with a leading 0 (e.g. 0377). A trailing L denotes long (e.g. 255L or 255l), and U denotes unsigned. These may be combined (e.g. 255lu or 255UL is unsigned long). Most integer operations translate to a single machine instruction and are very fast.
355
356 + - * / % -i Add, subtract, multiply, divide, mod, unary negation
357 = Assignment
358 == != < <= > >= Comparison, returns true or false
359 ++i i++ --i i-- Pre/post increment and decrement
360 & | ^ ~i << >> Bitwise and, or, xor, not, left shift, right shift
361 += -= *= /= %= &= |= ^= <<= >>= Operate and assign, e.g. x+=y means x=x+y
362 && || !i Logical and then, or else, not
363Division rounds toward 0, e.g. 7/4 is 1, -7/4 is -1. x%y is the remainder with the sign of x, e.g. -7%4 is -3. Division or mod by 0 is a run time error and should be avoided. Operations that yield results outside the range of an int are converted modulo 232, or more generally, 2B for a B bit number. For instance, 65535*65537 is -1, not 232-1.
364Assignment returns the value assigned, e.g. x=y=0 assigns 0 to y and the new y to x. The result is an lvalue, e.g. (x=y)=0 is also legal (but useless). It assigns y to x, then 0 to x.
365
366++i and i++ both add 1 to i. However, ++i returns the new value, and i++ returns the old value. Likewise for decrement, --i and i--, which subtract 1. The pre forms, ++i, --i, are lvalues.
367
368Bitwise operators treat an int as a 2's compliment B-bit binary number (B=32) with weights -2B-1, 2B-2, 2B-3, ... 8, 4, 2, 1. The leftmost bit is negative, and serves as the sign bit. Thus, 0 is all zero bits and -1 is all 1 bits. Bitwise operators x&y x|y x^y and ~x perform B simultaneous logical operations on the bits of x and y. For instance, if y is a power of 2, then x&(y-1) has the effect x%y, but is usually faster, and the result is always positive in the range 0 to y-1.
369
370x<<y returns x shifted left by y places, shifting in zeros. The result is x*2y. x>>y returns x shifted right by y places, shifting in copies of the sign bit (or zeros if unsigned). The result is x/2y but rounding negative instead of toward 0. For instance, -100>>3 is -13. y must be in the range 0 to B-1 (0 to 31). Shifting is usually faster than * and /.
371
372Any binary arithmetic or bitwise operator may be combined with assignemt. The result is an lvalue. e.g. (x+=2)*=3; has the effect x=x+2; x=x*3;
373
374Logical operators treat 0 as false and any other value as true. They return true (1) or false (0), as do comparisons. The && and || operators do not evaluate the right operand if the result is known from the left operand.
375
376 if (i>=0 && i<n && a[i]==x) // Do bounds check on i before indexing array a
377 if (x=3) // Legal but probably wrong, assign 3 to x and test true
378char
379A char is a one byte value. Unlike other numeric types, it prints as a character, although it can be used in arithmetic expressions. Character constants are enclosed in single quotes, as 'a'. A backslash has special meaning. '\n' is a newline, '\\' is a single backslash, '\'' is a single quote, '\"' is a double quote. A backslash may be followed by 3 octal digits ('\377') or an X and 2 hex digits ('\xFF') (but not decimal). Most computers use ASCII conversion as follows:
380
381 8-13: \b\t\n\v\f\r (bell, tab, newline, vertical tab, formfeed, return)
382 32-47: !\"#$%&\'()*+,-./ (32=space, \' and \" are one char)
383 48-63: 0123456789:;<=>\? (\? is one char)
384 64-95: @ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_ (\\ is one char)
385 96-126: `abcdefghijklmnopqrstuvwxyz{|}~
386Floating Point Types
387A number with a decimal point is double (e.g. 3.7) unless a trailing F is appended (e.g. 3.7f or 3.7F), in which case it is float. Double is preferred. A double may be written in the form xey meaning x*10y, e.g. 3.7E-2 (0.037) or 1e4 (10000.0).
388A double is usually represented as a 64 bit number with a sign bit, an 11 bit exponent, and 52 bit mantissa. Therefore it can only represent numbers of the form M*2E exactly, where -252 < M < 252 and 2-10 < E < 210. This is about + or - 1.797e308 with about 14 decimal digits of precision. Therefore, numbers like 1e14 and 0.5 have exact representations, but 1e15 and 0.1 do not.
389
390 0.1 * 10 == 1 // false, they differ by about 10-14
391There are no bitwise or logical operators, %, ++, or --
392 + - * / -x Add, subtract, multiply, divide, unary negation (no %)
393 = += -= *= /= Assignment, may be combined with operators
394 == != < <= > >= Comparison, however only < and > are meaningful
395Operations may produce values outside the range of a double resulting in infinity, -infinity or NaN (not a number). These values cannot be written in C++.
396Additional mathematical functions (sqrt(), log(), pow(), etc.) can be found in <cmath>.
397
398Modifiers
399In a declaration, modifiers before the type name apply to all objects in the list. Otherwise they apply to single objects.
400
401 int* p, q; // p is a pointer, q is an int
402 const int a=0, b=0; // a and b are both const
403const
404const objects cannot be modified once created. They must be initialized in the declaration. By convention, const objects are UPPERCASE when used globally or as parameters.
405
406 const double PI=3.14159265359; // Assignment to PI not allowed
407References
408A reference creates an alias for an object that already exists. It must be initialized. A reference to a const object must also be const.
409
410 int i=3;
411 int& r=i; // r is an alias for i
412 r=4; // i=4;
413 double& pi=PI; // Error, would allow PI to be modified
414 const double& pi=PI; // OK
415Functions
416A function has a list of parameter declarations, a return type, and a block of statements. Execution must end with a return statement returning an expression that can be converted to the return type, unless void, in which case there is an implied return; at the end. Arguments passed to a function must match the parameters or allow implicit conversion (such as int to double). Functions must be defined before use, or have a matching declaration that replaces the block with a semicolon and may optionally omit parameter names. Functions are always global (not defined in other functions).
417
418 void f(double x, double); // Declaration
419 double g() { // Definition
420 return 3; // Implied conversion to double (3.0)
421 }
422 int main() { // Execution starts with funcion main
423 f(g(), 5); // Calls g, then f with implicit 5.0
424 return 0; // Return UNIX $status or Windows ERRORLEVEL
425 }
426 void f(double x, double y) { // Definition must match declaration
427 cout << x+y;
428 return; // Optional
429 }
430Command line arguments may be passed to main(int argc, char** argv) where argv is an array of argc elements of type char* ('\0' terminated) one element for each word (separated by white spaces). In UNIX, the command line is expanded before being passed (* becomes a directory listing, etc). The following program prints the command line.
431
432 // echo.cpp
433 #include <iostream>
434 using namespace std;
435 int main(int argc, char** argv) {
436 for (int i=0; i<argc; ++i)
437 cout << argv[i] << endl;
438 return 0;
439 }
440
441 g++ echo.cpp
442 ./a.out hello world
443 ./a.out
444 hello
445 world
446Function parameters have local scope. They are initialized by copying the argument, which may be an expression. Reference parameters are not copied; they become references to the arguments passed, which must be objects that the function may modify. If the reference is const, then the argument may be an expression. Const reference is the most common for passing large objects because it avoids the run time overhead of copying.
447
448 void assign_if(bool cond, string& to, const string& from) {
449 // value reference const reference
450 if (cond)
451 to=from;
452 }
453 int main() {
454 string s;
455 assign_if(true, s, "a"); // OK, s="a"
456 assign_if(false, "b", s); // Error: to refers to a const
457Functions returning a reference must return an object which can be assigned to, and that object must exist after returning (global or static, but not local). The function may be called on the left side of an assignment. Functions returning by value make a temporary copy which is const.
458
459 int a=1; // Global
460 int f() {return a;} // OK, returns copy of a
461 int& g() {return a;} // OK, g() is alias for a
462 int& h() {return a+1;} // Error, reference to const
463 int& i() {int b; return b;) // Error, b destroyed after return
464 int& j() {static int b; return b;} // OK, static has global lifespan
465 int main() {
466 f()=2; // Error, assignment to const
467 g()=f(); // OK, a=1;
468Functions with the same name may be overloaded by matching the arguments to the parameters.
469
470 int abs(int);
471 double abs(double);
472 main()
473 abs(3); // int
474 abs(3.0); // double
475 abs("3"); // Error, no match
476 abs('a'); // Error, ambiguous, could convert char to int or double
477 }
478Most operators X can be overloaded by defining a function named operator X() taking the operands as arguments. At least one argument has to be a class type.
479 string operator - (const string& s, int i); // Defines s-i
480 string operator - (const string& s); // Defines -s
481Operators . :: ?: and sizeof cannot be overloaded. Operators = [] -> cannot be overloaded except as class members. Postfix ++ -- are overloaded as binary operators with a second dummy int parameter to distingiush from the prefix form.
482 string& operator++(const string& s); // defines ++s
483 string operator++(const string& s, int) // defines s++
484Functions may have default arguments by initializing the parameters. Defaults should be specified only once. Defaulted parameters must appear after all non-default parameters.
485
486 void f(int i, int j=0, int k=0); // OK
487 void g(int i=0, int j); // Error
488 int main() {
489 f(1, 2); // f(1, 2, 0);
490 f(1); // f(1, 0, 0);
491 f(); // Error
492 return 0;
493 }
494 void f(int i, int j, int k) {} // Defaults not specified again
495A template overloads a function for all types. The declaration template <class T, class U> before a function definition allows T and U to be used in the code as types. The compiler will figure out appropriate substitutions from the arguments. A non-templated overloaded function takes precedence over a template.
496 template <class T>
497 void swap(T& a, T& b) {
498 T tmp=a;
499 a=b;
500 b=tmp;
501 }
502 void swap(string& a, string& b); // Overrides the case T=string
503 int main() {
504 int i=1, j=2;
505 string a, b;
506 swap(i, j); // OK, T is int
507 swap(a, b); // OK, calls non-templated swap
508 swap(i, a); // Error, cannot resolve T
509 swap(cout, cerr); // Error, ostream does not allow =
510inline is a hint to the compiler to optimize for speed by expanding the code where it is called, saving a call and return instruction. Unlike a macro, semantics are preserved. Only short functions should be inlined.
511
512 inline int min1(int a, int b) {return a<b?a:b;}
513 #define min2(a,b) ((a)<(b)?(a):(b))
514 int main() {
515 min1(f(), 0); // calls f() once
516 min2(f(), 0); // calls f() twice, expands to ((f())<(0)?(f()):(0))
517Pointers
518A pointer stores the address of another object, and unlike a reference, may be moved to point elsewhere. The expression &x means "address of x" and has type "pointer to x". If x has type T, then &x has type T*. If p has type T*, then *p is the object to which it points, which has type T. The * and & operators are inverses, e.g. *&x == x.
519
520Two pointers are equal if they point to the same object. All pointer types are distinct, and can only be assigned pointers of the same type or 0 (NULL). There are no run time checks against reading or writing the contents of a pointer to invalid memory. This usually causes a segmentation fault or general protection fault.
521
522 int i=3, *p=&i; // p points to i, *p == 3
523 *p=5; // i=5
524 p=new int(6); // OK, p points to an int with value 6
525 p=new char('a'); // Error, even though char converts to int
526 p=6; // Error, no conversion from int to pointer
527 p=0; // OK
528 p=i-5; // Error, compiler can't know this is 0
529 *p=7; // Segmentation fault: writing to address 0
530 int *q; *q; // Segmentation fault: q is not initialized, reading random memory
531A pointer to a const object of type T must also be const, of type const T*, meaning that the pointer may be assigned to but its contents may not.
532
533 double* p=&PI; // Error, would allow *p=4 to change PI
534 const double* p=&PI; // OK, can't assign to *p (but may assign to p)
535 double* const p=&PI; // Error, may assign to *p (but not to p)
536 const double* const p=&PI; // OK, both *p and p are const
537A function name used without parenthesis is a pointer to a function. Function pointers can be assigned values and called.
538
539 int f(double); // functions f and g take double and return int
540 int g(double);
541 int *h(double); // function h takes double and returns pointer to int
542 int (*p)(double); // p is a pointer to a function that takes double and returns int
543 int main() {
544 p=f; p(3.0); // calls f(3.0)
545 p=g; p(3.0); // calls g(3.0)
546 p=h; // Error, type mismatch
547Explicit pointer conversions are allowed but usually unsafe.
548
549 int i, *p=&i;
550 i=int(3.0); // OK, rounds 3.0
551 *(double*)p = 3.0; // Crash, writes beyond end of i
552 *(double*)&PI = 4; // Overwrites a const
553These may also be written (with the same results):
554 i=static_cast<int>(3.0); // Apply standard conversions
555 *reinterpret_cast<double*>p = 3.0; // Pretend p has type double*
556 *const_cast<double*>&PI = 4; // Same type except for const
557Arrays
558The size of an array must be specified by a constant, and may be left blank if the array is initialized from a list. Array bounds start at 0. There are no run time checks on array bounds. Multi-dimensional arrays use a separate bracket for each dimension. An array name used without brackets is a pointer to the first element.
559
560 int a[]={0,1,2,3,4}; // Array with elements a[0] to a[4]
561 int b[5]={6,7}; // Implied ={6,7,0,0,0};
562 int c[5]; // Not initialized, c[0] to c[4] could have any values
563 int d[2][3]={{1,2,3},{4,5,6}}; // Initialized 2-D array
564 int i=d[1][2]; // 6
565 d[-1][7]=0; // Not checked, program may crash
566The bare name of an array is a consst pointer to the first element. If p is a pointer to an array element, then p+i points i elements ahead, to p[i]. By definition, p[i] is *(p+i).
567 int a[5]; // a[0] through a[4]
568 int* p=a+2; // *p is a[2]
569 p[1]; // a[3]
570 p-a; // 2
571 p>a; // true because p-a > 0
572 p-1 == a+1 // true, both are &a[1]
573 *a; // a[0] or p[-2]
574 a=p; // Error, a is const (but not *a)
575A literal string enclosed in double quotes is an unnamed static array of const char with an implied '\0' as the last element. It may be used either to initialize an array of char, or in an expression as a pointer to the first char. Special chars in literals may be escaped with a backslash as before. Literal strings are concatenated without a + operator (convenient to span lines).
576
577 char s[]="abc"; // char s[4]={'a','b','c','\0'};
578 const char* p="a" "b\n"; // Points to the 'a' in the 4 element array "ab\n\0"
579 const char* answers[2]={"no","yes"}; // Array of pointers to char
580 cout << answers[1]; // prints yes (type const char*)
581 cout << answers[1][0]; // prints y (type const char)
582 "abc"[1] // 'b'
583Arrays do not support copying, assignment, or comparison.
584 int a[5], b[5]=a; // Error: can't initialize b this way
585 b=a; // Error: can't assign arrays
586 b==a; // false, comparing pointers, not contents
587 "abc"=="abc" // false, comparing pointers to 2 different locations
588The size of an array created with new[] may be an expression. The elements cannot be initialized with a list. There is no run time check against accessing deleted elements.
589 int n, *p;
590 cin >> n;
591 p=new int[n]; // Elements p[0] to p[n-1] with values initially undefined
592 delete[] p; // Use delete with new or new(), delete[] with new[]
593 p[0] = 1; // May crash
594static
595Normally, objects are placed on the stack. Memory is allocated by growing the stack at the top; thus objects are destroyed in the reverse order in which they are created. An object's life span is the same as its scope. If an object comes into scope more than once, then it is reinitialized each time, and destroyed when leaving its scope.
596 +----------+
597 | |
598 | Heap | Allocated with new until deleted or program exits.
599 | |
600 +^^^^^^^^^^+
601 | Stack | Local objects, parameters, temporaries, function return addresses.
602 +----------+ +---------+
603 | Data | <-- | Data | Initial values for static and global objects.
604 +----------+ +---------+
605 | Code | <-- | Code | Executable machine instructions.
606 +----------+ +---------+ (Cannot be read or written by program.)
607 | Reserved | a.out on disk
608 | for OS |
609 | and other| Cannot be read or written by program, will cause segmentation
610 | programs | fault or general protection fault.
611 +----------+
612 Memory
613static objects are placed in the data segment. They are initialized from values stored in the executable file, and therefore these values must be known at compile time. Initialization occurs only once. Values are maintained when the object is out of scope (e.g. between function calls), and it is safe to return a pointer or reference to them. Numeric values not explicitly initialized are set to 0.
614 int& f() { // Return by reference, f() is an alias for s, not a temporary copy
615 static int s=1; // Initialized only once
616 ++s;
617 return s; // Safe to return by reference
618 }
619 int main() {
620 cout << f(); // 2
621 cout << f(); // 3
622 f()=5; // OK, s=5;
623 s=6; // Error, s is not in scope
624register
625(Rare) A hint to the compiler to optimize an int or pointer for speed. It is no longer used because most optimizers can do a better job.
626 register int x;
627volatile
628(Rare) Indicates that an object might be modified from outside the program (e.g. a hardware input port) and that the optimizer should not make copies of it. Its use is machine dependent.
629 const volatile unsigned short& port=*(const short*)0xfffe; // 16 bit port at address xfffe
630Standard Library Types
631Standard library types (string, vector, map...) and objects (cin, cout...) require a #include <header> and must be extracted from namespace std, either with a using namespace std; statement or by using the fully qualified names preceeded with std::, as in std::cout.
632
633 #include <iostream> #include <iostream>
634 int main() { using namespace std;
635 std::cout << "Hello\n"; int main() {
636 return 0; cout << "Hello\n";
637 } return 0;
638 }
639<iostream>
640The header <iostream> defines global object cin of type istream, and global objects cout, cerr, clog of type ostream. cin represents standard input, normally the keyboard, unless redirected to a file or piped on the command line. cout represents standard output, which is normally the screen unless redirected or piped. Writing to cerr or clog both write to the screen even if output is redirected. The difference is that writing a newline ('\n') flushes any buffered output to cerr but not to cout or clog.
641
642In the following, in is an istream (cin), out is an ostream (cout, cerr, clog), i is int, c is char, and cp is char*.
643
644 in >> x; // Read 1 word to numeric, string, or char* x, return in
645 in.get(); // Read 1 char (0-255) or EOF (-1) as an int
646 in.get(c); // Read 1 char into c, return in
647 in.unget(); // Put back last char read, return in
648 in.getline(cp, i); // Read up to i chars into char cp[i] or until '\n', return in
649 in.getline(cp, i, c); // Read to c instead of '\n', return in
650 getline(in, s); // Read up to '\n' into string s, return in
651 in.good(); // true if no error or EOF
652 bool(in); // in.good();
653 in.bad(); // true if unexpected char in formatted input
654 in.clear(); // Allow more input after bad, or throw an ios::failure
655 in.eof(); // true if end of file
656 in.fail(); // true if system input error
657
658 out << x; // Formatted output, redirected with >
659 out << endl; // Print '\n' and flush
660Input with >> reads a contiguous sequence of non-whitespace characters. If x is numeric and the next word contains invalid characters (such as "1.5" or "foo" for an int), then the first offending character remains unread, is.bad() is set, and no further input can occur until is.clear() is called. Input into a char* array is not bounds checked. Input returns the istream to allow chaining, and has a conversion to bool to test for success. Output also returns the ostream to allow chaining.
661
662 // Read and print pairs of strings and ints until something goes wrong
663 // Input: hi 3 there 5 this is 1 test
664 // Output: hi 3
665 there 5
666
667 string s; int i;
668 while (cin >> s >> i)
669 cout << s << " " << i << endl;
670 cin.clear();
671The get() methods read one character including whitespace. The various getline() functions read up through the next newline character and discard the newline. The methods good(), bad(), eof(), fail(), clear(), and implicit convertion to bool are available as in istream, but seldom used.
672
673<iomanip>
674Defines manipulators for formatted output of numeric types. They have no effect on strings. setw() applies only to the next object printed, but the others remain in effect until changed.
675
676 out << setw(i); // Pad next output to i chars, then back to 0
677 out << setfill(c); // Pad with c (default ' ')
678 out << setprecision(i); // Use i significant digits for all float, double
679
680 cout << setw(6) << setprecision(3) << setfill('0') << 3.1; // print "003.10"
681<fstream>
682Defines types ifstream and ofstream representing input and output files respectively. ifstream is derived from istream, inheriting all its operations (such as >>). In addition,
683 ifstream in(cp); // Open file named cp for reading
684 ifstream in(cp, ios::in | ios::binary); // Open in binary mode
685 bool(in); // true if open successful
686cp is the file name. It must be a char*, not string (use s.c_str() to convert string s). Input is normally in text mode. In Windows, carriage returns ('\r') are discarded, and an ASCII 26 ('\032') signals end of file. In binary mode and in UNIX, no such translation occurs. The file is closed when the ifstream is destroyed.
687
688 {
689 ifstream f("input.dat", ios::in | ios::binary);
690 if (!f)
691 cerr << "File not found\n";
692 else {
693 int i=f.get(); // First byte or EOF if empty
694 }
695 } // f closed here
696ofstream is derived from ostream, inheriting all its operations (such as <<). In addition,
697
698 ofstream os(cp); // Open file named cp for writing
699 ofstream os(cp, ios::out | ios::binary); // Open in binary mode
700In text mode in Windows, writing '\n' actually writes "\r\n". The file named cp is overwritten if it exists, or created otherwise. The file is flushed and closed when the ofstream is destroyed.
701
702<string>
703A string is like an array of char, but it also supports copying, assignment, and comparison, and its size may be set at run time. '\0' has no special meaning. There is implicit conversion from char* to string in mixed type expressions.
704 string() // Empty string
705 string(cp) // Convert char* cp to string
706 string(n, c) // string of n copies of char c
707 s=s2 // Assign char* or string s2 to string s
708 s1<s2 // Also ==, !=, >, <=, >=, either s1 or s2 may be char*
709 s.size() // Length of string s
710 string::size_type // Type of s.size(), usually unsigned int
711 s.empty() // True if s.size() == 0
712 s[i] // i'th char, 0 <= i < s.size() (unchecked), may be assigned to
713 s1+s2 // Concatenate strings, either s1 or s2 may be char or char*
714 s+=s2 // Append string, char, or char* s2 to string s
715 s.c_str() // string s as a const char* with trailing '\0'
716 s.substr(i, j) // Substring of string s of length j starting at s[i]
717 s.substr(i) // Substring from s[i] to the end
718 s.find(s2) // Index of char, char*, or string s2 in s, or string::npos if not found
719 s.rfind(s2) // Index of last occurrence of s2 in s
720 s.find_first_of(s2) // Index of first char in s that occurs in s2
721 s.find_last_of(s2) // Index of last char in s that occurs in s2
722 s.find_first_not_of(s2) // Index of first char in s not found in s2
723 s.find_last_not_of(s2) // Index of last char in s not found in s2
724 s.replace(i, j, s2) // Replace s.substr(i, j) with s2
725s.size() should be converted to int to avoid unsigned comparison.
726 string s(3,'a'); // "aaa"
727 s += "b"+s; // "aaabaaa"
728 for (int i=0; i!=int(s.size()); ++i) { // print s one char at a time
729 cout << s[i];
730 s.size() > -1; // false! -1 is converted to unsigned
731string supports standard container operations with regard to iterators. string iterators are random, supporting all the pointer operators of char*. The notation [b,e) means the sequence such that pointer or iterator b points to the first element and e points one past the last element.
732 s.begin() // Iterator pointing to s[0]
733 s.end() // Iterator pointing 1 past last char
734 string::iterator // Iterator type, like char*
735 string::const_iterator // Type if s is const, like const char*
736 string(b, e) // string initialized from sequence [b,e)
737 s.erase(b) // Remove char in s pointed to by b
738 s.erase(b, e) // Remove substring [b,e) from s
739 s.replace(b, e, s2); // Replace substring [b,e) with string s2
740Conversion from iterator to const_iterator is allowed, but not the other way. const_iterator should be used if the string is not going to be modified.
741 char* cp="ABCDE";
742 string s(cp, cp+5); // "ABCDE"
743 string s2(s.begin()+1, s.end()-1); // "BCD"
744 for (string::const_iterator p=s.begin(); p!=s.end(); ++p) // Print s one char at a time
745 cout << *p; // or p[0]
746As with arrays and pointers, indexing and iterator dereferencing are not checked at run time. Creating a string with a negative or very large size is also trouble.
747 string s(-1, 'x'); // Crash, negative size
748 string s2(s.end(), s.begin()); // Crash, negative size
749 s[-1]='x'; // Crash, out of bounds
750 *s.end()='x'; // Crash, out of bounds
751 string::iterator p; *p='x'; // Crash, dereferencing unitialized iterator
752<vector>
753A vector<T> is like an array of T, but supports copying, assignment, and comparison. Its size can be set and changed at run time, and it can efficiently implement a stack (O(1) time to push or pop). It has random iterators like string, which behave like type T* (or const T* if the vector is const). If T is numeric, elements are initialized to 0. It is not possible to have an initialization list such as {1,2,3}.
754 vector<T>() // Empty vector, elements of type T
755 vector<T>(n) // n elements, default initialized
756 vector<T>(n, x) // n elements each initialized to x
757 vector<T> v2=v; // Copy v to v2
758 v2=v; // Assignment
759 v2<v // Also >, ==, !=, <=, >= if defined for T
760 vector<T>(b, e) // Initialize to sequence [b, e)
761 v.size() // n
762 vector<T>::size_type // Type of v.size(), usually unsigned int
763 v.empty() // true if v.size() == 0
764 v[i] // i'th element, 0 <= i < v.size() (unchecked), may be assigned to
765 v.begin(), v.end() // Iterators [b, e)
766 vector<T>::iterator // Iterator type, also const_iterator
767 v.back() // v[v.size()-1] (unchecked if empty)
768 v.push_back(x) // Increase size by 1, copy x to last element
769 v.pop_back() // Decrease size by 1 (unchecked if empty)
770 v.front() // v[0] (unchecked)
771 v.resize(n) // Change size to n >= 0 (unchecked)
772 v.insert(d, x) // Insert x in front of iterator d, shift, increase size by 1
773 v.insert(d, n, x) // Insert n copies of x in front of d
774 v.insert(d, b, e) // Insert copy of [b, e) in front of d
775 v.erase(d) // Remove *d, shift, decrease size by 1
776 v.erase(d, e) // Remove subsequence [d, e)
777 v.clear() // v.erase(v.begin(), v.end())
778 v.reserve(n) // Anticipate that v will grow to size n >= v.size()
779 v.capacity() // Reserved size
780For insert and erase, d and e must point into v (and d <= e) or the program may crash. Elements from *d to the end are shifted and the size is changed as needed. Saved copies of iterators may become invalid after any change of size or capacity (not checked).
781To implement push_back() efficiently, a vector typically doubles the reserved space when it runs out in order to minimize memory reallocation and copying. reserve() allows this strategy to be optimized.
782
783 // Read words from input into a stack, print in reverse order
784 string s;
785 vector<string> v;
786 while (cin >> s)
787 v.push_back(s);
788 while (!v.empty()) {
789 cout << v.back() << endl;
790 v.pop_back();
791 }
792<deque>
793A deque (double ended queue) is just like a vector, but optimized for adding and removing elements at either end in O(1) time. It lacks reserve() and capacity() and adds
794 v.push_front(x) // v.insert(v.begin(), x)
795 v.pop_front() // v.erase(v.begin())
796<list>
797A list is like a deque but optimized for insert and erase at any point at the cost of random access. It lacks [] (indexing), and its iterators are bidirectional, not supporting [], +, -, <, >, <=, or >=. list adds
798 v.splice(d, v2, b); // Move *b from list v2 to in front of d in v
799 v.splice(d, v2); // Move all elements of list v2 to in front of d in v
800 v.splice(d, v2, b, e); // Move [b,e) in v2 to in front of d at v
801 v.remove(x); // Remove all elements equal to x
802 v.remove_if(f); // Remove elements x where f(x) is true
803 v.sort(); // Sort list
804 v.sort(f); // Sort list using function bool f(x,y) instead of x <
805 v.merge(v2); // Merge sorted list v2 into sorted list v
806 v.merge(v2, f); // Merge using f(x,y) instead of x < y to sort v
807 v.unique(); // Remove duplicates from sorted list
808 v.unique(f); // Use f(x,y) instead of x == y
809 v.reverse(); // Reverse order of elements
810Iterators can only be moved one element at a time using ++ or --, and compared using == or !=.
811 char* cp="ABCDE";
812 list<char> v(cp, cp+5); // v.size() is 5
813 for (list<char>::const_iterator p=v.begin(); p!=v.end(); ++p) // Print ABCDE
814 cout << *p;
815<map>
816A map<K,V> m is a set of key-value pairs with unique, sorted keys of type K and values of type V. m[k] efficiently (O(log n) time) returns the value associated with k (as an lvalue), or creates a default value (0 if V is numeric) if k is used for the first time. A map iterator points to a pair<const K, V>, which has members first of type K and second of type V.
817 pair<K,V> x(k,v); // Create a pair x containing copies of k and v
818 x.first // k
819 x.second // v
820 x=make_pair(k,v) // x.first=k; x.second=v;
821
822 map<K,V> m; // map sorted by < on K
823 map<K,V,f>() // map sorted by f(x,y) instead of x<y on K
824 m[k]=v; // Associate v (type V) with unique key k of type K
825 m[k] // Retrieve v, or associate V() with k if new
826 m.size() // Number of unique keys
827 m.empty() // true if m.size() == 0
828 map<K,V>::iterator // bidirectional, points to a pair<const K, V>
829 map<K,V>::const_iterator // points to a pair<const K, const V>
830 m.begin() // Points to first pair (lowest k)
831 m.end() // Points 1 past last pair
832 m.find(k) // Points to pair containing k or m.end() if not found
833 m.erase(k) // Remove key K and its associated value
834 m.erase(b) // Remove pair pointed to by iterator b
835 m.erase(b, e) // Remove sequence [b, e)
836 m.clear() // Make empty: m.erase(m.begin(), m.end())
837 m==m2 // Compare maps, also !=, <, <=, >, >=
838We use m.find(k) rather than m[k] when we wish to look up k without increasing the size of m if k is not found.
839 // Read words, print an alphabetical index of words with their counts
840 string s;
841 map<string, int> m;
842 while (cin >> s)
843 ++m[s];
844 for (map<string, int>::const_iterator p=m.begin(); p!=m.end(); ++p)
845 cout << p->first << " " << p->second << endl;
846A multimap is a map that allows duplicate keys. It support all map operations except []. Elements are added by inserting a pair<K,V> and retrieved by m.equal_range(k) which returns a pair of iterators defining the sequence of pairs matching k.
847 multimap<K,V,f> m; // f defaults to < on K
848 m.insert(make_pair(k,v)) // Insert a pair
849 pair<multimap<K,V,f>::iterator, multimap<K,V,f>::iterator> p
850 = m.equal_range(k) // Sequence with key k is [p->first, p->second)
851A set<K> and multiset<K> are like a map and multimap, but without values. Iterators point to a K rather than a pair. There is no [] operator.
852 set<K> m; // Elements are sorted by < on K
853 m.insert(k) // Add an element
854 m.erase(k) // Remove an element
855 m.find(k)!=m.end() // Test if k is in m
856<queue>
857A queue is a container in which elements are inserted at the back and removed from the front. This could also be done with a deque or list, so no new capabilities are provided. A queue does not support iterators or indexing.
858 queue<T> q; // Queue of type T
859 q.size() // Number of items in q
860 q.empty() // true if q.size() == 0
861 q.push(x) // Put x in the back
862 x=q.back() // The item last pushed, may be assigned to
863 x=q.front() // The next item to pop, may be assigned to
864 q.pop() // Remove the front item
865A priority_queue is more useful. It sorts the items as they are pushed so that the largest is on top and removed first.
866 priority_queue<T> q; // Element type is T
867 priority_queue<T, lt> q; // Use lt(x,y) instead of x < y to sort
868 q.size(), q.empty() // As before
869 q.push(x) // Insert x
870 x=q.top() // Largest item in q, cannot be assigned to
871 q.pop() // Remove top item
872<stack>
873Items are popped from the top of a stack in the reverse order in which they were pushed. It does not provide any new functionality beyond a vector, deque, or list, and does not support iterators or indexing.
874 stack<T> s; // Stack with elements of type T
875 s.size(), s.empty() // As with queue
876 s.push(x); // Put x on top
877 x=s.top(); // Last item pushed, may be assigned to
878 s.pop(); // Remove the top item
879<bitset>
880A bitset<N> is like a vector<bool> with fixed size N, but without iterators, and supporting logical operators like an N-bit int. Its elements have the values 0 or 1. It is implemented efficiently, with 8 elements per byte.
881 bitset<N> b; // N-bit bitset, N must be a compile time constant
882 bitset<N> b=x; // Initialize b[0]..b[31] from bits of long x
883 b[i] // i'th bit, 0 <= i < N or throw out_of_range()
884 b.size() // N, cannot be changed
885 b.set(i) // b[i] = 1
886 b.reset(i) // b[i] = 0
887 b.flip(i) // b[i] = 1 - b[i]
888 b.test(i) // true if b[i] == 1
889 b.set() // Set all bits, also b.reset(), b.flip()
890 b & b2 // Bitwise AND, also | ^ ~ << >> &= |= ^= <<= >>= == !=
891 b.count() // Number of bits set to 1
892 b.any() // true if b.count() > 0
893 b.none() // true if b.count() == 0
894 cin >> b // Read bits as '0' and '1' e.g. "10101"
895 cout << b // Write bits as '0' and '1'
896 bitset<N> b(s); // Initialize from string s of '0' and '1' or throw invalid_argument()
897 s=b.template to_string<char>() // Convert to string
898 x=b.to_ulong() // Convert to unsigned long, throw overflow_error() if bits > 31 set
899<valarray>
900A valarray is like a fixed sized array or vector that supports arithmetic operations on all the elements at once. For instance, if x and y are valarrays of the same size, then x+y is a valarray containing the sums of the corresponding elements. Likewise, y=sqrt(x) assigns y[i]=sqrt(x[i]) to each element of y. In mixed type expressions, a scalar (element of type T) is promoted to a valarray of the same size by duplicating it, e.g. x+1 adds 1 to all elements of x.
901 valarray<T> v(n); // n elements of type T, initially T() or 0
902 valarray<T> v(x, n); // n copies of x (note arguments are backwards)
903 valarray<T> v(a, n); // Initialize from array a[0]..a[n-1]
904 valarray<T> v; // size is 0
905 v.size() // Number of elements, n
906 v[i] // i'th element, 0 <= i < n, not checked
907 v+=x, v+=v // Add x or v[i] to all v[i], also = -= *= /= %= ^= &= |= <<= >>=
908 v+v, v+x, x+v // Also - * / % ^ & | << >> and unary + - ~ !
909 sqrt(v) // Also all functions in cmath
910 x=v.sum() // Sum of all elements
911 v.shift(n) // Move all v[i] to v[i+n], shift in 0
912 v.cshift(n) // Move v[i] to v[(i+n) % v.size()]
913 v.resize(n) // Change size to n, but reset all elements to 0
914 v.resize(n, x) // Change size to n, set all elements to x
915<complex>
916A complex supports complex arithmetic. It has real and imaginary parts of type T. Mixed type expressions promote real to complex (e.g. double to complex<double> and lower precision to higher precision (e.g. complex<int> to complex<double>).
917 complex<T> x; // (0,0), T is a numeric type
918 complex<T> x=r; // (r,0), convert real r to complex
919 complex<T> x(r, i); // (r,i)
920 complex<T> x(rho, theta); // Polar notation: radius, angle in radians
921 x.real() // r
922 x.imag() // i
923 abs(x) // rho = sqrt(r*r+i*i)
924 arg(x) // tan(theta) = i/r
925 norm(x) // abs(x)*abs(x)
926 conj(x) // (r,-i)
927 x+y // Also - * / == != = += -= *= /= and unary + -
928 sin(x) // Also sinh, sqrt, tan, tanh, cos, cosh, exp, log, log10, pow(x,y)
929 cout << x // Prints in format "(r,i)"
930 cin >> x // Expects "r", "(r)", or "(r,i)"
931<stdexcept>, <exception>
932The standard library provides a hierarchy of exception types. Not all of them are used by the library, but any may be thrown.
933
934 Type Header Thrown by
935 exception stdexcept, exception
936 logic_error stdexcept
937 length_error stdexcept
938 domain_error stdexcept
939 out_of_range stdexcept, bitset bitset[] (index out of bounds)
940 invalid_argument stdexcept, bitset bitset("xxx") (not '0' or '1')
941 runtime_error stdexcept
942 range_error stdexcept
943 overflow_error stdexcept
944 underflow_error stdexcept
945 bad_alloc new new, new[] (out of memory)
946 bad_cast typeinfo dynamic_cast<T&> (can't convert to derived)
947 bad_typeid typeinfo typeid(*p) when p==0
948 bad_exception exception
949 ios_base::failure ios, iostream, fstream istream::clear(), ostream::clear()
950Catching a base class catches all derived classes, thus catch(exception e) catches all of the above types. However, C++ allows throwing exceptions not derived from exception, so this may not catch everything. All exceptions provide the following interface:
951 throw exception(msg) // Throw exception with char* or string msg
952 throw exception(); // Default msg
953 catch(exception e) {e.what();} // msg as a char*
954New exceptions may be derived from existing types to maintain this interface (see inheritance).
955
956 class MyError: public exception {
957 public:
958 MyError(const string& msg=""): exception(msg) {}
959 }
960C++ Standard Library Functions
961Many C++ standard library functions operate on sequences denoted by iterators or pointers. Iterators are a family of types that include pointers. They are classified by the operators they support.
962
963input: ++p, p++, p=q, p==q, p!=q, *p (read-only)
964output: p=q, p==q, p!=q, *p++ = x (alternating write/increment)
965forward: input and output and p->m, *p (multiple read-write)
966bidirectional: forward and --p, p--, implemented by list, map, multimap, set, multiset.
967random: bidirectional and p<q, p>q, p<=q, p>=q, p+i, i+p, p-i, p-q, p[i], implemented by arrays (as pointers), string, vector, deque.
968Some algorithms require certain iterator types, but will accept more powerful types. For example, copy(b, e, d) require b and e to be at least input iterators and d to be at least an output iterator. But it will accept forward, bidirectional, or random iterators because these all support input and output operations. sort() requires random iterators and will accept no other type.
969
970The notation [b,e) denotes the sequence of e-b objects from b[0] to e[-1], i.e. b points to the beginning of the sequence and e points one past the end. For most containers, v, the sequence is [v.begin(), v.end()). For an array of n elements, the sequence is [a, a+n).
971
972<algorithm>
973In the following, b and e are input iterators, and d is an output iterator, unless otherwise specified. Parameters eq and lt are optional, and default to functions that take 2 arguments x and y and return x==y and x<y respectively, e.g. bool eq(x,y) {return x==y;}. x and y are objects of the type pointed to by the iterators. p is a pair of iterators. f is a function or function object as noted.
974
975 // Operations on ordinary objects
976 swap(x1, x2); // Swap values of 2 objects of the same type
977 min(x1, x2); // Smaller of x1 or x2, must be same type
978 max(x1, x2); // Larger of x1 or x2, must be same type
979
980 // Properties of sequences (input iterators)
981 equal(b, e, b2, eq); // true if [b,e)==[b2,...)
982 lexicographical_compare(b, e, b2, e2, lt); // true if [b,e)<[b2,e2)
983 i=min_element(b, e); // Points to smallest in [b,e)
984 i=max_element(b, e); // Points to largest
985 n=count(b, e, x); // Number of occurrences of x in [b,e)
986 n=count_if(b, e, f); // Number of f(x) true in [b,e)
987
988 // Searching, i points to found item or end (e) if not found
989 i=find(b, e, x); // Find first x in [b,e)
990 i=find_if(b, e, f); // Find first x where f(x) is true
991 i=search(b, e, b2, e2, eq);// Find first [b2,e2) in [b,e) (forward)
992 i=find_end(b, e, b2, e2, eq); // Find last [b2,e2) in [b,e) (forward)
993 i=search_n(b, e, n, x, eq);// Find n copies of x in [b,e) (forward)
994 p=mismatch(b, e, b2, eq); // Find first *p.first in [b,e) != *p.second in [b2,.) (forward)
995 i=adjacent_find(b, e, eq); // Find first of 2 equal elements (forward)
996
997 // Modifying elements
998 i=copy(b, e, d); // Copy [b,e) to [d,i)
999 fill(d, i, x); // Set all in [d,i) to x (forward)
1000 i=fill_n(d, n, x); // Set n elements in [d,i) to x
1001 generate(d, i, f); // Set [d,i) to f() (e.g. rand) (forward)
1002 i=generate_n(d, n, f); // Set n elements in [d,i) to f()
1003 f=for_each(b, e, f); // Call f(x) for each x in [b,e)
1004 i=transform(b, e, d, f); // For x in [b,e), put f(x) in [d,i)
1005 i=transform(b, e, b2, d, f); // For x in [b,e), y in [b2,.), put f(x,y) in [d,i)
1006 replace(b, e, x, y) // Replace x with y in [b,e)
1007 replace_if(b, e, f, y); // Replace with y in [b,e) where f(x) is true
1008 i=replace_copy(b, e, d, x, y); // Copy [b,e) to [d,i) replacing x with y
1009 i=replace_copy_if(b, e, d, f, y); // Copy replacing with y where f(x) is true
1010
1011 // Rearranging sequence elements
1012 sort(b, e, lt); // Sort [b,e) by < (random)
1013 stable_sort(b, e, lt); // Sort slower, maintaining order of equal elements (random)
1014 partial_sort(b, m, e, lt); // Sort faster but leave [m,e) unsorted (random)
1015 nth_element(b, m, e, lt); // Sort fastest but only *m in proper place (random)
1016 iter_swap(b, e); // swap(*b, *e) (forward)
1017 i=swap_ranges(b, e, b2); // swap [b,e) with [b2,i) (forward)
1018 i=partition(b, e, f); // Moves f(x) true to front, [i,e) is f(x) false (bidirectional)
1019 i=stable_partition(b, e, f); // Maintains order within each partition
1020 i=remove(b, e, x); // Move all x to end in [i,e) (forward)
1021 i=remove_if(b, e, f); // Move f(x) true to front in [b,i) (forward)
1022 i=remove_copy(b, e, d, x); // Copy elements matching x to [d,i)
1023 i=remove_copy_if(b, e, d, f); // Copy elements x if f(x) is false to [d,i)
1024 replace(b, e, x1, x2); // Replace x1 with x2 in [b,e)
1025 i=replace_copy(b, e, d, x1, x2); // Copy [b,e) to [d,i) replacing x1 with x2
1026 reverse(b, e); // Reverse element order in [b,e) (bidirectional)
1027 i=reverse_copy(b, e, d); // Copy [b,e) to [d,i) reversing the order (b,e bidirectional)
1028 rotate(b, m, e); // Move [b,m) behind [m,e) (forward)
1029 i=rotate_copy(b, m, e, d); // Rotate into [d,i)
1030 random_shuffle(b, e, f); // Random permutation, f() defaults to rand()
1031 next_permutation(b, e, lt);// Next greater sequence, true if successful (bidirectional)
1032 prev_permutation(b, e, lt);// Previous permutation, true if successful (bidirectional)
1033
1034 // Operations on sorted sequences
1035 i=unique(b, e, eq); // Move unique list to [b,i), extras at end
1036 i=unique_copy(b, e, d, eq); // Copy one of each in [b,d) to [d,i)
1037 i=binary_search(b, e, x, lt); // Find i in [b,e) (forward)
1038 i=lower_bound(b, e, x, lt); // Find first x in [b,e) or where to insert it (forward)
1039 i=upper_bound(b, e, x, lt); // Find 1 past last x in [b,e) or where to insert it (forward)
1040 p=equal_range(b, e, x, lt); // p.first = lower bound, p.second = upper bound (forward)
1041 includes(b, e, b2, e2, lt); // true if [b,e) is a subset of [b2,e2)
1042 i=merge(b, e, b2, e2, d, lt); // Merge [b,e) and [b2,e2) to [d,i)
1043 inplace_merge(b, m, e, lt); // Merge [b,m) and [m,e) to [b,e) (bidirectional)
1044 i=set_union(b, e, b2, e2, d, lt); // [d,i) = unique elements in either [b,e) or [b2,e2)
1045 i=set_intersection(b, e, b2, e2, d, lt); // [d,i) = unique elements in both
1046 i=set_difference(b, e, b2, e2, d, lt); // [d,i) = unique elements in [b,e) but not [b2,e2)
1047 i=set_symmetric_difference(b, e, b2, e2, d, lt); // [d,i) = elements in one but not both
1048Algorithms never change the size of a container. When copying, the destination must be large enough to hold the result.
1049 int a[5]={3,1,4,1,6};
1050 vector b(5);
1051 copy(a, a+5, v.begin()); // Copy a to v
1052 remove(a, a+5, 1); // {3,4,6,1,1}, returns a+3
1053 sort(a, a+4); // {1,3,4,6,1}
1054<numeric>
1055In the following, plus, minus, and times are optional functions taking 2 arguments x and y that return x+y, x-y, and x*y respectively, e.g. int plus(int x, int y) {return x+y;}
1056 x=accumulate(b, e, x, plus); // x + sum over [b,e)
1057 x=inner_product(b, e, b2, x, plus, times); // x + sum [b,e)*[b2,e2)
1058 adjacent_difference(b, e, minus); // for i in (b,e) *i -= i[-1]
1059 partial_sum(b, e, plus); // for i in [b,e) *i += sum [b,i)
1060<iterator>
1061An inserter is an output iterator that expands the container it points to by calling push_back(), push_front(), or insert(). The container must support this operation. A stream iterator can be used to do formatted input or output using >> or <<
1062
1063 back_inserter(c); // An iterator that appends to container c
1064 front_inserter(c); // Inserts at front of of c
1065 inserter(c, p); // Inserts in front of p
1066 ostream_iterator<T>(out, cp); // Writes to ostream separated by char* cp (default " ")
1067 istream_iterator<T>(in); // An input iterator that reads T objects from istream
1068The most common use is to copy to an empty vector, deque, or list.
1069 vector<int> from(10), to;
1070 copy(from.begin(), from.end(), back_inserter(to));
1071<functional>
1072Functions in <functional> create function objects, which are objects that behave like functions by overloading operator(). These can be passed to algorithms that take function arguments, e.g.
1073
1074 vector<int> v(10);
1075 sort(v.begin(), v.end(), greater<int>()); // Sort v in reverse order
1076 int x=accumulate(v.begin(), v.end(), 1, multiplies<T>); // Product of elements
1077The following create function objects that take one or two parameters x and y of type T and return the indicated expression, i.e, equal_to<int>()(3,4) returns false.
1078 // Predicates (return bool)
1079 equal_to<T>() // x==y
1080 not_equal_to<T>() // x!=y
1081 greater<T>() // x>y
1082 less<T>() // x<y
1083 greater_equal<T>() // x>=y
1084 less_equal<T>() // x<=y
1085 logical_and<bool>() // x&&y
1086 logical_or<bool>() // x||y
1087 logical_not<bool>() // !x (unary)
1088
1089 // Arithmetic operations (return T)
1090 plus<T>() // x+y
1091 minus<T>() // x-y
1092 multiplies<T>() // x*y
1093 divides<T>() // x/y
1094 modulus<T>() // x%y
1095 negate<T>() // -x (unary)
1096A binder converts a 2-argument function object into a 1-argument object by binding a fixed value c to the other argument, e.g. bind2nd(less<int>(), 10) returns a function object that takes one argument x and returns true if x<10.
1097 bind1st(f, c) // An object computing f(c,y)
1098 bind2nd(f, c) // An object computing f(x,c)
1099
1100 i=find_if(v.begin(), v.end(), bind2nd(equal_to<int>(), 0)); // Find first 0
1101The following convert ordinary functions and member functions into function objects. All functions must be converted to be passed to bind1st and bind2nd. Member functions must also be converted to be passed to algorithms.
1102 ptr_fun(f) // Convert ordinary function f to object
1103 mem_fun(&T::f) // Convert member function of class T
1104 mem_fun_ref(T::f) // Same
1105
1106 i=find_if(v.begin(), v.end(), mem_fun(&string::empty)); // Find ""
1107 transform(v.begin(), v.end(), v.begin(), bind2nd(ptr_fun(pow), 2.0)); // Square elements
1108not1() and not2() negate a unary or binary function object.
1109 not1(f) // Object computing !f(x)
1110 not2(f) // Object computing !f(x,y)
1111
1112 i=find_if(v.begin(), v.end(), not1(bind2nd(equal_to<int>(), 0))); // Find nonzero
1113<new>
1114The default behavior of new is to throw an exception of type bad_accoc if out of memory. This can be changed by writing a function (taking no parameters and returning void) and passing it to set_new_handler().
1115
1116 void handler() {throw bad_alloc();} // The default
1117 set_new_handler(handler);
1118new(nothrow) may be used in place of new. If out of memory, it returns 0 rather than throw bad_alloc.
1119 int* p = new(nothrow) int[1000000000]; // p may be 0
1120C Library Functions
1121The C library is provided for backwards compatibility with the C language. Because C lacked namespaces, all types and functions were defined globally. For each C header, C++ provides an additional header by prefixing "c" and dropping the ".h" suffix, which places everything in namespace std. For instance, <stdio.h> becomes <cstdio>.
1122<cstdlib>
1123Miscellanious functions. s is type char*, n is int
1124
1125 atoi(s); atol(s); atof(s);// Convert char* s to int, long, double e.g. atof("3.5")
1126 abs(x); labs(x); // Absolute value of numeric x as int, long
1127 rand(); // Pseudo-random int from 0 to RAND_MAX (at least 32767)
1128 srand(n); // Initialize rand(), e.g. srand(time(0));
1129 system(s); // Execute OS command s, e.g. system("ls");
1130 getenv(s); // Environment variable or 0 as char*, e.g. getenv("PATH");
1131 exit(n); // Kill program, return status n, e.g. exit(0);
1132 void* p = malloc(n); // Allocate n bytes or 0 if out of memory. Obsolete, use new.
1133 p = calloc(n); // Allocate and set to 0 or return NULL. Obsolete.
1134 p = realloc(p, n); // Enlarge to n bytes or return NULL. Obsolete.
1135 free(p); // Free memory. Obsolete: use delete
1136<cctype>
1137Character tests take a char c and return bool.
1138
1139 isalnum(c); // Is c a letter or digit?
1140 isalpha(c); isdigit(c); // Is c a letter? Digit?
1141 islower(c); isupper(c); // Is c lower case? Upper case?
1142 c=tolower(c); c=toupper(c); // Convert c to lower/upper case
1143<cmath>
1144Functions take double and return double.
1145
1146 sin(x); cos(x); tan(x); // Trig functions, x in radians
1147 asin(x); acos(x); atan(x);// Inverses
1148 atan2(y, x); // atan(y/x)
1149 sinh(x); cosh(x); tanh(x);// Hyperbolic
1150 exp(x); log(x); log10(x); // e to the x, log base e, log base 10
1151 pow(x, y); sqrt(x); // x to the y, square root
1152 ceil(x); floor(x); // Round up or down (as a double)
1153 fabs(x); fmod(x, y); // Absolute value, x mod y
1154<ctime>
1155Functions for reading the system clock. time_t is an integer type (usually long). tm is a struct.
1156
1157 clock()/CLOCKS_PER_SEC; // Time in seconds since program started
1158 time_t t=time(0); // Absolute time in seconds or -1 if unknown
1159 tm* p=gmtime(&t); // 0 if UCT unavailable, else p->tm_X where X is:
1160 sec, min, hour, mday, mon (0-11), year (-1900), wday, yday, isdst
1161 asctime(p); // "Day Mon dd hh:mm:ss yyyy\n"
1162 asctime(localtime(&t)); // Same format, local time
1163<cstring>
1164Functions for performing stringlike operations on arrays of char marked with a terminating '\0' (such as "quoted literals" or as returned by string::c_str(). Mostly obsoleted by type string.
1165
1166 strcpy(dst, src); // Copy src to dst. Not bounds checked
1167 strcat(dst, src); // Concatenate to dst. Not bounds checked
1168 strcmp(s1, s2); // Compare, <0 if s1<s2, 0 if s1==s2, >0 if s1>s2
1169 strncpy(dst, src, n); // Copy up to n chars, also strncat(), strncmp()
1170 strlen(s); // Length of s not counting \0
1171 strchr(s,c); strrchr(s,c);// Address of first/last char c in s or 0
1172 strstr(s, sub); // Address of first substring in s or 0
1173 // mem... functions are for any pointer types (void*), length n bytes
1174 memcpy(dst, src, n); // Copy n bytes from src to dst
1175 memmove(dst, src, n); // Same, but works correctly if dst overlaps src
1176 memcmp(s1, s2, n); // Compare n bytes as in strcmp
1177 memchr(s, c, n); // Find first byte c in s, return address or 0
1178 memset(s, c, n); // Set n bytes of s to c
1179<cstdio>
1180The stdio library is made mostly obsolete by the newer iostream library, but many programs still use it. There are facilities for random access files and greater control over output format, error handling, and temporary files. Mixing both I/O libraries is not recommended. There are no facilities for string I/O.
1181
1182Global objects stdin, stdout, stderr of type FILE* correspond to cin, cout, cerr. s is type char*, c is char, n is int, f is FILE*.
1183
1184 FILE* f=fopen("filename", "r"); // Open for reading, NULL (0) if error
1185 // Mode may also be "w" (write) "a" append, "a+" random access read/append,
1186 // "rb", "wb", "ab", "a+b" are binary
1187 fclose(f); // Close file f
1188 fprintf(f, "x=%d", 3); // Print "x=3" Other conversions:
1189 "%5d %u %-8ld" // int width 5, unsigned int, long left justified
1190 "%o %x %X %lx" // octal, hex, HEX, long hex
1191 "%f %5.1f" // double: 123.000000, 123.0
1192 "%e %g" // 1.23e2, use either f or g
1193 "%c %s" // char, char*
1194 "%%" // %
1195 sprintf(s, "x=%d", 3); // Print to array of char s
1196 printf("x=%d", 3); // Print to stdout (screen unless redirected)
1197 fprintf(stderr, ... // Print to standard error (not redirected)
1198 getc(f); // Read one char (as an int, 0-255) or EOF (-1) from f
1199 ungetc(c, f); // Put back one c to f
1200 getchar(); // getc(stdin);
1201 putc(c, f) // fprintf(f, "%c", c);
1202 putchar(c); // putc(c, stdout);
1203 fgets(s, n, f); // Read line including '\n' into char s[n] from f. NULL if EOF
1204 gets(s) // fgets(s, INT_MAX, f); no '\n' or bounds check
1205 fread(s, n, 1, f); // Read n bytes from f to s, return number read
1206 fwrite(s, n, 1, f); // Write n bytes of s to f, return number written
1207 fflush(f); // Force buffered writes to f
1208 fseek(f, n, SEEK_SET); // Position binary file f at n
1209 // or SEEK_CUR from current position, or SEEK_END from end
1210 ftell(f); // Position in f, -1L if error
1211 rewind(f); // fseek(f, 0L, SEEK_SET); clearerr(f);
1212 feof(f); // Is f at end of file?
1213 ferror(f); // Error in f?
1214 perror(s); // Print char* s and last I/O error message to stderr
1215 clearerr(f); // Clear error code for f
1216 remove("filename"); // Delete file, return 0 if OK
1217 rename("old", "new"); // Rename file, return 0 if OK
1218 f = tmpfile(); // Create temporary file in mode "wb+"
1219 tmpnam(s); // Put a unique file name in char s[L_tmpnam]
1220Example: input file name and print its size
1221
1222 char filename[100]; // Cannot be a string
1223 printf("Enter filename\n"); // Prompt
1224 gets(filename, 100, stdin); // Read line ending in "\n\0"
1225 filename[strlen(filename)-1]=0; // Chop off '\n';
1226 FILE* f=fopen(filename, "rb"); // Open for reading in binary mode
1227 if (f) { // Open OK?
1228 fseek(f, 0, SEEK_END); // Position at end
1229 long n=ftell(f); // Get position
1230 printf("%s has %ld bytes\n", filename, n);
1231 fclose(f); // Or would close when program ends
1232 }
1233 else
1234 perror(filename); // fprintf(stderr, "%s: not found\n", filename);
1235 // or permission denied, etc.
1236printf(), fprintf(), and sprintf() accept a variable number of arguments, one for each "%" in the format string, which must be the approprate type. The compiler does not check for this.
1237 printf("%d %f %s", 2, 2.0, "2"); // OK
1238 printf("%s", 5); // Crash: expected a char* arg, read from address 5
1239 printf("%s"); // Crash
1240 printf("%s", string("hi")); // Crash: use "hi" or string("hi").c_str()
1241<cassert>
1242Provides a debugging function for testing conditions where all instances can be turned on or off at once. assert(false); prints the asserted expression, source code file name, and line number, then aborts. Compiling with g++ -DNDEBUG effectively removes these statements.
1243
1244 assert(e); // If e is false, print message and abort
1245 #define NDEBUG // (before #include <assert.h>), turn off assert
1246Classes
1247Classes provide data abstraction, the ability to create new types and hide their implementation in order to improve maintainability. A class is a data structure and an associated set of member functions (methods) and related type declarations which can be associated with the class or instances (objects) of the class. A class is divided into a public interface, visible wherever the class or its instances are visible, and a private implementation visible only to member functions of the class.
1248
1249 class T { // Create a new type T
1250 private: // Members are visible only to member functions of T (default)
1251 public: // Members are visible wherever T is visible
1252 // Type, object, and function declarations
1253 };
1254 T::m; // Member m of type T
1255 T x; // Create object x of type T
1256 x.m; // Member m of object x
1257 T* p=&x; p->m; // Member m of object pointed to by p
1258Typically the data structure is private, and functionality is provided by member functions. Member function definitions should be separated from the declaration and written outside the class definition, or else they are assumed to be inline (which is appropriate for short functions). A member function should be declared const (before the opening brace) if it does not modify any data members. Only const member functions may be called on const objects.
1259 class Complex { // Represents imaginary numbers
1260 private:
1261 double re, im; // Data members, represents re + im * sqrt(-1)
1262 public:
1263 void set(double r, double i) {re=r; im=i;} // Inlined member function definition
1264 double real() const {return re;} // const method does not modify data members
1265 double imag() const; // Declaration for non-inlined function
1266 };
1267 double Complex::imag() const {return im;} // Definition for imag()
1268 int main() {
1269 Complex a, b=a; // Objects of type Complex
1270 a.set(3, 4); // Call a member function
1271 b=a; // Assign b.re=a.re; b.im=a.im
1272 b==a; // Error, == is not defined
1273 cout << a.re; // Error, re is private
1274 cout << a.real(); // OK, 3
1275 cout << Complex().real(); // OK, prints an undefined value
1276 Complex().set(5, 6); // Error, non-const member called on const object
1277A class has two special methods, a constructor, which is called when the object is created, and a destructor, called when destroyed. The constructor is named class::class, has no return type or value, may be overloaded and have default arguments, and is never const. It is followed by an optional initialization list listing each data member and its initial value. Initialization takes place before the constructor code is executed. Initialization might not be in the order listed. Members not listed are default-initialized by calling their constructors with default arguments. If no constructor is written, the compiler provides one which default-initializes all members. The syntax is:
1278
1279 class::class(parameter list): member(value), member(value) { code...}
1280The destructor is named class::~class, has no return type or value, no parameters, and is never const. It is usually not needed except to return shared resources by closing files or deleting memory. After the code executes, the data members are destroyed using their respective destructors in the reverse order in which they were constructed.
1281
1282 class Complex {
1283 public:
1284 Complex(double r=0, double i=0): re(r), im(i) {} // Constructor
1285 ~Complex() {} // Destructor
1286 // Other members...
1287 };
1288 Complex a(1,2), b(3), c=4, d; // (1,2) (3,0) (4,0) (0,0)
1289A constructor defines a conversion function for creating temporary objects. A constructor that allows 1 argument allows implicit conversion wherever needed, such as in expressions, parameter passing, assignment, and initialization.
1290
1291 Complex(3, 4).real(); // 3
1292 a = 5; // Implicit a = Complex(5) or a = Complex(5, 0)
1293
1294 void assign_if(bool, Complex&, const Complex&);
1295 assign_if(true, a, 6); // Implicit Complex(6) passed to parameter c
1296 assign_if(true, 6, a); // Error, non-const reference to Complex(6), which is const
1297Operators may be overloaded as members. The expression aXb for operator X can match either operator X(a, b) (global) or a.operator X(b) (method), but not both. Unary operators omit b.
1298
1299 class Complex {
1300 public:
1301 Complex operator + (const Complex& b) const { // const because a+b doesn't change a
1302 return Complex(re+b.re, im+b.im);
1303 }
1304 // ...
1305 };
1306
1307 Complex operator - (const Complex& a, const Complex& b) {
1308 return Complex(a.real()-b.real(), a.imag()-b.imag());
1309 }
1310
1311 Complex a(1, 2), b(3, 4);
1312 a+b; // OK, a.operator+(b) == Complex(4, 6)
1313 a-b; // OK, operator-(a, b) == Complex(-2, -2)
1314 a+10; // OK, Complex(1, 12), implicit a+Complex(10, 0)
1315 10+a; // Error, 10 has no member operator+(Complex)
1316 a-10; // OK, Complex(1, -8)
1317 10-a; // OK, Complex(7, -4)
1318The method (+) has the advantage of private access (including to other objects of the same class), but can only do implicit conversions on the right side. The global function (-) is symmetrical, but lacks private access. A friend declaration (in either the private or public section) allows private access to a global function.
1319
1320 class Complex {
1321 friend Complex operator-(const Complex&, const Complex&);
1322 friend class T; // All methods of class T are friends
1323 // ...
1324 };
1325A conversion operator allows implicit conversion to another type. It has the form of a method named operator T() const with implied return type T. It is generally a good idea to allow implicit conversions in only one direction, preferably with constructors, so this method is usually used to convert to pre-existing types.
1326
1327 class Complex {
1328 public:
1329 operator double() const {return re;}
1330 // ...
1331 }
1332
1333 Complex a(1, 2);
1334 a-10; // Error, double(a)-10 or a-Complex(10) ?
1335 a-Complex(10); // Complex(-9, 2);
1336 double(a)-10; // -9
1337An explicit constructor does not allow implicit conversions.
1338
1339 class Complex {
1340 explicit Complex(double r=0, double i=0);
1341 // ...
1342 };
1343
1344 Complex a=1; // Error
1345 Complex a(1); // OK
1346 a-10; // OK, double(a)-10 = -9
1347 a-Complex(10); // OK, Complex(-9, 0)
1348A class or method may be templated. The type parameter must be passed in the declaration for objects of the class.
1349
1350 template <class T>
1351 class Complex {
1352 T re, im;
1353 public:
1354 T real() const {return re;}
1355 T imag() const {return im;}
1356 Complex(T r=0, T i=0);
1357 friend T operator - (const T&, const T&);
1358 };
1359
1360 template <class T>
1361 Complex<T>::Complex(T r, T i): re(r), im(i) {}
1362
1363 Complex<int> a(1, 2); // Complex of int
1364 Complex<double> b(1.0, 2.0); // Complex of double
1365 a=a-Complex<int>(3, 4); // Complex<int>(-2, -2)
1366 Complex<Complex<double> > c(b, b); // Note space, not >>
1367 c.real().imag(); // 2.0
1368Templates can have default arguments and int parameters. The argument to an int parameter must be a value known at compile time.
1369 template <class T, class U=T, int n=0> class V {};
1370 V<double, string, 3> v1;
1371 V<char> v2; // V<char, char, 0>
1372Classes define default behavior for copying and assignment, which is to copy/assign each data member. This behavior can be overridden by writing a copy constructor and operator= as members, both taking arguments of the same type, passed by const reference. They are usually required in classes that have destructors, such as the vector<T>-like class below. If we did not overload these, the default behavior would be to copy the data pointer, resulting in two Vectors pointing into the same array. The assignment operator normally returns itself (*this) by reference to allow expressions of the form a=b=c;, but is not required to do so. this means the address of the current object; thus any member m may also be called this->m within a member function.
1373
1374 template <class T>
1375 class Vector {
1376 private:
1377 T* data; // Array of n elements
1378 int n; // size()
1379 public:
1380 typedef T* iterator; // Vector::iterator means T*
1381 typedef const T* const_iterator; // Iterators for const Vector
1382 int size() const {return n;} // Number of elements
1383 T& operator[](int i) {return data[i];} // i'th element
1384 const T& operator[](int i) const {return data[i];} // i'th element of const Vector
1385 iterator begin() {return data;} // First, last+1 elements
1386 iterator end() {return data+size();}
1387 const_iterator begin() const {return data;} // Const versions
1388 const_iterator end() const {return data+size();}
1389 Vector(int i=0): data(new T[i]), n(i) {} // Create with size i
1390 ~Vector() {delete[] data;} // Return memory
1391 Vector(const Vector<T>& v): data(new T[v.n]), n(v.n) { // Copy constructor
1392 copy(v.begin(), v.end(), begin());
1393 }
1394 Vector& operator=(const Vector& v) { // Assignment
1395 if (&v != this) { // Assignment to self?
1396 delete[] data; // If not, resize and copy
1397 data=new T[n=v.n];
1398 copy(v.begin(), v.end(), begin());
1399 }
1400 return *this; // Allow a=b=c;
1401 }
1402 template <class P> Vector(P b, P e): data(new T[e-b]), n(e-b) { // Templated member
1403 copy(b, e, data); // Ititialize from sequence [b, e)
1404 }
1405 };
1406A type defined in a class is accessed through class::type
1407 Vector<int>::iterator p; // Type is int*
1408 Vector<int>::const_iterator cp; // Type is const int*
1409Methods may be overloaded on const. Overloaded methods need not have the same return types. const methods should not return non-const references or pointers to data members.
1410 Vector<int> v(10); // Uses non-const [], begin(), end()
1411 const Vector<int> cv(10); // Uses const [], begin(), end()
1412 cv=v; // Error, non-const operator= called on cv
1413 v[5]=cv[5]; // OK. assigns to int&
1414 cv[5]=v[5]; // Error, assigns to const int&
1415 p=cv.begin(); // Error, would allow *p=x to write into cv
1416 cp=cv.begin(); // OK because can't assign to *cp
1417A static data member is shared by all instances of a class. It must be initialized in a separate declaration, not in the class definition or in the constructor intialization list. A static method cannot refer to this or any non-static members (and therefore it makes no sense to make them const). Static members may be referenced either as object.member or class::member.
1418
1419 class Counter {
1420 static int count; // Number of Counters that currently exist (private)
1421 public:
1422 static int get() {return count;}
1423 Counter() {++count;}
1424 ~Counter() {--count;}
1425 Counter(const Counter& c) {++count;} // Default would be wrong
1426 Counter& operator=(const Counter& c) {return *this;} // Default would be OK
1427 };
1428 int Counter::count = 0; // Initialize here, OK if private
1429 main() {
1430 Counter a, b, c;
1431 cout << b.get(); // 3
1432 cout << Counter::get(); // 3
1433 }
1434Operators [] and = can only be overloaded as member functions. Operator -> should be overloaded as a unary function returning a pointer to a class to which -> will be applied, i.e. x->m is interpreted as x.operator->()->m. Nested class members are named Outer::Inner::member. Outer and inner classes cannot access each other's private members. Templated members defined outside the class need their own template declarations.
1435
1436 // Reverse iterator for Vector, i.e. ++p goes to the previous element.
1437 template <class T> class Vector {
1438 public:
1439 class reverse_iterator { // Iterates backwards through a Vector<T>
1440 private:
1441 T* p; // Points to current element
1442 public:
1443 reverse_iterator(T* a=0): p(a) {} // Implicit conversion from T* and iterator
1444 Vector<T>::iterator base() const {return p;} // Convert to normal iterator
1445
1446 // Forward operators
1447 Vector<T>::reverse_iterator& operator++() {--p; return *this;} // prefix
1448 Vector<T>::reverse_iterator operator++(int); // postfix, we pretend it's binary
1449 T& operator*() const {return *p;}
1450 T* operator->() const {return p;} // We pretend it's unary
1451 bool operator==(Vector<T>::reverse_iterator b) const {return p==b.p;}
1452 bool operator!=(Vector<T>::reverse_iterator b) const {return p!=b.p;}
1453 // Also, bidirectional and random operators
1454 };
1455 reverse_iterator rbegin() {return end()-1;}
1456 reverse_iterator rend() {return begin()-1;}
1457 // Other members...
1458 };
1459
1460 // Code for postfix ++
1461 teplate <class T>
1462 inline Vector<T>::reverse_iterator Vector::reverse_iterator::operator++(int dummy) {
1463 Vector<T>::reverse_iterator result = *this;
1464 ++*this;
1465 return result;
1466 };
1467
1468 // Print a Vector in reverse order
1469 int main() {
1470 Vector<int> a(10);
1471 for (Vector<int>::reverse_iterator p=a.rbegin(); p!=a.rend(); ++p)
1472 cout << *p << endl;
1473vector<T> supplies random reverse_iterator and const_reverse_iterator as above.
1474Inheritance
1475Inheritance is used to write a specialized or enhanced version of another class. For example, an ofstream is a type of ostream. class D: public B defines class D as derived from (subclass of) base class (superclass) B, meaning that D inherits all of B's members, except the constructors, destructor, and assignment operator. The default behavior of these special methods is to treat the base class as a data member.
1476 class String: public Vector<char> {
1477 public:
1478 String(const char* s=""): Vector<char>(strlen(s)) {
1479 copy(s, s+strlen(s), begin()); // Inherits Vector<char>::begin()
1480 }
1481 };
1482 String a="hello"; // Calls Vector<char>::Vector(5);
1483 a.size(); // 5, inherits Vector<char>::size()
1484 a[0]='j'; // "jello", inherits Vector<char>::operator[]
1485 String b=a; // Default copy constructor uses Vector's copy constructor on base part
1486 b=a; // Default = calls Vector's assignment operator on base part
1487The default destructor String::~String() {} is correct, since in the process of destroying a String, the base is also destroyed, calling Vector<char>::~Vector() {delete data[];}. Since there is no need to write a destructor, there is no need to redefine copying or assignment either.
1488Although String inherits Vector<char>::data, it is private and inaccessible. A protected member is accessible to derived classes but private elsewhere.
1489
1490 class B {
1491 protected:
1492 int x;
1493 } b; // Declare class B and object b
1494 b.x=1; // Error, x is protected
1495
1496 class D: public B {
1497 void f() {x=1;} // OK
1498 };
1499By default, a base class is private, making all inherited members private. Private base classes are rare and typically used as implementations rather than specializations (A string is a vector, but a stack is not).
1500 class Stack: Vector<int> { // or class Stack: private Vector<int>
1501 public:
1502 bool empty() const {return size()==0;} // OK
1503 } s;
1504 s.size(); // Error, private
1505 s.empty(); // OK, public
1506A class may have more than one base class (called multiple inheritance). If both bases are in turn derived from a third base, then we derive from this root class using virtual to avoid inheriting its members twice further on. Any indirectly derived class treats the virtual root as a direct base class in the constructor initialization list.
1507
1508 class ios {...}; // good(), binary, ...
1509 class fstreambase: public virtual ios {...}; // open(), close(), ...
1510 class istream: public virtual ios {...}; // get(), operator>>(), ...
1511 class ifstream: public fstreambase, public istream { // Only 1 copy of ios
1512 ifstream(): fstreambase(), istream(), ios() {...} // Normally ios() would be omitted
1513 };
1514Polymorphism
1515Polymorphism is the technique of defining a common interface for a hierarchy of classes. To support this, a derived object is allowed wherever a base object is expected. For example,
1516 String s="Hello";
1517 Vector<char> v=s; // Discards derived part of s to convert
1518 Vector<char>* p=&s; // p points to base part of s
1519 try {throw s;} catch(Vector<char> x) {} // Caught with x set to base part of s
1520 s=Vector<char>(5); // Error, can't convert base to derived
1521
1522 // Allow output of Vector<char> using normal notation
1523 ostream& operator << (ostream& out, const Vector<char>& v) {
1524 copy(v.begin(), v.end(), ostream_iterator<char>(out, "")); // Print v to out
1525 return out; // To allow (cout << a) << b;
1526 }
1527 cout << s; // OK, v refers to base part of s
1528 ofstream f("file.txt");
1529 f << s; // OK, ofstream is derived from ostream
1530A derived class may redefine inherited methods, overriding any method with the same name, parameters, return type, and const-ness (and hiding other methods with the same name, thus the overriding method should not be overloaded). The method call is resolved at compile time. This is incorrect in case of a base pointer or reference to a derived object. To allow run time resolution, the base method should be declared virtual. Since the default destructor is not virtual, a virtual destructor should be added to the base class. If empty, no copy constructor or assignment operator is required. Constructors and = are never virtual.
1531
1532 class Shape {
1533 public:
1534 virtual void draw() const;
1535 virtual ~Shape() {}
1536 };
1537 class Circle: public Shape {
1538 public:
1539 void draw() const; // Must use same parameters, return type, and const
1540 };
1541
1542 Shape s; s.draw(); // Shape::draw()
1543 Circle c; c.draw(); // Circle::draw()
1544 Shape& r=c; r.draw(); // Circle::draw() if virtual
1545 Shape* p=&c; p->draw(); // Circle::draw() if virtual
1546 p=new Circle; p->draw(); // Circle::draw() if virtual
1547 delete p; // Circle::~Circle() if virtual
1548An abstract base class defines an interface for one or more derived classes, which are allowed to instantiate objects. Abstractness can be enforced by using protected (not private) constructors or using pure virtual methods, which must be overridden in the derived class or else that class is abstract too. A pure virtual method is declared =0; and has no code defined.
1549
1550 class Shape {
1551 protected:
1552 Shape(); // Optional, but default would be public
1553 public:
1554 virtual void draw() const = 0; // Pure virtual, no definition
1555 virtual ~Shape() {}
1556 };
1557 // Circle as before
1558
1559 Shape s; // Error, protected constructor, no Shape::draw()
1560 Circle c; // OK
1561 Shape& r=c; r.draw(); // OK, Circle::draw()
1562 Shape* p=new Circle(); // OK
1563Run time type identification
1564C++ provides for run time type identification, although this usually indicates a poor design. dynamic_cast<T>(x) checks at run time whether a base pointer or referece is to a derived object, and if so, does a conversion. The base class must have at least one virtual function to use run time type checking.
1565 #include <typeinfo> // For typeid()
1566 typeid(*p)==typeid(T) // true if p points to a T
1567 dynamic_cast<T*>(p) // Convert base pointer to derived T* or 0.
1568 dynamic_cast<T&>(r) // Convert base reference to derived T& or throw bad_cast()
1569For example,
1570 class B {public: virtual void f(){}};
1571 class D: public B {public: int x;} d; // Bad design, public member in D but not B
1572 B* p=&d; p->x; // Error, no B::x
1573 D* q=p; q->x; // Error, can't convert B* to D*
1574 q=(D*)p; q->x; // OK, but reinterpret_cast, no run time check
1575 q=dynamic_cast<D*>(p); if (q) q->x; // OK
1576Other Types
1577typedef defines a synonym for a type.
1578 typedef char* Str; // Str is a synonym for char*
1579 Str a, b[5], *c; // char* a; char* b[5]; char** c;
1580 char* d=a; // OK, really the same type
1581enum defines a type and a set of symbolic values for it. There is an implicit conversion to int and expicit conversion from int to enum. You can specify the int equivalents of the symbolic names, or they default to successive values beginning with 0. Enums may be anonymous, specifying the set of symbols and possibly objects without giving the type a name.
1582
1583 enum Weekday {MON,TUE=1,WED,THU,FRI}; // Type declaration
1584 enum Weekday today=WED; // Object declaration, has value 2
1585 today==2 // true, implicit int(today)
1586 today=Weekday(3); // THU, conversion must be explicit
1587 enum {N=10}; // Anonymous enum, only defines N
1588 int a[N]; // OK, N is known at compile time
1589 enum {SAT,SUN} weekend=SAT; // Object of anonymous type
1590A struct is a class where the default protection is public instead of private. A struct can be initialized like an array.
1591
1592 struct Complex {double re, im;}; // Declare type
1593 Complex a, b={1,2}, *p=&b; // Declare objects
1594 a.re = p->im; // Access members
1595A union is a struct whose fields overlap in memory. Unions can also be anonymous. They may be used to implement variant records.
1596
1597 union U {int i; double d;}; // sizeof(U) is larger of int or double
1598 U u; u.i=3; // overwrites u.d
1599
1600 // A variant record
1601 class Token {
1602 enum {INT, DOUBLE} type; // which field is in use?
1603 union {int i; double d;} value; // An anonymous union
1604 public:
1605 void print() const {
1606 if (type==INT) cout << value.i;
1607 else cout << value.d;
1608 }
1609 };
1610An enum, struct, class, or union type and a list of objects may be declared together in a single statement.
1611
1612 class Complex {public: double re, im;} a, b={1,2}, *p=&b;
1613Program Organization
1614For C++ programs that only use one source code file and the standard library, the only rule is to declare things before using them: type declarations before object declarations, and function declarations or definitions before calling them. However, implicitly inlined methods may use members not yet declared, and templates may use names as long as they are declared before instantiation.
1615
1616 class Complex {
1617 double real() const {return re;} // OK
1618 double re, im;
1619 };
1620Functions and methods (unless inlined or templated) and global or class static objects are separately compilable units, and may appear in separate source code (.cpp) files. If 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 be in a shared header file. A shared header conventionally has a .h extension, and is inserted with a #include "filename.h", using double quotes to indicate that the file is in the current directory. Global variables are declared with extern without initialization.
1621
1622// prog.h // prog1.cpp // prog2.cpp
1623extern int x; #include "prog.h" #include "prog.h"
1624int f(); int x=0; int f() {
1625 int main() { return x;
1626 f(); }
1627 return 0;
1628 }
1629To compile,
1630 g++ prog1.cpp prog2.cpp -o prog
1631This produces two object files (prog1.o, prog2.o), and then links them to produce the executable prog. g++ also accepts .o files, which are linked only, saving time if the .cpp file was not changed. To compile without linking, use -c. To optimize (compile slower but run faster), use -O.
1632The UNIX make command updates the executable as needed based on the timestamps of source and .o files. It requires a file named Makefile containing a set of dependencies of the form:
1633
1634 file: files which should be older than file
1635 (tab) commands to update file
1636Dependencies may be in any order. The Makefile is executed repeatedly until all dependencies are satisfied.
1637 # Makefile comment
1638 prog: prog1.o prog2.o
1639 g++ prog1.o prog2.o -o prog
1640
1641 prog1.o: prog1.cpp prog.h
1642 g++ -c prog1.cpp
1643
1644 prog2.o: prog2.cpp prog.h
1645 g++ -c prog2.cpp
1646Compiler options for g++. Other compilers may vary.
1647 g++ file1.cpp Compile, produce executable a.out in UNIX
1648 g++ file1.cpp file2.o Compile .cpp and link .o to executable a.out
1649 g++ -Wall Turn on all warnings
1650 g++ -c file1.cpp Compile to file1.o, do not link
1651 g++ -o file1 Rename a.out to file1
1652 g++ -O Optimize executable for speed
1653 g++ -v Verbose mode
1654 g++ -DX=Y Equivalent to #define X Y
1655 g++ --help Show all g++ options
1656 gxx file1.cpp Compile in Windows MS-DOS box (DJGPP) to A.EXE
1657Anything which is not a separately compilable unit may appear in a header file, such as class definitions (but not method code unless inlined), templated classes (including method code), templated functions, and other #include statements.
1658
1659Creating Libraries (namespaces)
1660Libraries usually come in the form of a header and an object (.o) file. To use them, #include "header.h" and link the .o file using g++. If the .o was compiled in C rather than C++, then indicate this with extern "C" {} to turn off name mangling. C++ encodes or "mangles" overloaded function names to allow them to be linked, but C does not since it doesn't allow overloading.
1661 extern "C" { // Turn off name mangling
1662 #include "header.h" // Written in C
1663 }
1664When writing your own library, use a unique namespace name to prevent conflicts with other libraries. A namespace may span multiple files. Types, objects, and functions declared in a namespace N must be prefixed with N:: when used outside the namespace, or there must be a using namespace N; in the current scope.
1665Also, to guard against possible multiple inclusions of the header file, #define some symbol and test for it with #ifndef ... #endif on the first and last lines. Don't have a using namespace std;, since the user may not want std visible.
1666
1667 #ifndef MYLIB_H // mylib.h, or use #if !defined(MYLIB_H)
1668 #define MYLIB_H
1669 #include <string>
1670 // No using statement
1671 namespace mylib {
1672 class B {
1673 public:
1674 std::string f(); // No code
1675 }
1676 }
1677 #endif
1678
1679 // mylib.cpp, becomes mylib.o
1680 #include <string>
1681 #include "mylib.h"
1682 using namespace std; // OK
1683 namespace mylib {
1684 string B::f() {return "hi";}
1685 }
1686#define could be used to create constants through text substitution, but it is better to use const to allow type checking. #define X Y has the effect of replacing symbol X with arbitrary text Y before compiling, equivalent to the g++ option -DX=Y. Each compiler usually defines a different set of symbols, which can be tested with #if, #ifdef, #ifndef, #elsif, #else, and #endif.
1687 #ifdef unix // Defined by most UNIX compilers
1688 // ...
1689 #else
1690 // ...
1691 #endif
1692Preprocessor statements are one line (no semicolon). They perform text substitutions in the source code prior to compiling.
1693 #include <header> // Standard header
1694 #include "header.h" // Include header file from current directory
1695 #define X Y // Replace X with Y in source code
1696 #define f(a,b) a##b // Replace f(1,2) with 12
1697 #define X \ // Continue a # statement on next line
1698 #ifdef X // True if X is #defined
1699 #ifndef X // False if X is #defined
1700 #if !defined(X) // Same
1701 #else // Optional after #if...
1702 #endif // Required
1703History of C++
1704C++ evolved from C, which in turn evolved from B, written by Ken Thompson in 1970 as a variant of BCPL. C was developed in the 1970's by Brian Kernighan and Dennis Ritchie as a "portable assembly language" to develop UNIX. C became widely available when they published "The C Programming Language" in 1983. C lacked standard containers (string, vector, map), iostreams, bool, const, references, classes, exceptions, namespaces, new/delete, function and operator overloading, and object-oriented capabilities. I/O was done using <stdio.h>. 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(). Function arguments were not type checked. Functions could only modify arguments by passing their addresses. Memory allocation was done using malloc(), which requires the number of bytes to allocate and returns an untyped pointer or NULL if it fails. The language allowed unsafe implicit conversions such as int to pointers. Variables had to be declared before the first statement. There was no inline, so macros were often used in place of small functions. Hardware was slow and optimizers were not very good, so it was common to declare register variables. There were no // style comments. For instance,
1705
1706 /* Copy argv[1] to buf and print it */
1707 #include <stdio.h> /* No cout, use printf() */
1708 #include <string.h> /* No string type, use char* */
1709 #include <stdlib.h> /* No new/delete, use malloc/free */
1710 main(argc, argv) /* Return type defaults to int */
1711 int argc; /* Old style parameter declaration, no type checking */
1712 char** argv;
1713 { /* No namespace std */
1714 char* buf; /* All declarations before the first statement */
1715 if (argc>1) {
1716 buf=(char*)malloc((strlen(argv[1])+1)*sizeof(char)); /* Cast optional */
1717 strcpy(buf, argv[1]); /* Can't assign, no range check */
1718 printf("%s\n", buf); /* Arguments not type checked */
1719 free(buf); /* No delete */
1720 }
1721 } /* Return value is undefined (unchecked) */
1722The ANSI C standard was finished in 1988. It added const, new style function declaration with type checking, struct assignment, strict type checking of pointer assignments, and specified the standard C library, which until now was widely used but with minor, annoying variations. However, many compilers did not become ANSI compliant until the early 1990's.
1723
1724In the 1980's Bjarne Stroustrup at AT&T developed "C with Classes", later C++. Early implementations were available for UNIX as cfront (cc), a C++ to C translator around 1990. It added object oriented programming with classes, inheritance, and polymorphism, also references, the iostream library, and minor enhancements such as // style comments and the ability to declare variables anywhere. Because there were no namespaces, the iostream header was named <iostream.h> and no using statement was required. Unlike C programs which always have a .c extension, C++ didn't say, so .cpp, .cc and .C were all common, and .hpp for headers.
1725
1726GNU gcc and g++, which compiled C and C++ directly to machine code, were developed in the early 1990's. Templates were added in 1993. Exceptions were added in 1994. The standard container library (originally called the standard template library or STL) was developed by researchers at Hewlett-Packard and made available free as a separate download in the mid 1990's and ported to several compilers.
1727
1728ANSI standard C++ compilers became available in 1998. This added STL to the standard library, added multiple inheritance, namespaces, type bool, and run time type checking (dynamic_cast, typeid). The .h extension on headers was dropped.
1729
1730C++ most likely succeeded where other early object oriented languages failed (Simula67, Actor, Eiffel, Smalltalk) because it was backwards compatible with C, allowing old code to be used, and because C programmers could use it immediately without learning the new features. However, there are a few incompatilities.
1731
1732Old style function declarations are not allowed.
1733Conversion from void* (returned by malloc()) requires a cast.
1734There are many new reserved words.
1735There are also some imcompatabilities between old (before 1998) and new versions of C++.
1736
1737new was changed to throw type bad_alloc if out of memory, instead of returning 0.
1738The scope of a variable declared in a for loop was changed to be local to the loop and not beyond it (not yet implemented by Microsoft Visual C++)
1739g++ does not yet implement all ANSI C++ features. For instance,
1740
1741Type ostringstream allowing formatted writing to strings.
1742Run time bounds checking of vector indexes using v.at(i)
1743The largest integer type is 32 bits in most implementations, but as 64 bit machines become common it is possible that type long could become a 64 bit type (as in Java) in the future. g++ supports the nonstandard 64-bit integer type long long, e.g.
1744
1745 unsigned long long bigzero=0LLU;
1746Most implementations of time() return the number of seconds since Jan. 1, 1970 as a time_t, normally a signed 32-bit long. Programs that use this implementation will fail on Jan. 19, 2038 at 3:14:08 AM as this value overflows and becomes negative.