- Notifications
You must be signed in to change notification settings - Fork727
Modern C++ Cheatsheet
mortennobel/cpp-cheatsheet
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Based onPhillip M. Duxbury's C++ Cheatsheet and edited by Morten Nobel-Jørgensen.The cheatsheet focus is both on the language as well as common classes from the standard library.C++11 additions is inspired byISOCPP.org C++11 Cheatsheet).
The goal is to give a concise overview of basic, modern C++ (C++14).
The document is hosted onhttps://github.com/mortennobel/cpp-cheatsheet. Any comments and feedback are appreciated.
// Comment to end of line/* Multi-line comment*/#include<stdio.h>// Insert standard header file#include"myfile.h"// Insert file in current directory#defineX some text// Replace X with some text#defineF(a,b) a+b// Replace F(1,2) with 1+2#defineX \ some text// Multiline definition#undef X// Remove definition#if defined(X)// Conditional compilation (#ifdef X)#else// Optional (#ifndef X or #if !defined(X))#endif// Required after #if, #ifdef
255,0377,0xff// Integers (decimal, octal, hex)2147483647L,0x7fffffffl// Long (32-bit) integers123.0,1.23e2// double (real) numbers'a','\141','\x61'// Character (literal, octal, hex)'\n','\\','\'','\"'// Newline, backslash, single quote, double quote"string\n"// Array of characters ending with newline and \0"hello""world"// Concatenated stringstrue,false// bool constants 1 and 0nullptr// Pointer type with the address of 0
int x;// Declare x to be an integer (value undefined)int x=255;// Declare and initialize x to 255short s;long l;// Usually 16 or 32 bit integer (int may be either)char c='a';// Usually 8 bit characterunsignedchar u=255;signedchar s=-1;// char might be eitherunsignedlong x =0xffffffffL;// short, int, long are signedfloat f;double d;// Single or double precision real (never unsigned)bool b=true;// true or false, may also use int (1 or 0)int a, b, c;// Multiple declarationsint a[10];// Array of 10 ints (a[0] through a[9])int a[]={0,1,2};// Initialized array (or a[3]={0,1,2}; )int a[2][2]={{1,2},{4,5}};// Array of array of intschar s[]="hello";// String (6 elements including '\0')std::string s ="Hello"// Creates string object with value "Hello"std::string s =R"(HelloWorld)";// Creates string object with value "Hello\nWorld"int* p;// p is a pointer to (address of) intchar* s="hello";// s points to unnamed array containing "hello"void* p=nullptr;// Address of untyped memory (nullptr is 0)int& r=x;// r is a reference to (alias of) int xenum weekend {SAT,SUN};// weekend is a type with values SAT and SUNenum weekend day;// day is a variable of type weekendenum weekend{SAT=0,SUN=1};// Explicit representation as intenum {SAT,SUN} day;// Anonymous enumenumclassColor {Red,Blue};// Color is a strict type with values Red and BlueColor x = Color::Red;// Assign Color x to redtypedef Stringchar*;// String s; means char* s;constint c=3;// Constants must be initialized, cannot assign toconstint* p=a;// Contents of p (elements of a) are constantint*const p=a;// p (but not contents) are constantconstint*const p=a;// Both p and its contents are constantconstint& cr=x;// cr cannot be assigned to change xint8_t,uint8_t,int16_t,uint16_t,int32_t,uint32_t,int64_t,uint64_t// Fixed length standard typesauto it = m.begin();// Declares it to the result of m.begin()autoconst param = config["param"];// Declares it to the const resultauto& s = singleton::instance();// Declares it to a reference of the result
int x;// Auto (memory exists only while in scope)staticint x;// Global lifetime even if local scopeexternint x;// Information only, declared elsewhere
x=y;// Every expression is a statementint x;// Declarations are statements;// Empty statement{// A block is a single statementint x;// Scope of x is from declaration to end of block}if (x) a;// If x is true (not 0), evaluate aelseif (y) b;// If not x and y (optional, may be repeated)else c;// If not x and not y (optional)while (x) a;// Repeat 0 or more times while x is truefor (x; y; z) a;// Equivalent to: x; while(y) {a; z;}for (x : y) a;// Range-based for loop e.g.// for (auto& x in someList) x.y();do a;while (x);// Equivalent to: a; while(x) a;switch (x) {// x must be intcase X1: a;// If x == X1 (must be a const), jump herecase X2: b;// Else if x == X2, jump heredefault: c;// Else jump here (optional)}break;// Jump out of while, do, or for loop, or switchcontinue;// Jump to bottom of while, do, or for loopreturn x;// Return x from function to callertry { a; }catch (T t) { b; }// If a throws a T, then jump herecatch (...) { c; }// If a throws something else, jump here
intf(int x,int y);// f is a function taking 2 ints and returning intvoidf();// f is a procedure taking no argumentsvoidf(int a=0);// f() is equivalent to f(0)f();// Default return type is intinlinef();// Optimize for speedf() { statements; }// Function definition (must be global)Toperator+(T x, T y);// a+b (if type T) calls operator+(a, b)Toperator-(T x);// -a calls function operator-(a)Toperator++(int);// postfix ++ or -- (parameter ignored)extern"C" {voidf();}// f() was compiled in C
Function parameters and return values may be of any type. A function must either be declared or defined beforeit is used. It may be declared first and defined later. Every program consists of a set of a set of global variabledeclarations and a set of function definitions (possibly in separate files), one of which must be:
intmain() { statements... }// orintmain(int argc,char* argv[]) { statements... }
argv is an array ofargc strings from the command line.By convention,main returns status0 if successful,1 or higher for errors.
Functions with different parameters may have the same name (overloading). Operators except::..*?: may be overloaded.Precedence order is not affected. New operators may not be created.
Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. Allothers are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run timechecks for arrays out of bounds, invalid pointers, etc.
T::X// Name X defined in class TN::X// Name X defined in namespace N::X// Global name Xt.x// Member x of struct or class tp-> x// Member x of struct or class pointed to by pa[i]// i'th element of array af(x,y)// Call to function f with arguments x and yT(x,y)// Object of class T initialized with x and yx++// Add 1 to x, evaluates to original x (postfix)x--// Subtract 1 from x, evaluates to original xtypeid(x)// Type of xtypeid(T)// Equals typeid(x) if x is a Tdynamic_cast< T>(x)// Converts x to a T, checked at run time.static_cast< T>(x)// Converts x to a T, not checkedreinterpret_cast< T>(x)// Interpret bits of x as a Tconst_cast< T>(x)// Converts x to same type T but not constsizeof x// Number of bytes used to represent object xsizeof(T)// Number of bytes to represent type T++x// Add 1 to x, evaluates to new value (prefix)--x// Subtract 1 from x, evaluates to new value~x// Bitwise complement of x!x// true if x is 0, else false (1 or 0 in C)-x// Unary minus+x// Unary plus (default)&x// Address of x*p// Contents of address p (*&x equals x)new T// Address of newly allocated T objectnew T(x, y)// Address of a T initialized with x, ynew T[x]// Address of allocated n-element array of Tdelete p// Destroy and free object at address pdelete[] p// Destroy and free array of objects at p(T) x// Convert x to T (obsolete, use .._cast<T>(x))x * y// Multiplyx / y// Divide (integers round toward 0)x % y// Modulo (result has sign of x)x + y// Add, or \&x[y]x - y// Subtract, or number of elements from *x to *yx << y// x shifted y bits to left (x * pow(2, y))x >> y// x shifted y bits to right (x / pow(2, y))x < y// Less thanx <= y// Less than or equal tox > y// Greater thanx >= y// Greater than or equal tox & y// Bitwise and (3 & 6 is 2)x ^ y// Bitwise exclusive or (3 ^ 6 is 5)x | y// Bitwise or (3 | 6 is 7)x && y// x and then y (evaluates y only if x (not 0))x || y// x or else y (evaluates y only if x is false (0))x = y// Assign y to x, returns new value of xx += y// x = x + y, also -= *= /= <<= >>= &= |= ^=x ? y : z// y if x is true (nonzero), else zthrow x// Throw exception, aborts if not caughtx , y// evaluates x and y, returns y (seldom used)
classT {// A new typeprivate:// Section accessible only to T's member functionsprotected:// Also accessible to classes derived from Tpublic:// Accessible to allint x;// Member datavoidf();// Member functionvoidg() {return;}// Inline member functionvoidh()const;// Does not modify any data membersintoperator+(int y);// t+y means t.operator+(y)intoperator-();// -t means t.operator-()T(): x(1) {}// Constructor with initialization listT(const T& t): x(t.x) {}// Copy constructor T&operator=(const T& t) {x=t.x;return *this; }// Assignment operator~T();// Destructor (automatic cleanup routine)explicitT(int a);// Allow t=T(3) but not t=3T(float x): T((int)x) {}// Delegate constructor to T(int)operatorint()const {return x;}// Allows int(t)friendvoidi();// Global function i() has private accessfriendclassU;// Members of class U have private accessstaticint y;// Data shared by all T objectsstaticvoidl();// Shared code. May access y but not xclassZ {};// Nested class T::Ztypedefint V;// T::V means int};voidT::f() {// Code for member function f of class Tthis->x = x;}// this is address of self (means x=x;)int T::y =2;// Initialization of static member (required)T::l();// Call to static memberT t;// Create object t implicit call constructort.f();// Call method f on object tstructT {// Equivalent to: class T { public:virtualvoidi();// May be overridden at run time by derived classvirtualvoidg()=0; };// Must be overridden (pure virtual)classU:publicT {// Derived class U inherits all members of base Tpublic:voidg(int)override; };// Override method gclassV:privateT {};// Inherited members of T become privateclassW:publicT,publicU {};// Multiple inheritanceclassX:publicvirtual T {};// Classes derived from X have base T directly
All classes have a default copy constructor, assignment operator, and destructor, which perform thecorresponding operations on each data member and each base class as shown above. There is also a default no-argumentconstructor (required to create arrays) if the class has no constructors. Constructors, assignment, anddestructors do not inherit.
template<classT> Tf(T t);// Overload f for all typestemplate<classT>classX {// Class with type parameter TX(T t); };// A constructortemplate<classT> X<T>::X(T t) {}// Definition of constructorX<int>x(3);// An object of type "X of int"template<classT,classU=T,int n=0>// Template with default parameters
namespaceN {classT {};}// Hide name TN::T t;// Use name T in namespace NusingnamespaceN;// Make T visible without N::
#include<memory>// Include memory (std namespace)shared_ptr<int> x;// Empty shared_ptr to a integer on heap. Uses reference counting for cleaning up objects.x = make_shared<int>(12);// Allocate value 12 on heapshared_ptr<int> y = x;// Copy shared_ptr, implicit changes reference count to 2.cout << *y;// Dereference y to print '12'if (y.get() == x.get()) {// Raw pointers (here x == y) cout <<"Same"; } y.reset();// Eliminate one owner of objectif (y.get() != x.get()) { cout <<"Different"; }if (y ==nullptr) {// Can compare against nullptr (here returns true) cout <<"Empty"; } y = make_shared<int>(15);// Assign new valuecout << *y;// Dereference x to print '15'cout << *x;// Dereference x to print '12'weak_ptr<int> w;// Create empty weak pointerw = y;// w has weak reference to y.if (shared_ptr<int> s = w.lock()) {// Has to be copied into a shared_ptr before usage cout << *s;}unique_ptr<int> z;// Create empty unique pointersunique_ptr<int> q;z = make_unique<int>(16);// Allocate int (16) on heap. Only one reference allowed.q = move(z);// Move reference from z to q.if (z ==nullptr){ cout <<"Z null";}cout << *q;shared_ptr<B> r;r = dynamic_pointer_cast<B>(t);// Converts t to a shared_ptr<B>
#include<cmath>// Include cmath (std namespace)sin(x); cos(x); tan(x);// Trig functions, x (double) is in radiansasin(x); acos(x); atan(x);// Inversesatan2(y, x);// atan(y/x)sinh(x); cosh(x); tanh(x);// Hyperbolic sin, cos, tan functionsexp(x); log(x); log10(x);// e to the x, log base e, log base 10pow(x, y); sqrt(x);// x to the y, square rootceil(x); floor(x);// Round up or down (as a double)fabs(x); fmod(x, y);// Absolute value, x mod y
#include<cassert>// Include iostream (std namespace)assert(e);// If e is false, print message and abort#defineNDEBUG// (before #include <assert.h>), turn off assert
#include<iostream>// Include iostream (std namespace)cin >> x >> y;// Read words x and y (any type) from stdincout <<"x=" <<3 << endl;// Write line to stdoutcerr << x << y << flush;// Write to stderr and flushc = cin.get();// c = getchar();cin.get(c);// Read charcin.getline(s, n,'\n');// Read line into char s[n] to '\n' (default)if (cin)// Good state (not EOF)?// To read/write any type T:istream&operator>>(istream& i, T& x) {i >> ...; x=...;return i;}ostream&operator<<(ostream& o,const T& x) {return o << ...;}
#include<fstream>// Include filestream (std namespace)ifstreamf1("filename");// Open text file for readingif (f1)// Test if open and input available f1 >> x;// Read object from filef1.get(s);// Read char or linef1.getline(s, n);// Read line into string s[n]ofstreamf2("filename");// Open file for writingif (f2) f2 << x;// Write to file
#include<string>// Include string (std namespace)string s1, s2="hello";// Create stringss1.size(), s2.size();// Number of characters: 0, 5s1 += s2 +'' +"world";// Concatenations1 =="hello world"// Comparison, also <, >, !=, etc.s1[0];// 'h's1.substr(m, n);// Substring of size n starting at s1[m]s1.c_str();// Convert to const char*s1 = to_string(12.05);// Converts number to stringgetline(cin, s);// Read line ending in '\n'
#include<vector>// Include vector (std namespace)vector<int>a(10);// a[0]..a[9] are int (default size is 0)vector<int> b{1,2,3};// Create vector with values 1,2,3a.size();// Number of elements (10)a.push_back(3);// Increase size to 11, a[10]=3a.back()=4;// a[10]=4;a.pop_back();// Decrease size by 1a.front();// a[0];a[20]=1;// Crash: not bounds checkeda.at(20)=1;// Like a[20] but throws out_of_range()for (int& p : a) p=0;// C++11: Set all elements of a to 0for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p) *p=0;// C++03: Set all elements of a to 0vector<int>b(a.begin(), a.end());// b is copy of avector<T>c(n, x);// c[0]..c[n-1] init to xT d[10]; vector<T>e(d, d+10);// e is initialized from d
deque<T> is likevector<T>, but also supports:
#include<deque>// Include deque (std namespace)a.push_front(x);// Puts x at a[0], shifts elements toward backa.pop_front();// Removes a[0], shifts toward front
#include<utility>// Include utility (std namespace)pair<string,int>a("hello",3);// A 2-element structa.first;// "hello"a.second;// 3
map (associative array - usually implemented as binary search trees - avg. time complexity: O(log n))
#include<map>// Include map (std namespace)map<string,int> a;// Map from string to inta["hello"] =3;// Add or replace element a["hello"]for (auto& p:a) cout << p.first << p.second;// Prints hello, 3a.size();// 1
#include<unordered_map>// Include map (std namespace)unordered_map<string,int> a;// Map from string to inta["hello"] =3;// Add or replace element a["hello"]for (auto& p:a) cout << p.first << p.second;// Prints hello, 3a.size();// 1
set (store unique elements - usually implemented as binary search trees - avg. time complexity: O(log n))
#include<set>// Include set (std namespace)set<int> s;// Set of integerss.insert(123);// Add element to setif (s.find(123) != s.end())// Search for an element s.erase(123);cout << s.size();// Number of elements in set
unordered_set (store unique elements - usually implemented as a hash set - avg. time complexity: O(1))
#include<unordered_set>// Include set (std namespace)unordered_set<int> s;// Set of integerss.insert(123);// Add element to setif (s.find(123) != s.end())// Search for an element s.erase(123);cout << s.size();// Number of elements in set
#include<algorithm>// Include algorithm (std namespace)min(x, y); max(x, y);// Smaller/larger of x, y (any type defining <)swap(x, y);// Exchange values of variables x and ysort(a, a+n);// Sort array a[0]..a[n-1] by <sort(a.begin(), a.end());// Sort vector or dequereverse(a.begin(), a.end());// Reverse vector or deque
#include<chrono>// Include chronousingnamespacestd::chrono;// Use namespaceauto from =// Get current time_pointhigh_resolution_clock::now();// ... do some workauto to =// Get current time_pointhigh_resolution_clock::now();using ms =// Define ms as floating point duration duration<float, milliseconds::period>;// Compute duration in millisecondscout << duration_cast<ms>(to - from) .count() <<"ms";
#include<thread>// Include threadunsigned c =hardware_concurrency();// Hardware threads (or 0 for unknown)auto lambdaFn = [](){// Lambda function used for thread body cout <<"Hello multithreading";};threadt(lambdaFn);// Create and run thread with lambdat.join();// Wait for t finishes// --- shared resource example ---mutex mut;// Mutex for synchronizationcondition_variable cond;// Shared condition variableconstchar* sharedMes// Shared resource =nullptr;auto pingPongFn =// thread body (lambda). Print someone else's message [&](constchar* mes){while (true){ unique_lock<mutex>lock(mut);// locks the mutexdo { cond.wait(lock, [&](){// wait for condition to be true (unlocks while waiting which allows other threads to modify)return sharedMes != mes;// statement for when to continue }); }while (sharedMes == mes);// prevents spurious wakeup cout << sharedMes << endl; sharedMes = mes; lock.unlock();// no need to have lock on notify cond.notify_all();// notify all condition has changed } };sharedMes ="ping";threadt1(pingPongFn, sharedMes);// start example with 3 concurrent threadsthreadt2(pingPongFn,"pong");threadt3(pingPongFn,"boing");
#include<future>// Include futurefunction<int(int)> fib =// Create lambda function [&](int i){if (i <=1){return1; }returnfib(i-1) +fib(i-2); };future<int> fut =// result of async functionasync(launch::async, fib,4);// start async function in other thread// do some other workcout << fut.get();// get result of async function. Wait if needed.
About
Modern C++ Cheatsheet
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Contributors3
Uh oh!
There was an error while loading.Please reload this page.