├── README.md
└── cheatsheet-as-sourcefile.cpp
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | # C++ QUICK REFERENCE / C++ CHEATSHEET
4 | Based on Phillip M. Duxbury's C++ Cheatsheet and edited by Morten Nobel-Jørgensen.
5 | The cheatsheet focus is both on the language as well as common classes from the standard library.
6 | C++11 additions is inspired by ISOCPP.org C++11 Cheatsheet).
7 |
8 | The goal is to give a concise overview of basic, modern C++ (C++14).
9 |
10 | The document is hosted on https://github.com/mortennobel/cpp-cheatsheet. Any comments and feedback are appreciated.
11 |
12 | ## Preprocessor
13 |
14 | ```cpp
15 | // Comment to end of line
16 | /* Multi-line comment */
17 | #include // Insert standard header file
18 | #include "myfile.h" // Insert file in current directory
19 | #define X some text // Replace X with some text
20 | #define F(a,b) a+b // Replace F(1,2) with 1+2
21 | #define X \
22 | some text // Multiline definition
23 | #undef X // Remove definition
24 | #if defined(X) // Conditional compilation (#ifdef X)
25 | #else // Optional (#ifndef X or #if !defined(X))
26 | #endif // Required after #if, #ifdef
27 | ```
28 |
29 | ## Literals
30 |
31 | ```cpp
32 | 255, 0377, 0xff // Integers (decimal, octal, hex)
33 | 2147483647L, 0x7fffffffl // Long (32-bit) integers
34 | 123.0, 1.23e2 // double (real) numbers
35 | 'a', '\141', '\x61' // Character (literal, octal, hex)
36 | '\n', '\\', '\'', '\"' // Newline, backslash, single quote, double quote
37 | "string\n" // Array of characters ending with newline and \0
38 | "hello" "world" // Concatenated strings
39 | true, false // bool constants 1 and 0
40 | nullptr // Pointer type with the address of 0
41 | ```
42 |
43 | ## Declarations
44 |
45 | ```cpp
46 | int x; // Declare x to be an integer (value undefined)
47 | int x=255; // Declare and initialize x to 255
48 | short s; long l; // Usually 16 or 32 bit integer (int may be either)
49 | char c='a'; // Usually 8 bit character
50 | unsigned char u=255;
51 | signed char s=-1; // char might be either
52 | unsigned long x =
53 | 0xffffffffL; // short, int, long are signed
54 | float f; double d; // Single or double precision real (never unsigned)
55 | bool b=true; // true or false, may also use int (1 or 0)
56 | int a, b, c; // Multiple declarations
57 | int a[10]; // Array of 10 ints (a[0] through a[9])
58 | int a[]={0,1,2}; // Initialized array (or a[3]={0,1,2}; )
59 | int a[2][2]={{1,2},{4,5}}; // Array of array of ints
60 | char s[]="hello"; // String (6 elements including '\0')
61 | std::string s = "Hello" // Creates string object with value "Hello"
62 | std::string s = R"(Hello
63 | World)"; // Creates string object with value "Hello\nWorld"
64 | int* p; // p is a pointer to (address of) int
65 | char* s="hello"; // s points to unnamed array containing "hello"
66 | void* p=nullptr; // Address of untyped memory (nullptr is 0)
67 | int& r=x; // r is a reference to (alias of) int x
68 | enum weekend {SAT,SUN}; // weekend is a type with values SAT and SUN
69 | enum weekend day; // day is a variable of type weekend
70 | enum weekend{SAT=0,SUN=1}; // Explicit representation as int
71 | enum {SAT,SUN} day; // Anonymous enum
72 | enum class Color {Red,Blue};// Color is a strict type with values Red and Blue
73 | Color x = Color::Red; // Assign Color x to red
74 | typedef String char*; // String s; means char* s;
75 | const int c=3; // Constants must be initialized, cannot assign to
76 | const int* p=a; // Contents of p (elements of a) are constant
77 | int* const p=a; // p (but not contents) are constant
78 | const int* const p=a; // Both p and its contents are constant
79 | const int& cr=x; // cr cannot be assigned to change x
80 | int8_t,uint8_t,int16_t,
81 | uint16_t,int32_t,uint32_t,
82 | int64_t,uint64_t // Fixed length standard types
83 | auto it = m.begin(); // Declares it to the result of m.begin()
84 | auto const param = config["param"];
85 | // Declares it to the const result
86 | auto& s = singleton::instance();
87 | // Declares it to a reference of the result
88 | ```
89 |
90 | ## STORAGE Classes
91 |
92 | ```cpp
93 | int x; // Auto (memory exists only while in scope)
94 | static int x; // Global lifetime even if local scope
95 | extern int x; // Information only, declared elsewhere
96 | ```
97 |
98 | ## Statements
99 |
100 | ```cpp
101 | x=y; // Every expression is a statement
102 | int x; // Declarations are statements
103 | ; // Empty statement
104 | { // A block is a single statement
105 | int x; // Scope of x is from declaration to end of block
106 | }
107 | if (x) a; // If x is true (not 0), evaluate a
108 | else if (y) b; // If not x and y (optional, may be repeated)
109 | else c; // If not x and not y (optional)
110 |
111 | while (x) a; // Repeat 0 or more times while x is true
112 |
113 | for (x; y; z) a; // Equivalent to: x; while(y) {a; z;}
114 |
115 | for (x : y) a; // Range-based for loop e.g.
116 | // for (auto& x in someList) x.y();
117 |
118 | do a; while (x); // Equivalent to: a; while(x) a;
119 |
120 | switch (x) { // x must be int
121 | case X1: a; // If x == X1 (must be a const), jump here
122 | case X2: b; // Else if x == X2, jump here
123 | default: c; // Else jump here (optional)
124 | }
125 | break; // Jump out of while, do, or for loop, or switch
126 | continue; // Jump to bottom of while, do, or for loop
127 | return x; // Return x from function to caller
128 | try { a; }
129 | catch (T t) { b; } // If a throws a T, then jump here
130 | catch (...) { c; } // If a throws something else, jump here
131 | ```
132 |
133 | ## Functions
134 |
135 | ```cpp
136 | int f(int x, int y); // f is a function taking 2 ints and returning int
137 | void f(); // f is a procedure taking no arguments
138 | void f(int a=0); // f() is equivalent to f(0)
139 | f(); // Default return type is int
140 | inline f(); // Optimize for speed
141 | f() { statements; } // Function definition (must be global)
142 | T operator+(T x, T y); // a+b (if type T) calls operator+(a, b)
143 | T operator-(T x); // -a calls function operator-(a)
144 | T operator++(int); // postfix ++ or -- (parameter ignored)
145 | extern "C" {void f();} // f() was compiled in C
146 | ```
147 |
148 | Function parameters and return values may be of any type. A function must either be declared or defined before
149 | it is used. It may be declared first and defined later. Every program consists of a set of a set of global variable
150 | declarations and a set of function definitions (possibly in separate files), one of which must be:
151 |
152 | ```cpp
153 | int main() { statements... } // or
154 | int main(int argc, char* argv[]) { statements... }
155 | ```
156 |
157 | `argv` is an array of `argc` strings from the command line.
158 | By convention, `main` returns status `0` if successful, `1` or higher for errors.
159 |
160 | Functions with different parameters may have the same name (overloading). Operators except `::` `.` `.*` `?:` may be overloaded.
161 | Precedence order is not affected. New operators may not be created.
162 |
163 | ## Expressions
164 |
165 | Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All
166 | others are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time
167 | checks for arrays out of bounds, invalid pointers, etc.
168 |
169 | ```cpp
170 | T::X // Name X defined in class T
171 | N::X // Name X defined in namespace N
172 | ::X // Global name X
173 |
174 | t.x // Member x of struct or class t
175 | p-> x // Member x of struct or class pointed to by p
176 | a[i] // i'th element of array a
177 | f(x,y) // Call to function f with arguments x and y
178 | T(x,y) // Object of class T initialized with x and y
179 | x++ // Add 1 to x, evaluates to original x (postfix)
180 | x-- // Subtract 1 from x, evaluates to original x
181 | typeid(x) // Type of x
182 | typeid(T) // Equals typeid(x) if x is a T
183 | dynamic_cast< T>(x) // Converts x to a T, checked at run time.
184 | static_cast< T>(x) // Converts x to a T, not checked
185 | reinterpret_cast< T>(x) // Interpret bits of x as a T
186 | const_cast< T>(x) // Converts x to same type T but not const
187 |
188 | sizeof x // Number of bytes used to represent object x
189 | sizeof(T) // Number of bytes to represent type T
190 | ++x // Add 1 to x, evaluates to new value (prefix)
191 | --x // Subtract 1 from x, evaluates to new value
192 | ~x // Bitwise complement of x
193 | !x // true if x is 0, else false (1 or 0 in C)
194 | -x // Unary minus
195 | +x // Unary plus (default)
196 | &x // Address of x
197 | *p // Contents of address p (*&x equals x)
198 | new T // Address of newly allocated T object
199 | new T(x, y) // Address of a T initialized with x, y
200 | new T[x] // Address of allocated n-element array of T
201 | delete p // Destroy and free object at address p
202 | delete[] p // Destroy and free array of objects at p
203 | (T) x // Convert x to T (obsolete, use .._cast(x))
204 |
205 | x * y // Multiply
206 | x / y // Divide (integers round toward 0)
207 | x % y // Modulo (result has sign of x)
208 |
209 | x + y // Add, or \&x[y]
210 | x - y // Subtract, or number of elements from *x to *y
211 | x << y // x shifted y bits to left (x * pow(2, y))
212 | x >> y // x shifted y bits to right (x / pow(2, y))
213 |
214 | x < y // Less than
215 | x <= y // Less than or equal to
216 | x > y // Greater than
217 | x >= y // Greater than or equal to
218 |
219 | x & y // Bitwise and (3 & 6 is 2)
220 | x ^ y // Bitwise exclusive or (3 ^ 6 is 5)
221 | x | y // Bitwise or (3 | 6 is 7)
222 | x && y // x and then y (evaluates y only if x (not 0))
223 | x || y // x or else y (evaluates y only if x is false (0))
224 | x = y // Assign y to x, returns new value of x
225 | x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=
226 | x ? y : z // y if x is true (nonzero), else z
227 | throw x // Throw exception, aborts if not caught
228 | x , y // evaluates x and y, returns y (seldom used)
229 | ```
230 |
231 | ## Classes
232 |
233 | ```cpp
234 | class T { // A new type
235 | private: // Section accessible only to T's member functions
236 | protected: // Also accessible to classes derived from T
237 | public: // Accessible to all
238 | int x; // Member data
239 | void f(); // Member function
240 | void g() {return;} // Inline member function
241 | void h() const; // Does not modify any data members
242 | int operator+(int y); // t+y means t.operator+(y)
243 | int operator-(); // -t means t.operator-()
244 | T(): x(1) {} // Constructor with initialization list
245 | T(const T& t): x(t.x) {}// Copy constructor
246 | T& operator=(const T& t)
247 | {x=t.x; return *this; } // Assignment operator
248 | ~T(); // Destructor (automatic cleanup routine)
249 | explicit T(int a); // Allow t=T(3) but not t=3
250 | T(float x): T((int)x) {}// Delegate constructor to T(int)
251 | operator int() const
252 | {return x;} // Allows int(t)
253 | friend void i(); // Global function i() has private access
254 | friend class U; // Members of class U have private access
255 | static int y; // Data shared by all T objects
256 | static void l(); // Shared code. May access y but not x
257 | class Z {}; // Nested class T::Z
258 | typedef int V; // T::V means int
259 | };
260 | void T::f() { // Code for member function f of class T
261 | this->x = x;} // this is address of self (means x=x;)
262 | int T::y = 2; // Initialization of static member (required)
263 | T::l(); // Call to static member
264 | T t; // Create object t implicit call constructor
265 | t.f(); // Call method f on object t
266 |
267 | struct T { // Equivalent to: class T { public:
268 | virtual void i(); // May be overridden at run time by derived class
269 | virtual void g()=0; }; // Must be overridden (pure virtual)
270 | class U: public T { // Derived class U inherits all members of base T
271 | public:
272 | void g(int) override; }; // Override method g
273 | class V: private T {}; // Inherited members of T become private
274 | class W: public T, public U {};
275 | // Multiple inheritance
276 | class X: public virtual T {};
277 | // Classes derived from X have base T directly
278 | ```
279 |
280 | All classes have a default copy constructor, assignment operator, and destructor, which perform the
281 | corresponding operations on each data member and each base class as shown above. There is also a default no-argument
282 | constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and
283 | destructors do not inherit.
284 |
285 | ## Templates
286 |
287 | ```cpp
288 | template T f(T t);// Overload f for all types
289 | template class X {// Class with type parameter T
290 | X(T t); }; // A constructor
291 | template X::X(T t) {}
292 | // Definition of constructor
293 | X x(3); // An object of type "X of int"
294 | template
295 | // Template with default parameters
296 | ```
297 |
298 | ## Namespaces
299 |
300 | ```cpp
301 | namespace N {class T {};} // Hide name T
302 | N::T t; // Use name T in namespace N
303 | using namespace N; // Make T visible without N::
304 | ```
305 |
306 | ## `memory` (dynamic memory management)
307 |
308 | ```cpp
309 | #include // Include memory (std namespace)
310 | shared_ptr x; // Empty shared_ptr to a integer on heap. Uses reference counting for cleaning up objects.
311 | x = make_shared(12); // Allocate value 12 on heap
312 | shared_ptr y = x; // Copy shared_ptr, implicit changes reference count to 2.
313 | cout << *y; // Dereference y to print '12'
314 | if (y.get() == x.get()) { // Raw pointers (here x == y)
315 | cout << "Same";
316 | }
317 | y.reset(); // Eliminate one owner of object
318 | if (y.get() != x.get()) {
319 | cout << "Different";
320 | }
321 | if (y == nullptr) { // Can compare against nullptr (here returns true)
322 | cout << "Empty";
323 | }
324 | y = make_shared(15); // Assign new value
325 | cout << *y; // Dereference x to print '15'
326 | cout << *x; // Dereference x to print '12'
327 | weak_ptr w; // Create empty weak pointer
328 | w = y; // w has weak reference to y.
329 | if (shared_ptr s = w.lock()) { // Has to be copied into a shared_ptr before usage
330 | cout << *s;
331 | }
332 | unique_ptr z; // Create empty unique pointers
333 | unique_ptr q;
334 | z = make_unique(16); // Allocate int (16) on heap. Only one reference allowed.
335 | q = move(z); // Move reference from z to q.
336 | if (z == nullptr){
337 | cout << "Z null";
338 | }
339 | cout << *q;
340 | shared_ptr r;
341 | r = dynamic_pointer_cast(t); // Converts t to a shared_ptr
342 |
343 | ```
344 |
345 | ## `math.h`, `cmath` (floating point math)
346 |
347 | ```cpp
348 | #include // Include cmath (std namespace)
349 | sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians
350 | asin(x); acos(x); atan(x); // Inverses
351 | atan2(y, x); // atan(y/x)
352 | sinh(x); cosh(x); tanh(x); // Hyperbolic sin, cos, tan functions
353 | exp(x); log(x); log10(x); // e to the x, log base e, log base 10
354 | pow(x, y); sqrt(x); // x to the y, square root
355 | ceil(x); floor(x); // Round up or down (as a double)
356 | fabs(x); fmod(x, y); // Absolute value, x mod y
357 | ```
358 |
359 | ## `assert.h`, `cassert` (Debugging Aid)
360 |
361 | ```cpp
362 | #include // Include iostream (std namespace)
363 | assert(e); // If e is false, print message and abort
364 | #define NDEBUG // (before #include ), turn off assert
365 | ```
366 |
367 | ## `iostream.h`, `iostream` (Replaces `stdio.h`)
368 |
369 | ```cpp
370 | #include // Include iostream (std namespace)
371 | cin >> x >> y; // Read words x and y (any type) from stdin
372 | cout << "x=" << 3 << endl; // Write line to stdout
373 | cerr << x << y << flush; // Write to stderr and flush
374 | c = cin.get(); // c = getchar();
375 | cin.get(c); // Read char
376 | cin.getline(s, n, '\n'); // Read line into char s[n] to '\n' (default)
377 | if (cin) // Good state (not EOF)?
378 | // To read/write any type T:
379 | istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}
380 | ostream& operator<<(ostream& o, const T& x) {return o << ...;}
381 | ```
382 |
383 | ## `fstream.h`, `fstream` (File I/O works like `cin`, `cout` as above)
384 |
385 |
386 | ```cpp
387 | #include // Include filestream (std namespace)
388 | ifstream f1("filename"); // Open text file for reading
389 | if (f1) // Test if open and input available
390 | f1 >> x; // Read object from file
391 | f1.get(s); // Read char or line
392 | f1.getline(s, n); // Read line into string s[n]
393 | ofstream f2("filename"); // Open file for writing
394 | if (f2) f2 << x; // Write to file
395 | ```
396 |
397 | ## `string` (Variable sized character array)
398 |
399 | ```cpp
400 | #include // Include string (std namespace)
401 | string s1, s2="hello"; // Create strings
402 | s1.size(), s2.size(); // Number of characters: 0, 5
403 | s1 += s2 + ' ' + "world"; // Concatenation
404 | s1 == "hello world" // Comparison, also <, >, !=, etc.
405 | s1[0]; // 'h'
406 | s1.substr(m, n); // Substring of size n starting at s1[m]
407 | s1.c_str(); // Convert to const char*
408 | s1 = to_string(12.05); // Converts number to string
409 | getline(cin, s); // Read line ending in '\n'
410 | ```
411 |
412 | ## `vector` (Variable sized array/stack with built in memory allocation)
413 |
414 | ```cpp
415 | #include // Include vector (std namespace)
416 | vector a(10); // a[0]..a[9] are int (default size is 0)
417 | vector b{1,2,3}; // Create vector with values 1,2,3
418 | a.size(); // Number of elements (10)
419 | a.push_back(3); // Increase size to 11, a[10]=3
420 | a.back()=4; // a[10]=4;
421 | a.pop_back(); // Decrease size by 1
422 | a.front(); // a[0];
423 | a[20]=1; // Crash: not bounds checked
424 | a.at(20)=1; // Like a[20] but throws out_of_range()
425 | for (int& p : a)
426 | p=0; // C++11: Set all elements of a to 0
427 | for (vector::iterator p=a.begin(); p!=a.end(); ++p)
428 | *p=0; // C++03: Set all elements of a to 0
429 | vector b(a.begin(), a.end()); // b is copy of a
430 | vector c(n, x); // c[0]..c[n-1] init to x
431 | T d[10]; vector e(d, d+10); // e is initialized from d
432 | ```
433 |
434 | ## `deque` (Array stack queue)
435 |
436 | `deque` is like `vector`, but also supports:
437 |
438 | ```cpp
439 | #include // Include deque (std namespace)
440 | a.push_front(x); // Puts x at a[0], shifts elements toward back
441 | a.pop_front(); // Removes a[0], shifts toward front
442 | ```
443 |
444 | ## `utility` (pair)
445 |
446 | ```cpp
447 | #include // Include utility (std namespace)
448 | pair a("hello", 3); // A 2-element struct
449 | a.first; // "hello"
450 | a.second; // 3
451 | ```
452 |
453 | ## `map` (associative array - usually implemented as binary search trees - avg. time complexity: O(log n))
454 |
455 | ```cpp
456 | #include