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