{"id":18708627,"url":"https://github.com/va1da5/cpp-practice","last_synced_at":"2025-08-21T00:06:20.261Z","repository":{"id":106644964,"uuid":"578347619","full_name":"va1da5/cpp-practice","owner":"va1da5","description":"Personal notes from C++ learning journey","archived":false,"fork":false,"pushed_at":"2023-01-22T16:09:00.000Z","size":125,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-05-19T07:35:25.169Z","etag":null,"topics":["cheatsheet","cpp","notes","reference"],"latest_commit_sha":null,"homepage":"","language":"HTML","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/va1da5.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,"publiccode":null,"codemeta":null}},"created_at":"2022-12-14T21:01:58.000Z","updated_at":"2023-02-04T08:52:46.000Z","dependencies_parsed_at":"2024-01-11T11:05:08.074Z","dependency_job_id":null,"html_url":"https://github.com/va1da5/cpp-practice","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/va1da5/cpp-practice","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/va1da5%2Fcpp-practice","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/va1da5%2Fcpp-practice/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/va1da5%2Fcpp-practice/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/va1da5%2Fcpp-practice/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/va1da5","download_url":"https://codeload.github.com/va1da5/cpp-practice/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/va1da5%2Fcpp-practice/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":271405573,"owners_count":24753799,"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","status":"online","status_checked_at":"2025-08-20T02:00:09.606Z","response_time":69,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"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","notes","reference"],"created_at":"2024-11-07T12:24:19.990Z","updated_at":"2025-08-21T00:06:20.242Z","avatar_url":"https://github.com/va1da5.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"# C++ Notes\n\nThis repository contains personal notes on learning the C++ programming language. It covers a range of topics, including basic syntax, data types, and common functions and libraries. The notes are intended to serve as a reference for anyone looking to learn or brush up on their C++ skills.\n\n## Initial Setup\n\n```bash\n# for Fedora\ndnf install gcc-c++ gdb clang-tools-extra\n```\n\n## Quick Reference\n\n\n### Data Types\n\n```cpp\n\nbool x = true;                                // 1 byte, values 0, 1\nchar a = 'a';                                 // 1 byte, values -127 to 127 or 0 to 255, usually 8 bit character\nunsigned char b = 0xff;                       // 1 byte, values 0 to 255\nsigned char c = -1;                           // 1 byte, values -127 to 127\nint d = 1234;                                 // 4 bytes, values -2147483648 to 2147483647\nunsigned int e = 1;                           // 4 bytes, values 0 to 4294967295\nsigned int f = -127;                          // 4 bytes, values -2147483648 to 2147483647\nshort int g = -256;                           // 2 bytes, values -32768 to 32767\nunsigned short int h = 65'535;                // 2 bytes, values 0 to 65,535\nsigned short int i = 32'767;                  // 2 bytes, values -32768 to 32767\nlong int j = 0xffffffffffffffL;               // 8 bytes, values -9223372036854775808 to 9223372036854775807\nsigned long int k = -0xffffffffffffff;        // 8 bytes, values -9223372036854775808 to 9223372036854775807\nunsigned long int l = 0xffffffffffffffffUL;   // 8 bytes, values 0 to 18446744073709551615\nlong long int m = -0xfffffffffffffff;         // 8 bytes, values -(2^63) to (2^63)-1\nunsigned long long int n = 0xfffffffffffffff; // 8 bytes, 0 to 18,446,744,073,709,551,615\nfloat o = 2.5;                                // 4 bytes, single precision real (never unsigned)\ndouble p = 3.14;                              // 8 bytes, double precision real (never unsigned)\nlong double q = 6.62607015e-34;               // 12 bytes\nwchar_t r = L'ם';                             // 2 or 4 bytes, values 1 wide character\n\nint8_t s = 0x7f;                              // 1 byte, values -127 to 127\nint16_t t = 0x7fff;                           // 2 bytes, values -32768 to 32767\nint32_t u = 0x7fffffff;                       // 4 bytes, values -2147483648 to 2147483647\nint64_t v = 0x7fffffffffffffff;               // 8 bytes, values -9223372036854775808 to 9223372036854775807\n\nuint8_t us = 0xff;                            // 1 byte, values 0 to 255\nuint16_t ut = 0xffff;                         // 2 bytes, values 0 to 65,535\nuint32_t uu = 0xffffffff;                     // 4 bytes, values 0 to 4294967295\nuint64_t uv = 0xffffffffffffffff;             // 8 bytes, values 0 to 18446744073709551615\n\n```\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\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 = 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\"]; // Declares it to the const result\nauto\u0026 s = singleton::instance();    // 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\n{                           // A block is a single statement\n    int x;                  // Scope of x is from declaration to end of block\n}\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}\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\n### Expressions\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\n\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 {}; // Multiple inheritance\nclass X: public virtual T {};   // Classes derived from X have base T directly\n```\n\nAll classes have a default copy constructor, assignment operator, and destructor, which perform the corresponding operations on each data member and each base class as shown above. There is also a default no-argument constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and destructors 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\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`\n\nDynamic 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### `string`\n\nVariable 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### `array`\n\n\u003cimg src=\"./images/array_thumb.svg\" alt=\"array\" height=\"50px\"\u003e\n\nFixed-size contiguous array with overhead-free random access.\nExcels in fast traversal and good for linear searches.\n`size` has to be a constant expression (= known at compile time).\nDoes not support size-changing operations (resize, insert, erase, …).\nPotentially slow if element type has high copy/assignment cost (reordering elements requires copying/moving them)\n\n```cpp\n#include \u003carray\u003e        // Include vector (std namespace)\nstd::array\u003cint,6\u003e a {4,8,15,16,23,42};\n                        // Create array with values 4,8,15,16..\na.size();               // Number of elements (6)\na[0];                   // 4\na[3];                   // 16\na.front();              // 4\na.back();               // 42\n\n```\n\n### `vector`\n\n\n\u003cimg src=\"./images/vector_thumb.svg\" alt=\"vector\" height=\"50px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/vector.png)\n\nDynamic contiguous array/stack with built in memory allocation.\nAmortized O(1) growth strategy.\nC++'s default container.\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` Double Ended Queue\n\n\u003cimg src=\"./images/deque_thumb.svg\" alt=\"deque\" height=\"50px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/deque.png)\n\nConstant-time random access (extremely small overhead).\nGood insertion and deletion performance at both ends.\n\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### `list` Doubly-linked List\n\n\u003cimg src=\"./images/list_thumb.svg\" alt=\"list\" height=\"60px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/list.png)\n\nDoubly-linked list; O(1) insert, erase \u0026 splicing;\nin practice often slower than vector.\nRestructuring operations don't require elements to be moved/copied (good for storing large objects with high copy/assignment cost).\nConstant-time splicing (of complete lists).\n\n\n```cpp\n#include \u003clist\u003e                 // Include list (std namespace)\nstd::list\u003cint\u003e l {3};\nl.push_back(2);                 // Adds a new element ‘2’ at the end of the list\nl.push_front(4);                // Adds a new element ‘4’ at the beginning of the list\nl.splice(begin(l)+1,\n         list\u003cint\u003e{8, 4, 7});   // Used to transfer elements from one list to another\nl.reverse();                    // Reverses the list\nl.sort();                       // Sorts the list in increasing order\nl.unique();                     // Removes all duplicate consecutive elements from the list\n```\n\n### `forward_list` Singly-linked List\n\n\u003cimg src=\"./images/forward_list_thumb.svg\" alt=\"forward_list\" height=\"60px\"\u003e]\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/forward_list.png)\n\n\nSingly-linked list; `O(1)` insert, erase \u0026 splicing; needs less memory than list; in practice often slower than vector.\n\n```cpp\n#include \u003cforward_list\u003e                 // Include list (std namespace)\nstd::forward_list\u003cint\u003e l {23,42,4};     // Create list with values 23,42,4\n\nl.insert_after(begin(l), 5);            // Puts values into second position overwriting 42\nl.insert_after(before_begin(l), 88);    // Puts value in the first position overwriting 23\nl.erase_after(begin(l));                // Removes second element\n```\n\n\n### `utility` (pair)\n\n```cpp\n#include \u003cutility\u003e        // Include utility (std namespace)\npair\u003cstring, int\u003e a(\"hello\", 7);  // A 2-element struct\na.first;                  // \"hello\"\na.second;                 // 7\n```\n\n### `map`\n\n\u003cimg src=\"./images/map_thumb.svg\" alt=\"map\" height=\"150px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/map.png)\n\nAssociative 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`\n\n\u003cimg src=\"./images/unordered_map_thumb.svg\" alt=\"unordered_map\" height=\"150px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/unordered_map.png)\n\nAssociative 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` Ordered Sets \n\n\u003cimg src=\"./images/set_thumb.svg\" alt=\"set\" height=\"150px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/set.png)\n\nStore 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\n### `unordered_set`\n\n\u003cimg src=\"./images/unordered_set_thumb.svg\" alt=\"unordered_set\" height=\"150px\"\u003e\n\n[Cheat sheet](https://hackingcpp.com/cpp/std/unordered_set.png)\n\nStore 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### `math.h`, `cmath`\n\nFloating 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`\n\nDebugging 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`\n\nReplaces 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`\n\nFile I/O works like cin, cout as above.\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### `algorithm`\n\nA 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`\n\nTime related library.\n\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`\n\nMulti-threading library.\n\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`\n\nThread support library.\n\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\n---\n\n## References\n\n- [📺️ C++ Tutorial for Beginners - Learn C++ in 1 Hour](https://www.youtube.com/watch?v=ZzaPdXTrSb8)\n- [Using C++ on Linux in VS Code](https://code.visualstudio.com/docs/cpp/config-linux)\n- [Visual Studio Code C++ December 2021 Update: clang-tidy](https://devblogs.microsoft.com/cppblog/visual-studio-code-c-december-2021-update-clang-tidy/)\n- [Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html)\n- [Google C++ Style Guide [with code highlight]](./google-style-guide.html)\n- [Bjarne Stroustrup's C++ Style and Technique FAQ](https://www.stroustrup.com/bs_faq2.html)\n- [STL Algorithms](https://www.cs.helsinki.fi/u/tpkarkka/alglib/k06/lectures/algorithms.html)\n- [mortennobel/cpp-Cheat sheet](https://github.com/mortennobel/cpp-Cheatsheet)\n- [C++ Cheat Sheets \u0026 Infographics](https://hackingcpp.com/cpp/cheat_sheets.html)\n- [CMake Tutorial](https://cmake.org/cmake/help/latest/guide/tutorial/A%20Basic%20Starting%20Point.html)\n- [📑 C++ Beginner's Guide](https://hackingcpp.com/cpp/beginners_guide.html#intro)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fva1da5%2Fcpp-practice","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fva1da5%2Fcpp-practice","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fva1da5%2Fcpp-practice/lists"}