{"id":13436667,"url":"https://github.com/mortennobel/cpp-cheatsheet","last_synced_at":"2025-05-14T23:06:23.389Z","repository":{"id":39620486,"uuid":"66033005","full_name":"mortennobel/cpp-cheatsheet","owner":"mortennobel","description":"Modern C++ Cheatsheet","archived":false,"fork":false,"pushed_at":"2023-12-15T08:48:20.000Z","size":45,"stargazers_count":3358,"open_issues_count":20,"forks_count":717,"subscribers_count":61,"default_branch":"master","last_synced_at":"2025-04-13T19:50:00.930Z","etag":null,"topics":["cheatsheet","cpp","cpp11","cpp14"],"latest_commit_sha":null,"homepage":null,"language":"C++","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/mortennobel.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null}},"created_at":"2016-08-18T21:51:44.000Z","updated_at":"2025-04-13T18:42:46.000Z","dependencies_parsed_at":"2024-01-06T01:18:21.608Z","dependency_job_id":"8b012b0f-8129-45aa-b786-d13dd6a92bce","html_url":"https://github.com/mortennobel/cpp-cheatsheet","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mortennobel%2Fcpp-cheatsheet","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mortennobel%2Fcpp-cheatsheet/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mortennobel%2Fcpp-cheatsheet/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/mortennobel%2Fcpp-cheatsheet/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/mortennobel","download_url":"https://codeload.github.com/mortennobel/cpp-cheatsheet/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254243360,"owners_count":22038046,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","cpp","cpp11","cpp14"],"created_at":"2024-07-31T03:00:51.106Z","updated_at":"2025-05-14T23:06:18.366Z","avatar_url":"https://github.com/mortennobel.png","language":"C++","readme":"\u003ca href=\"https://github.com/mortennobel/cpp-cheatsheet\"\u003e\u003cimg align=\"right\" src=\"https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67\" alt=\"Fork me on GitHub\" data-canonical-src=\"https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png\"\u003e\u003c/a\u003e\n\n# C++ QUICK REFERENCE / C++ CHEATSHEET\nBased on \u003ca href=\"http://www.pa.msu.edu/~duxbury/courses/phy480/Cpp_refcard.pdf\"\u003ePhillip M. Duxbury's C++ Cheatsheet\u003c/a\u003e and edited by Morten Nobel-Jørgensen.\nThe cheatsheet focus is both on the language as well as common classes from the standard library.\nC++11 additions is inspired by \u003ca href=\"https://isocpp.org/blog/2012/12/c11-a-cheat-sheet-alex-sinyakov\"\u003eISOCPP.org C++11 Cheatsheet\u003c/a\u003e).\n\nThe goal is to give a concise overview of basic, modern C++ (C++14).\n\nThe document is hosted on https://github.com/mortennobel/cpp-cheatsheet. Any comments and feedback are appreciated.\n\n## Preprocessor\n\n```cpp\n                            // Comment to end of line\n                            /* Multi-line comment */\n#include  \u003cstdio.h\u003e         // Insert standard header file\n#include \"myfile.h\"         // Insert file in current directory\n#define X some text         // Replace X with some text\n#define F(a,b) a+b          // Replace F(1,2) with 1+2\n#define X \\\n some text                  // Multiline definition\n#undef X                    // Remove definition\n#if defined(X)              // Conditional compilation (#ifdef X)\n#else                       // Optional (#ifndef X or #if !defined(X))\n#endif                      // Required after #if, #ifdef\n```\n\n## Literals\n\n```cpp\n255, 0377, 0xff             // Integers (decimal, octal, hex)\n2147483647L, 0x7fffffffl    // Long (32-bit) integers\n123.0, 1.23e2               // double (real) numbers\n'a', '\\141', '\\x61'         // Character (literal, octal, hex)\n'\\n', '\\\\', '\\'', '\\\"'      // Newline, backslash, single quote, double quote\n\"string\\n\"                  // Array of characters ending with newline and \\0\n\"hello\" \"world\"             // Concatenated strings\ntrue, false                 // bool constants 1 and 0\nnullptr                     // Pointer type with the address of 0\n```\n\n## Declarations\n\n```cpp\nint x;                      // Declare x to be an integer (value undefined)\nint x=255;                  // Declare and initialize x to 255\nshort s; long l;            // Usually 16 or 32 bit integer (int may be either)\nchar c='a';                 // Usually 8 bit character\nunsigned char u=255;\nsigned char s=-1;           // char might be either\nunsigned long x =\n  0xffffffffL;              // short, int, long are signed\nfloat f; double d;          // Single or double precision real (never unsigned)\nbool b=true;                // true or false, may also use int (1 or 0)\nint a, b, c;                // Multiple declarations\nint a[10];                  // Array of 10 ints (a[0] through a[9])\nint a[]={0,1,2};            // Initialized array (or a[3]={0,1,2}; )\nint a[2][2]={{1,2},{4,5}};  // Array of array of ints\nchar s[]=\"hello\";           // String (6 elements including '\\0')\nstd::string s = \"Hello\"     // Creates string object with value \"Hello\"\nstd::string s = R\"(Hello\nWorld)\";                    // Creates string object with value \"Hello\\nWorld\"\nint* p;                     // p is a pointer to (address of) int\nchar* s=\"hello\";            // s points to unnamed array containing \"hello\"\nvoid* p=nullptr;            // Address of untyped memory (nullptr is 0)\nint\u0026 r=x;                   // r is a reference to (alias of) int x\nenum weekend {SAT,SUN};     // weekend is a type with values SAT and SUN\nenum weekend day;           // day is a variable of type weekend\nenum weekend{SAT=0,SUN=1};  // Explicit representation as int\nenum {SAT,SUN} day;         // Anonymous enum\nenum class Color {Red,Blue};// Color is a strict type with values Red and Blue\nColor x = Color::Red;       // Assign Color x to red\ntypedef String char*;       // String s; means char* s;\nconst int c=3;              // Constants must be initialized, cannot assign to\nconst int* p=a;             // Contents of p (elements of a) are constant\nint* const p=a;             // p (but not contents) are constant\nconst int* const p=a;       // Both p and its contents are constant\nconst int\u0026 cr=x;            // cr cannot be assigned to change x\nint8_t,uint8_t,int16_t,\nuint16_t,int32_t,uint32_t,\nint64_t,uint64_t            // Fixed length standard types\nauto it = m.begin();        // Declares it to the result of m.begin()\nauto const param = config[\"param\"];\n                            // Declares it to the const result\nauto\u0026 s = singleton::instance();\n                            // Declares it to a reference of the result\n```\n\n## STORAGE Classes\n\n```cpp\nint x;                      // Auto (memory exists only while in scope)\nstatic int x;               // Global lifetime even if local scope\nextern int x;               // Information only, declared elsewhere\n```\n\n## Statements\n\n```cpp\nx=y;                        // Every expression is a statement\nint x;                      // Declarations are statements\n;                           // Empty statement\n{                           // A block is a single statement\n    int x;                  // Scope of x is from declaration to end of block\n}\nif (x) a;                   // If x is true (not 0), evaluate a\nelse if (y) b;              // If not x and y (optional, may be repeated)\nelse c;                     // If not x and not y (optional)\n\nwhile (x) a;                // Repeat 0 or more times while x is true\n\nfor (x; y; z) a;            // Equivalent to: x; while(y) {a; z;}\n\nfor (x : y) a;              // Range-based for loop e.g.\n                            // for (auto\u0026 x in someList) x.y();\n\ndo a; while (x);            // Equivalent to: a; while(x) a;\n\nswitch (x) {                // x must be int\n    case X1: a;             // If x == X1 (must be a const), jump here\n    case X2: b;             // Else if x == X2, jump here\n    default: c;             // Else jump here (optional)\n}\nbreak;                      // Jump out of while, do, or for loop, or switch\ncontinue;                   // Jump to bottom of while, do, or for loop\nreturn x;                   // Return x from function to caller\ntry { a; }\ncatch (T t) { b; }          // If a throws a T, then jump here\ncatch (...) { c; }          // If a throws something else, jump here\n```\n\n## Functions\n\n```cpp\nint f(int x, int y);        // f is a function taking 2 ints and returning int\nvoid f();                   // f is a procedure taking no arguments\nvoid f(int a=0);            // f() is equivalent to f(0)\nf();                        // Default return type is int\ninline f();                 // Optimize for speed\nf() { statements; }         // Function definition (must be global)\nT operator+(T x, T y);      // a+b (if type T) calls operator+(a, b)\nT operator-(T x);           // -a calls function operator-(a)\nT operator++(int);          // postfix ++ or -- (parameter ignored)\nextern \"C\" {void f();}      // f() was compiled in C\n```\n\nFunction parameters and return values may be of any type. A function must either be declared or defined before\nit is used. It may be declared first and defined later. Every program consists of a set of a set of global variable\ndeclarations and a set of function definitions (possibly in separate files), one of which must be:\n\n```cpp\nint main()  { statements... }     // or\nint main(int argc, char* argv[]) { statements... }\n```\n\n`argv` is an array of `argc` strings from the command line.\nBy convention, `main` returns status `0` if successful, `1` or higher for errors.\n\nFunctions with different parameters may have the same name (overloading). Operators except `::` `.` `.*` `?:` may be overloaded.\nPrecedence order is not affected. New operators may not be created.\n\n## Expressions\n\nOperators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All\nothers are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time\nchecks for arrays out of bounds, invalid pointers, etc.\n\n```cpp\nT::X                        // Name X defined in class T\nN::X                        // Name X defined in namespace N\n::X                         // Global name X\n\nt.x                         // Member x of struct or class t\np-\u003e x                       // Member x of struct or class pointed to by p\na[i]                        // i'th element of array a\nf(x,y)                      // Call to function f with arguments x and y\nT(x,y)                      // Object of class T initialized with x and y\nx++                         // Add 1 to x, evaluates to original x (postfix)\nx--                         // Subtract 1 from x, evaluates to original x\ntypeid(x)                   // Type of x\ntypeid(T)                   // Equals typeid(x) if x is a T\ndynamic_cast\u003c T\u003e(x)         // Converts x to a T, checked at run time.\nstatic_cast\u003c T\u003e(x)          // Converts x to a T, not checked\nreinterpret_cast\u003c T\u003e(x)     // Interpret bits of x as a T\nconst_cast\u003c T\u003e(x)           // Converts x to same type T but not const\n\nsizeof x                    // Number of bytes used to represent object x\nsizeof(T)                   // Number of bytes to represent type T\n++x                         // Add 1 to x, evaluates to new value (prefix)\n--x                         // Subtract 1 from x, evaluates to new value\n~x                          // Bitwise complement of x\n!x                          // true if x is 0, else false (1 or 0 in C)\n-x                          // Unary minus\n+x                          // Unary plus (default)\n\u0026x                          // Address of x\n*p                          // Contents of address p (*\u0026x equals x)\nnew T                       // Address of newly allocated T object\nnew T(x, y)                 // Address of a T initialized with x, y\nnew T[x]                    // Address of allocated n-element array of T\ndelete p                    // Destroy and free object at address p\ndelete[] p                  // Destroy and free array of objects at p\n(T) x                       // Convert x to T (obsolete, use .._cast\u003cT\u003e(x))\n\nx * y                       // Multiply\nx / y                       // Divide (integers round toward 0)\nx % y                       // Modulo (result has sign of x)\n\nx + y                       // Add, or \\\u0026x[y]\nx - y                       // Subtract, or number of elements from *x to *y\nx \u003c\u003c y                      // x shifted y bits to left (x * pow(2, y))\nx \u003e\u003e y                      // x shifted y bits to right (x / pow(2, y))\n\nx \u003c y                       // Less than\nx \u003c= y                      // Less than or equal to\nx \u003e y                       // Greater than\nx \u003e= y                      // Greater than or equal to\n\nx \u0026 y                       // Bitwise and (3 \u0026 6 is 2)\nx ^ y                       // Bitwise exclusive or (3 ^ 6 is 5)\nx | y                       // Bitwise or (3 | 6 is 7)\nx \u0026\u0026 y                      // x and then y (evaluates y only if x (not 0))\nx || y                      // x or else y (evaluates y only if x is false (0))\nx = y                       // Assign y to x, returns new value of x\nx += y                      // x = x + y, also -= *= /= \u003c\u003c= \u003e\u003e= \u0026= |= ^=\nx ? y : z                   // y if x is true (nonzero), else z\nthrow x                     // Throw exception, aborts if not caught\nx , y                       // evaluates x and y, returns y (seldom used)\n```\n\n## Classes\n\n```cpp\nclass T {                   // A new type\nprivate:                    // Section accessible only to T's member functions\nprotected:                  // Also accessible to classes derived from T\npublic:                     // Accessible to all\n    int x;                  // Member data\n    void f();               // Member function\n    void g() {return;}      // Inline member function\n    void h() const;         // Does not modify any data members\n    int operator+(int y);   // t+y means t.operator+(y)\n    int operator-();        // -t means t.operator-()\n    T(): x(1) {}            // Constructor with initialization list\n    T(const T\u0026 t): x(t.x) {}// Copy constructor\n    T\u0026 operator=(const T\u0026 t)\n    {x=t.x; return *this; } // Assignment operator\n    ~T();                   // Destructor (automatic cleanup routine)\n    explicit T(int a);      // Allow t=T(3) but not t=3\n    T(float x): T((int)x) {}// Delegate constructor to T(int)\n    operator int() const\n    {return x;}             // Allows int(t)\n    friend void i();        // Global function i() has private access\n    friend class U;         // Members of class U have private access\n    static int y;           // Data shared by all T objects\n    static void l();        // Shared code.  May access y but not x\n    class Z {};             // Nested class T::Z\n    typedef int V;          // T::V means int\n};\nvoid T::f() {               // Code for member function f of class T\n    this-\u003ex = x;}           // this is address of self (means x=x;)\nint T::y = 2;               // Initialization of static member (required)\nT::l();                     // Call to static member\nT t;                        // Create object t implicit call constructor\nt.f();                      // Call method f on object t\n\nstruct T {                  // Equivalent to: class T { public:\n  virtual void i();         // May be overridden at run time by derived class\n  virtual void g()=0; };    // Must be overridden (pure virtual)\nclass U: public T {         // Derived class U inherits all members of base T\n  public:\n  void g(int) override; };  // Override method g\nclass V: private T {};      // Inherited members of T become private\nclass W: public T, public U {};\n                            // Multiple inheritance\nclass X: public virtual T {};\n                            // Classes derived from X have base T directly\n```\n\nAll classes have a default copy constructor, assignment operator, and destructor, which perform the\ncorresponding operations on each data member and each base class as shown above. There is also a default no-argument\nconstructor (required to create arrays) if the class has no constructors. Constructors, assignment, and\ndestructors do not inherit.\n\n## Templates\n\n```cpp\ntemplate \u003cclass T\u003e T f(T t);// Overload f for all types\ntemplate \u003cclass T\u003e class X {// Class with type parameter T\n  X(T t); };                // A constructor\ntemplate \u003cclass T\u003e X\u003cT\u003e::X(T t) {}\n                            // Definition of constructor\nX\u003cint\u003e x(3);                // An object of type \"X of int\"\ntemplate \u003cclass T, class U=T, int n=0\u003e\n                            // Template with default parameters\n```\n\n## Namespaces\n\n```cpp\nnamespace N {class T {};}   // Hide name T\nN::T t;                     // Use name T in namespace N\nusing namespace N;          // Make T visible without N::\n```\n\n## `memory` (dynamic memory management)\n\n```cpp\n#include \u003cmemory\u003e           // Include memory (std namespace)\nshared_ptr\u003cint\u003e x;          // Empty shared_ptr to a integer on heap. Uses reference counting for cleaning up objects.\nx = make_shared\u003cint\u003e(12);   // Allocate value 12 on heap\nshared_ptr\u003cint\u003e y = x;      // Copy shared_ptr, implicit changes reference count to 2.\ncout \u003c\u003c *y;                 // Dereference y to print '12'\nif (y.get() == x.get()) {   // Raw pointers (here x == y)\n    cout \u003c\u003c \"Same\";  \n}  \ny.reset();                  // Eliminate one owner of object\nif (y.get() != x.get()) { \n    cout \u003c\u003c \"Different\";  \n}  \nif (y == nullptr) {         // Can compare against nullptr (here returns true)\n    cout \u003c\u003c \"Empty\";  \n}  \ny = make_shared\u003cint\u003e(15);   // Assign new value\ncout \u003c\u003c *y;                 // Dereference x to print '15'\ncout \u003c\u003c *x;                 // Dereference x to print '12'\nweak_ptr\u003cint\u003e w;            // Create empty weak pointer\nw = y;                      // w has weak reference to y.\nif (shared_ptr\u003cint\u003e s = w.lock()) { // Has to be copied into a shared_ptr before usage\n    cout \u003c\u003c *s;\n}\nunique_ptr\u003cint\u003e z;          // Create empty unique pointers\nunique_ptr\u003cint\u003e q;\nz = make_unique\u003cint\u003e(16);   // Allocate int (16) on heap. Only one reference allowed.\nq = move(z);                // Move reference from z to q.\nif (z == nullptr){\n    cout \u003c\u003c \"Z null\";\n}\ncout \u003c\u003c *q;\nshared_ptr\u003cB\u003e r;\nr = dynamic_pointer_cast\u003cB\u003e(t); // Converts t to a shared_ptr\u003cB\u003e\n\n```\n\n## `math.h`, `cmath` (floating point math)\n\n```cpp\n#include \u003ccmath\u003e            // Include cmath (std namespace)\nsin(x); cos(x); tan(x);     // Trig functions, x (double) is in radians\nasin(x); acos(x); atan(x);  // Inverses\natan2(y, x);                // atan(y/x)\nsinh(x); cosh(x); tanh(x);  // Hyperbolic sin, cos, tan functions\nexp(x); log(x); log10(x);   // e to the x, log base e, log base 10\npow(x, y); sqrt(x);         // x to the y, square root\nceil(x); floor(x);          // Round up or down (as a double)\nfabs(x); fmod(x, y);        // Absolute value, x mod y\n```\n\n## `assert.h`, `cassert` (Debugging Aid)\n\n```cpp\n#include \u003ccassert\u003e        // Include iostream (std namespace)\nassert(e);                // If e is false, print message and abort\n#define NDEBUG            // (before #include \u003cassert.h\u003e), turn off assert\n```\n\n## `iostream.h`, `iostream` (Replaces `stdio.h`)\n\n```cpp\n#include \u003ciostream\u003e         // Include iostream (std namespace)\ncin \u003e\u003e x \u003e\u003e y;              // Read words x and y (any type) from stdin\ncout \u003c\u003c \"x=\" \u003c\u003c 3 \u003c\u003c endl;  // Write line to stdout\ncerr \u003c\u003c x \u003c\u003c y \u003c\u003c flush;    // Write to stderr and flush\nc = cin.get();              // c = getchar();\ncin.get(c);                 // Read char\ncin.getline(s, n, '\\n');    // Read line into char s[n] to '\\n' (default)\nif (cin)                    // Good state (not EOF)?\n                            // To read/write any type T:\nistream\u0026 operator\u003e\u003e(istream\u0026 i, T\u0026 x) {i \u003e\u003e ...; x=...; return i;}\nostream\u0026 operator\u003c\u003c(ostream\u0026 o, const T\u0026 x) {return o \u003c\u003c ...;}\n```\n\n## `fstream.h`, `fstream` (File I/O works like `cin`, `cout` as above)\n\n\n```cpp\n#include \u003cfstream\u003e          // Include filestream (std namespace)\nifstream f1(\"filename\");    // Open text file for reading\nif (f1)                     // Test if open and input available\n    f1 \u003e\u003e x;                // Read object from file\nf1.get(s);                  // Read char or line\nf1.getline(s, n);           // Read line into string s[n]\nofstream f2(\"filename\");    // Open file for writing\nif (f2) f2 \u003c\u003c x;            // Write to file\n```\n\n## `string` (Variable sized character array)\n\n```cpp\n#include \u003cstring\u003e         // Include string (std namespace)\nstring s1, s2=\"hello\";    // Create strings\ns1.size(), s2.size();     // Number of characters: 0, 5\ns1 += s2 + ' ' + \"world\"; // Concatenation\ns1 == \"hello world\"       // Comparison, also \u003c, \u003e, !=, etc.\ns1[0];                    // 'h'\ns1.substr(m, n);          // Substring of size n starting at s1[m]\ns1.c_str();               // Convert to const char*\ns1 = to_string(12.05);    // Converts number to string\ngetline(cin, s);          // Read line ending in '\\n'\n```\n\n## `vector` (Variable sized array/stack with built in memory allocation)\n\n```cpp\n#include \u003cvector\u003e         // Include vector (std namespace)\nvector\u003cint\u003e a(10);        // a[0]..a[9] are int (default size is 0)\nvector\u003cint\u003e b{1,2,3};        // Create vector with values 1,2,3\na.size();                 // Number of elements (10)\na.push_back(3);           // Increase size to 11, a[10]=3\na.back()=4;               // a[10]=4;\na.pop_back();             // Decrease size by 1\na.front();                // a[0];\na[20]=1;                  // Crash: not bounds checked\na.at(20)=1;               // Like a[20] but throws out_of_range()\nfor (int\u0026 p : a)\n  p=0;                    // C++11: Set all elements of a to 0\nfor (vector\u003cint\u003e::iterator p=a.begin(); p!=a.end(); ++p)\n  *p=0;                   // C++03: Set all elements of a to 0\nvector\u003cint\u003e b(a.begin(), a.end());  // b is copy of a\nvector\u003cT\u003e c(n, x);        // c[0]..c[n-1] init to x\nT d[10]; vector\u003cT\u003e e(d, d+10);      // e is initialized from d\n```\n\n## `deque` (Array stack queue)\n\n`deque\u003cT\u003e` is like `vector\u003cT\u003e`, but also supports:\n\n```cpp\n#include \u003cdeque\u003e          // Include deque (std namespace)\na.push_front(x);          // Puts x at a[0], shifts elements toward back\na.pop_front();            // Removes a[0], shifts toward front\n```\n\n## `utility` (pair)\n\n```cpp\n#include \u003cutility\u003e        // Include utility (std namespace)\npair\u003cstring, int\u003e a(\"hello\", 3);  // A 2-element struct\na.first;                  // \"hello\"\na.second;                 // 3\n```\n\n## `map` (associative array - usually implemented as binary search trees - avg. time complexity: O(log n))\n\n```cpp\n#include \u003cmap\u003e            // Include map (std namespace)\nmap\u003cstring, int\u003e a;       // Map from string to int\na[\"hello\"] = 3;           // Add or replace element a[\"hello\"]\nfor (auto\u0026 p:a)\n    cout \u003c\u003c p.first \u003c\u003c p.second;  // Prints hello, 3\na.size();                 // 1\n```\n\n## `unordered_map` (associative array - usually implemented as hash table - avg. time complexity: O(1))\n\n```cpp\n#include \u003cunordered_map\u003e  // Include map (std namespace)\nunordered_map\u003cstring, int\u003e a; // Map from string to int\na[\"hello\"] = 3;           // Add or replace element a[\"hello\"]\nfor (auto\u0026 p:a)\n    cout \u003c\u003c p.first \u003c\u003c p.second;  // Prints hello, 3\na.size();                 // 1\n```\n\n## `set` (store unique elements - usually implemented as binary search trees - avg. time complexity: O(log n))\n\n```cpp\n#include \u003cset\u003e            // Include set (std namespace)\nset\u003cint\u003e s;               // Set of integers\ns.insert(123);            // Add element to set\nif (s.find(123) != s.end()) // Search for an element\n    s.erase(123);\ncout \u003c\u003c s.size();         // Number of elements in set\n```\n\n## `unordered_set` (store unique elements - usually implemented as a hash set - avg. time complexity: O(1))\n\n```cpp\n#include \u003cunordered_set\u003e  // Include set (std namespace)\nunordered_set\u003cint\u003e s;     // Set of integers\ns.insert(123);            // Add element to set\nif (s.find(123) != s.end()) // Search for an element\n    s.erase(123);\ncout \u003c\u003c s.size();         // Number of elements in set\n```\n\n## `algorithm` (A collection of 60 algorithms on sequences with iterators)\n\n```cpp\n#include \u003calgorithm\u003e      // Include algorithm (std namespace)\nmin(x, y); max(x, y);     // Smaller/larger of x, y (any type defining \u003c)\nswap(x, y);               // Exchange values of variables x and y\nsort(a, a+n);             // Sort array a[0]..a[n-1] by \u003c\nsort(a.begin(), a.end()); // Sort vector or deque\nreverse(a.begin(), a.end()); // Reverse vector or deque\n```\n\n## `chrono` (Time related library)\n```cpp\n#include \u003cchrono\u003e         // Include chrono\nusing namespace std::chrono; // Use namespace\nauto from =               // Get current time_point\n  high_resolution_clock::now();\n// ... do some work       \nauto to =                 // Get current time_point\n  high_resolution_clock::now();\nusing ms =                // Define ms as floating point duration\n  duration\u003cfloat, milliseconds::period\u003e;\n                          // Compute duration in milliseconds\ncout \u003c\u003c duration_cast\u003cms\u003e(to - from)\n  .count() \u003c\u003c \"ms\";\n```\n\n## `thread` (Multi-threading library)\n```cpp\n#include \u003cthread\u003e         // Include thread\nunsigned c = \n  hardware_concurrency(); // Hardware threads (or 0 for unknown)\nauto lambdaFn = [](){     // Lambda function used for thread body\n    cout \u003c\u003c \"Hello multithreading\";\n};\nthread t(lambdaFn);       // Create and run thread with lambda\nt.join();                 // Wait for t finishes\n\n// --- shared resource example ---\nmutex mut;                         // Mutex for synchronization\ncondition_variable cond;           // Shared condition variable\nconst char* sharedMes              // Shared resource\n  = nullptr;\nauto pingPongFn =                  // thread body (lambda). Print someone else's message\n  [\u0026](const char* mes){\n    while (true){\n      unique_lock\u003cmutex\u003e lock(mut);// locks the mutex \n      do {                \n        cond.wait(lock, [\u0026](){     // wait for condition to be true (unlocks while waiting which allows other threads to modify)        \n          return sharedMes != mes; // statement for when to continue\n        });\n      } while (sharedMes == mes);  // prevents spurious wakeup\n      cout \u003c\u003c sharedMes \u003c\u003c endl;\n      sharedMes = mes;       \n      lock.unlock();               // no need to have lock on notify \n      cond.notify_all();           // notify all condition has changed\n    }\n  };\nsharedMes = \"ping\";\nthread t1(pingPongFn, sharedMes);  // start example with 3 concurrent threads\nthread t2(pingPongFn, \"pong\");\nthread t3(pingPongFn, \"boing\");\n```\n\n## `future` (thread support library)\n```cpp\n#include \u003cfuture\u003e         // Include future\nfunction\u003cint(int)\u003e fib =  // Create lambda function\n  [\u0026](int i){\n    if (i \u003c= 1){\n      return 1;\n    }\n    return fib(i-1) \n         + fib(i-2);\n  };\nfuture\u003cint\u003e fut =         // result of async function\n  async(launch::async, fib, 4); // start async function in other thread\n// do some other work \ncout \u003c\u003c fut.get();        // get result of async function. Wait if needed.\n```\n","funding_links":[],"categories":["HarmonyOS","▶️ Content","Index","Courses","C/C++程序设计","C++"],"sub_categories":["Windows Manager","CheatSheets","资源传输下载"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmortennobel%2Fcpp-cheatsheet","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmortennobel%2Fcpp-cheatsheet","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmortennobel%2Fcpp-cheatsheet/lists"}