mirror of
https://github.com/DevEhChad/cpp-cheatsheet.git
synced 2025-11-08 14:01:34 +00:00
177
README.md
177
README.md
@@ -9,9 +9,9 @@ The goal is to give a concise overview of basic, modern C++.
|
|||||||
|
|
||||||
The document is hosted on https://github.com/mortennobel/cpp-cheatsheet. Any comments and feedback are appreciated.
|
The document is hosted on https://github.com/mortennobel/cpp-cheatsheet. Any comments and feedback are appreciated.
|
||||||
|
|
||||||
## PREPROCESSOR
|
## Preprocessor
|
||||||
|
|
||||||
~~~~
|
```cpp
|
||||||
// Comment to end of line
|
// Comment to end of line
|
||||||
/* Multi-line comment */
|
/* Multi-line comment */
|
||||||
#include <stdio.h> // Insert standard header file
|
#include <stdio.h> // Insert standard header file
|
||||||
@@ -21,13 +21,14 @@ The document is hosted on https://github.com/mortennobel/cpp-cheatsheet. Any com
|
|||||||
#define X \
|
#define X \
|
||||||
some text // Multiline definition
|
some text // Multiline definition
|
||||||
#undef X // Remove definition
|
#undef X // Remove definition
|
||||||
#if defined(X) // Condional compilation (#ifdef X)
|
#if defined(X) // Conditional compilation (#ifdef X)
|
||||||
#else // Optional (#ifndef X or #if !defined(X))
|
#else // Optional (#ifndef X or #if !defined(X))
|
||||||
#endif // Required after #if, #ifdef
|
#endif // Required after #if, #ifdef
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## LITERALS
|
## Literals
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
255, 0377, 0xff // Integers (decimal, octal, hex)
|
255, 0377, 0xff // Integers (decimal, octal, hex)
|
||||||
2147483647L, 0x7fffffffl // Long (32-bit) integers
|
2147483647L, 0x7fffffffl // Long (32-bit) integers
|
||||||
123.0, 1.23e2 // double (real) numbers
|
123.0, 1.23e2 // double (real) numbers
|
||||||
@@ -37,10 +38,11 @@ The document is hosted on https://github.com/mortennobel/cpp-cheatsheet. Any com
|
|||||||
"hello" "world" // Concatenated strings
|
"hello" "world" // Concatenated strings
|
||||||
true, false // bool constants 1 and 0
|
true, false // bool constants 1 and 0
|
||||||
nullptr // Pointer type with the address of 0
|
nullptr // Pointer type with the address of 0
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## DECLARATIONS
|
## Declarations
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
int x; // Declare x to be an integer (value undefined)
|
int x; // Declare x to be an integer (value undefined)
|
||||||
int x=255; // Declare and initialize x to 255
|
int x=255; // Declare and initialize x to 255
|
||||||
short s; long l; // Usually 16 or 32 bit integer (int may be either)
|
short s; long l; // Usually 16 or 32 bit integer (int may be either)
|
||||||
@@ -83,17 +85,19 @@ auto const param = config["param"];
|
|||||||
// Declares it to the const result
|
// Declares it to the const result
|
||||||
auto& s = singleton::instance();
|
auto& s = singleton::instance();
|
||||||
// Declares it to a reference of the result
|
// Declares it to a reference of the result
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## STORAGE CLASSES
|
## STORAGE Classes
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
int x; // Auto (memory exists only while in scope)
|
int x; // Auto (memory exists only while in scope)
|
||||||
static int x; // Global lifetime even if local scope
|
static int x; // Global lifetime even if local scope
|
||||||
extern int x; // Information only, declared elsewhere
|
extern int x; // Information only, declared elsewhere
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## STATEMENTS
|
## Statements
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
x=y; // Every expression is a statement
|
x=y; // Every expression is a statement
|
||||||
int x; // Declarations are statements
|
int x; // Declarations are statements
|
||||||
; // Empty statement
|
; // Empty statement
|
||||||
@@ -124,11 +128,12 @@ return x; // Return x from function to caller
|
|||||||
try { a; }
|
try { a; }
|
||||||
catch (T t) { b; } // If a throws a T, then jump here
|
catch (T t) { b; } // If a throws a T, then jump here
|
||||||
catch (...) { c; } // If a throws something else, jump here
|
catch (...) { c; } // If a throws something else, jump here
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## FUNCTIONS
|
## Functions
|
||||||
~~~~
|
|
||||||
int f(int x, int); // f is a function taking 2 ints and returning int
|
```cpp
|
||||||
|
int f(int x, int y); // f is a function taking 2 ints and returning int
|
||||||
void f(); // f is a procedure taking no arguments
|
void f(); // f is a procedure taking no arguments
|
||||||
void f(int a=0); // f() is equivalent to f(0)
|
void f(int a=0); // f() is equivalent to f(0)
|
||||||
f(); // Default return type is int
|
f(); // Default return type is int
|
||||||
@@ -138,29 +143,30 @@ T operator+(T x, T y); // a+b (if type T) calls operator+(a, b)
|
|||||||
T operator-(T x); // -a calls function operator-(a)
|
T operator-(T x); // -a calls function operator-(a)
|
||||||
T operator++(int); // postfix ++ or -- (parameter ignored)
|
T operator++(int); // postfix ++ or -- (parameter ignored)
|
||||||
extern "C" {void f();} // f() was compiled in C
|
extern "C" {void f();} // f() was compiled in C
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
Function parameters and return values may be of any type. A function must either be declared or defined before
|
Function parameters and return values may be of any type. A function must either be declared or defined before
|
||||||
it is used. It may be declared first and defined later. Every program consists of a set of a set of global variable
|
it is used. It may be declared first and defined later. Every program consists of a set of a set of global variable
|
||||||
declarations and a set of function definitions (possibly in separate files), one of which must be:
|
declarations and a set of function definitions (possibly in separate files), one of which must be:
|
||||||
|
|
||||||
~~~~
|
```cpp
|
||||||
int main() { statements... } or
|
int main() { statements... } // or
|
||||||
int main(int argc, char* argv[]) { statements... }
|
int main(int argc, char* argv[]) { statements... }
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
argv is an array of argc strings from the command line. By convention, main returns status 0 if successful, 1 or
|
`argv` is an array of `argc` strings from the command line.
|
||||||
higher for errors.
|
By convention, `main` returns status `0` if successful, `1` or higher for errors.
|
||||||
|
|
||||||
Functions with different parameters may have the same name (overloading). Operators except :: . .* ?: may be
|
Functions with different parameters may have the same name (overloading). Operators except `::` `.` `.*` `?:` may be overloaded.
|
||||||
overloaded. Precedence order is not affected. New operators may not be created.
|
Precedence order is not affected. New operators may not be created.
|
||||||
|
|
||||||
|
## Expressions
|
||||||
|
|
||||||
## EXPRESSIONS
|
|
||||||
Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All
|
Operators are grouped by precedence, highest first. Unary operators and assignment evaluate right to left. All
|
||||||
others are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time
|
others are left to right. Precedence does not affect order of evaluation, which is undefined. There are no run time
|
||||||
checks for arrays out of bounds, invalid pointers, etc.
|
checks for arrays out of bounds, invalid pointers, etc.
|
||||||
|
|
||||||
~~~~
|
```cpp
|
||||||
T::X // Name X defined in class T
|
T::X // Name X defined in class T
|
||||||
N::X // Name X defined in namespace N
|
N::X // Name X defined in namespace N
|
||||||
::X // Global name X
|
::X // Global name X
|
||||||
@@ -220,14 +226,15 @@ x += y // x = x + y, also -= *= /= <<= >>= &= |= ^=
|
|||||||
x ? y : z // y if x is true (nonzero), else z
|
x ? y : z // y if x is true (nonzero), else z
|
||||||
throw x // Throw exception, aborts if not caught
|
throw x // Throw exception, aborts if not caught
|
||||||
x , y // evaluates x and y, returns y (seldom used)
|
x , y // evaluates x and y, returns y (seldom used)
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## CLASSES
|
## Classes
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
class T { // A new type
|
class T { // A new type
|
||||||
private: // Section accessible only to T's member functions
|
private: // Section accessible only to T's member functions
|
||||||
protected: // Also accessable to classes derived from T
|
protected: // Also accessuble to classes derived from T
|
||||||
public: // Accessable to all
|
public: // Accessuble to all
|
||||||
int x; // Member data
|
int x; // Member data
|
||||||
void f(); // Member function
|
void f(); // Member function
|
||||||
void g() {return;} // Inline member function
|
void g() {return;} // Inline member function
|
||||||
@@ -240,7 +247,7 @@ public: // Accessable to all
|
|||||||
{x=t.x; return *this; } // Assignment operator
|
{x=t.x; return *this; } // Assignment operator
|
||||||
~T(); // Destructor (automatic cleanup routine)
|
~T(); // Destructor (automatic cleanup routine)
|
||||||
explicit T(int a); // Allow t=T(3) but not t=3
|
explicit T(int a); // Allow t=T(3) but not t=3
|
||||||
T(float x): T((int)x) {}// Delegate contructor to T(int)
|
T(float x): T((int)x) {}// Delegate constructor to T(int)
|
||||||
operator int() const
|
operator int() const
|
||||||
{return x;} // Allows int(t)
|
{return x;} // Allows int(t)
|
||||||
friend void i(); // Global function i() has private access
|
friend void i(); // Global function i() has private access
|
||||||
@@ -268,15 +275,16 @@ class W: public T, public U {};
|
|||||||
// Multiple inheritance
|
// Multiple inheritance
|
||||||
class X: public virtual T {};
|
class X: public virtual T {};
|
||||||
// Classes derived from X have base T directly
|
// Classes derived from X have base T directly
|
||||||
~~~~
|
```cpp
|
||||||
|
|
||||||
All classes have a default copy constructor, assignment operator, and destructor, which perform the
|
All 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
|
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
|
constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and
|
||||||
destructors do not inherit.
|
destructors do not inherit.
|
||||||
|
|
||||||
## TEMPLATES
|
## Templates
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
template <class T> T f(T t);// Overload f for all types
|
template <class T> T f(T t);// Overload f for all types
|
||||||
template <class T> class X {// Class with type parameter T
|
template <class T> class X {// Class with type parameter T
|
||||||
X(T t); }; // A constructor
|
X(T t); }; // A constructor
|
||||||
@@ -285,37 +293,41 @@ template <class T> X<T>::X(T t) {}
|
|||||||
X<int> x(3); // An object of type "X of int"
|
X<int> x(3); // An object of type "X of int"
|
||||||
template <class T, class U=T, int n=0>
|
template <class T, class U=T, int n=0>
|
||||||
// Template with default parameters
|
// Template with default parameters
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## NAMESPACES
|
## Namespaces
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
namespace N {class T {};} // Hide name T
|
namespace N {class T {};} // Hide name T
|
||||||
N::T t; // Use name T in namespace N
|
N::T t; // Use name T in namespace N
|
||||||
using namespace N; // Make T visible without N::
|
using namespace N; // Make T visible without N::
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## MATH.H, CMATH (Floating point math)
|
## `math.h`, `cmath` (floating point math)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <cmath> // Include cmath (std namespace)
|
#include <cmath> // Include cmath (std namespace)
|
||||||
sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians
|
sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians
|
||||||
asin(x); acos(x); atan(x); // Inverses
|
asin(x); acos(x); atan(x); // Inverses
|
||||||
atan2(y, x); // atan(y/x)
|
atan2(y, x); // atan(y/x)
|
||||||
sinh(x); cosh(x); tanh(x); // Hyperbolic
|
sinh(x); cosh(x); tanh(x); // Hyperbolic sin, cos, tan functions
|
||||||
exp(x); log(x); log10(x); // e to the x, log base e, log base 10
|
exp(x); log(x); log10(x); // e to the x, log base e, log base 10
|
||||||
pow(x, y); sqrt(x); // x to the y, square root
|
pow(x, y); sqrt(x); // x to the y, square root
|
||||||
ceil(x); floor(x); // Round up or down (as a double)
|
ceil(x); floor(x); // Round up or down (as a double)
|
||||||
fabs(x); fmod(x, y); // Absolute value, x mod y
|
fabs(x); fmod(x, y); // Absolute value, x mod y
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## ASSERT.H, CASSERT (Debugging aid)
|
## `assert.h`, `cassert` (Debugging Aid)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <cassert> // Include iostream (std namespace)
|
#include <cassert> // Include iostream (std namespace)
|
||||||
assert(e); // If e is false, print message and abort
|
assert(e); // If e is false, print message and abort
|
||||||
#define NDEBUG // (before #include <assert.h>), turn off assert
|
#define NDEBUG // (before #include <assert.h>), turn off assert
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## IOSTREAM.H, IOSTREAM (Replaces stdio.h)
|
## `iostream.h`, `iostream` (Replaces `stdio.h`)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <iostream> // Include iostream (std namespace)
|
#include <iostream> // Include iostream (std namespace)
|
||||||
cin >> x >> y; // Read words x and y (any type) from stdin
|
cin >> x >> y; // Read words x and y (any type) from stdin
|
||||||
cout << "x=" << 3 << endl; // Write line to stdout
|
cout << "x=" << 3 << endl; // Write line to stdout
|
||||||
@@ -327,11 +339,12 @@ if (cin) // Good state (not EOF)?
|
|||||||
// To read/write any type T:
|
// To read/write any type T:
|
||||||
istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}
|
istream& operator>>(istream& i, T& x) {i >> ...; x=...; return i;}
|
||||||
ostream& operator<<(ostream& o, const T& x) {return o << ...;}
|
ostream& operator<<(ostream& o, const T& x) {return o << ...;}
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## FSTREAM.H, FSTREAM (File I/O works like cin, cout as above)
|
## `fstream.h`, `fstream` (File I/O works like `cin`, `cout` as above)
|
||||||
|
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <fstream> // Include filestream (std namespace)
|
#include <fstream> // Include filestream (std namespace)
|
||||||
ifstream f1("filename"); // Open text file for reading
|
ifstream f1("filename"); // Open text file for reading
|
||||||
if (f1) // Test if open and input available
|
if (f1) // Test if open and input available
|
||||||
@@ -340,10 +353,11 @@ f1.get(s); // Read char or line
|
|||||||
f1.getline(s, n); // Read line into string s[n]
|
f1.getline(s, n); // Read line into string s[n]
|
||||||
ofstream f2("filename"); // Open file for writing
|
ofstream f2("filename"); // Open file for writing
|
||||||
if (f2) f2 << x; // Write to file
|
if (f2) f2 << x; // Write to file
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## STRING (Variable sized character array)
|
## `string` (Variable sized character `array`)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <string> // Include string (std namespace)
|
#include <string> // Include string (std namespace)
|
||||||
string s1, s2="hello"; // Create strings
|
string s1, s2="hello"; // Create strings
|
||||||
s1.size(), s2.size(); // Number of characters: 0, 5
|
s1.size(), s2.size(); // Number of characters: 0, 5
|
||||||
@@ -354,11 +368,12 @@ s1.substr(m, n); // Substring of size n starting at s1[m]
|
|||||||
s1.c_str(); // Convert to const char*
|
s1.c_str(); // Convert to const char*
|
||||||
s1 = to_string(12.05); // Converts number to string
|
s1 = to_string(12.05); // Converts number to string
|
||||||
getline(cin, s); // Read line ending in '\n'
|
getline(cin, s); // Read line ending in '\n'
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## VECTOR (Variable sized array/stack with built in memory allocation)
|
## `vector` (Variable sized array/stack with built in memory allocation)
|
||||||
|
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <vector> // Include vector (std namespace)
|
#include <vector> // Include vector (std namespace)
|
||||||
vector<int> a(10); // a[0]..a[9] are int (default size is 0)
|
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,3
|
vector<int> b{1,2,3}; // Create vector with values 1,2,3
|
||||||
@@ -376,48 +391,44 @@ for (vector<int>::iterator p=a.begin(); p!=a.end(); ++p)
|
|||||||
vector<int> b(a.begin(), a.end()); // b is copy of a
|
vector<int> b(a.begin(), a.end()); // b is copy of a
|
||||||
vector<T> c(n, x); // c[0]..c[n-1] init to x
|
vector<T> c(n, x); // c[0]..c[n-1] init to x
|
||||||
T d[10]; vector<T> e(d, d+10); // e is initialized from d
|
T d[10]; vector<T> e(d, d+10); // e is initialized from d
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## DEQUE (array/stack/queue)
|
## `deque` (Array Stack Queue)
|
||||||
|
|
||||||
deque<T> is like vector<T>, but also supports:
|
`deque<T>` is like `vector<T>`, but also supports:
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <deque> // Include deque (std namespace)
|
#include <deque> // Include deque (std namespace)
|
||||||
a.push_front(x); // Puts x at a[0], shifts elements toward back
|
a.push_front(x); // Puts x at a[0], shifts elements toward back
|
||||||
a.pop_front(); // Removes a[0], shifts toward front
|
a.pop_front(); // Removes a[0], shifts toward front
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## UTILITY (Pair)
|
## `utility` (Pair)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <utility> // Include utility (std namespace)
|
#include <utility> // Include utility (std namespace)
|
||||||
pair<string, int> a("hello", 3); // A 2-element struct
|
pair<string, int> a("hello", 3); // A 2-element struct
|
||||||
a.first; // "hello"
|
a.first; // "hello"
|
||||||
a.second; // 3
|
a.second; // 3
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## MAP (associative array - usually implemented as red-black trees)
|
## `map` (associative array - usually implemented as red-black Trees)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <map> // Include map (std namespace)
|
#include <map> // Include map (std namespace)
|
||||||
map<string, int> a; // Map from string to int
|
map<string, int> a; // Map from string to int
|
||||||
a["hello"]=3; // Add or replace element a["hello"]
|
a["hello"] = 3; // Add or replace element a["hello"]
|
||||||
for (auto& p:a)
|
for (auto& p:a)
|
||||||
cout << p.first << p.second; // Prints hello, 3
|
cout << p.first << p.second; // Prints hello, 3
|
||||||
a.size(); // 1
|
a.size(); // 1
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
## ALGORITHM (A collection of 60 algorithms on sequences with iterators)
|
## `algorithm` (A collection of 60 algorithms on sequences with Iterators)
|
||||||
~~~~
|
|
||||||
|
```cpp
|
||||||
#include <algorithm> // Include algorithm (std namespace)
|
#include <algorithm> // Include algorithm (std namespace)
|
||||||
min(x, y); max(x, y); // Smaller/larger of x, y (any type defining <)
|
min(x, y); max(x, y); // Smaller/larger of x, y (any type defining <)
|
||||||
swap(x, y); // Exchange values of variables x and y
|
swap(x, y); // Exchange values of variables x and y
|
||||||
sort(a, a+n); // Sort array a[0]..a[n-1] by <
|
sort(a, a+n); // Sort array a[0]..a[n-1] by <
|
||||||
sort(a.begin(), a.end()); // Sort vector or deque
|
sort(a.begin(), a.end()); // Sort vector or deque
|
||||||
~~~~
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user