Advertisement
LshySVK

C++ quick reference

Jun 19th, 2024 (edited)
599
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 24.67 KB | Source Code | 0 0
  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 <a href="http://www.pa.msu.edu/~duxbury/courses/phy480/Cpp_refcard.pdf">Phillip M. Duxbury's C++ Cheatsheet</a> 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 <a href="https://isocpp.org/blog/2012/12/c11-a-cheat-sheet-alex-sinyakov">ISOCPP.org C++11 Cheatsheet</a>).
  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  <stdio.h>         // 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<T>(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 <class T> T f(T t);// Overload f for all types
  278. template <class T> class X {// Class with type parameter T
  279.     X(T t); };                // A constructor
  280. template <class T> X<T>::X(T t) {}
  281. // Definition of constructor
  282. X<int> x(3);                // An object of type "X of int"
  283. template <class T, class U=T, int n=0>
  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 <memory>           // Include memory (std namespace)
  295. shared_ptr<int> x;          // Empty shared_ptr to a integer on heap. Uses reference counting for cleaning up objects.
  296. x = make_shared<int>(12);   // Allocate value 12 on heap
  297. shared_ptr<int> 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<int>(15);   // Assign new value
  310. cout << *y;                 // Dereference x to print '15'
  311. cout << *x;                 // Dereference x to print '12'
  312. weak_ptr<int> w;            // Create empty weak pointer
  313. w = y;                      // w has weak reference to y.
  314. if (shared_ptr<int> s = w.lock()) { // Has to be copied into a shared_ptr before usage
  315.   cout << *s;
  316. }
  317. unique_ptr<int> z;          // Create empty unique pointers
  318. unique_ptr<int> q;
  319. z = make_unique<int>(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<B> r;
  326. r = dynamic_pointer_cast<B>(t); // Converts t to a shared_ptr<B>
  327.  
  328.  
  329. // ## `math.h`, `cmath` (floating point math)
  330.  
  331. #include <cmath>            // 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 <cassert>        // Include iostream (std namespace)
  344.         assert(e);                // If e is false, print message and abort
  345. #define NDEBUG            // (before #include <assert.h>), turn off assert
  346.  
  347. // ## `iostream.h`, `iostream` (Replaces `stdio.h`)
  348.  
  349. #include <iostream>         // 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 <fstream>          // 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 <string>         // 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 <vector>         // Include vector (std namespace)
  388. vector<int> a(10);        // a[0]..a[9] are int (default size is 0)
  389. vector<int> 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<int>::iterator p=a.begin(); p!=a.end(); ++p)
  400. *p=0;                   // C++03: Set all elements of a to 0
  401. vector<int> b(a.begin(), a.end());  // b is copy of a
  402. vector<T> c(n, x);        // c[0]..c[n-1] init to x
  403. T d[10]; vector<T> e(d, d+10);      // e is initialized from d
  404.  
  405. // ## `deque` (Array stack queue)
  406.  
  407. // `deque<T>` is like `vector<T>`, but also supports:
  408.  
  409. #include <deque>          // 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 <utility>        // Include utility (std namespace)
  416.         pair<string, int> 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 <map>            // Include map (std namespace)
  423. map<string, int> 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 <unordered_map>  // Include map (std namespace)
  432. unordered_map<string, int> 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 <set>            // Include set (std namespace)
  441. set<int> 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 <unordered_set>  // Include set (std namespace)
  450. unordered_set<int> 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 <algorithm>      // 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 <chrono>         // 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<float, milliseconds::period>;
  476. // Compute duration in milliseconds
  477. cout << duration_cast<ms>(to - from)
  478. .count() << "ms";
  479.  
  480. // ## `thread` (Multi-threading library)
  481.  
  482. #include <thread>         // 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<mutex> 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 <future>         // Include future
  519.         function<int(int)> 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<int> 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.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement