Merge pull request #2 from Naereen/patch-1

Typo corrected
This commit is contained in:
Morten Nobel-Jørgensen
2018-06-28 22:19:07 +02:00
committed by GitHub

189
README.md
View File

@@ -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.
## PREPROCESSOR
## Preprocessor
~~~~
```cpp
// Comment to end of line
/* Multi-line comment */
#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 \
some text // Multiline 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))
#endif // Required after #if, #ifdef
~~~~
```
## LITERALS
~~~~
## Literals
```cpp
255, 0377, 0xff // Integers (decimal, octal, hex)
2147483647L, 0x7fffffffl // Long (32-bit) integers
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
true, false // bool constants 1 and 0
nullptr // Pointer type with the address of 0
~~~~
```
## DECLARATIONS
~~~~
## Declarations
```cpp
int x; // Declare x to be an integer (value undefined)
int x=255; // Declare and initialize x to 255
short s; long l; // Usually 16 or 32 bit integer (int may be either)
@@ -83,22 +85,24 @@ auto const param = config["param"];
// Declares it to the const result
auto& s = singleton::instance();
// Declares it to a reference of the result
~~~~
```
## STORAGE CLASSES
~~~~
## STORAGE Classes
```cpp
int x; // Auto (memory exists only while in scope)
static int x; // Global lifetime even if local scope
extern int x; // Information only, declared elsewhere
~~~~
```
## STATEMENTS
~~~~
## Statements
```cpp
x=y; // Every expression is a statement
int x; // Declarations are statements
; // Empty statement
{ // A block is a single statement
int x; // Scope of x is from declaration to end of block
int x; // Scope of x is from declaration to end of block
}
if (x) a; // If x is true (not 0), evaluate a
else if (y) b; // If not x and y (optional, may be repeated)
@@ -114,9 +118,9 @@ for (x : y) a; // Range-based for loop e.g.
do a; while (x); // Equivalent to: a; while(x) a;
switch (x) { // x must be int
case X1: a; // If x == X1 (must be a const), jump here
case X2: b; // Else if x == X2, jump here
default: c; // Else jump here (optional)
case X1: a; // If x == X1 (must be a const), jump here
case X2: b; // Else if x == X2, jump here
default: c; // Else jump here (optional)
}
break; // Jump out of while, do, or for loop, or switch
continue; // Jump to bottom of while, do, or for loop
@@ -124,11 +128,12 @@ return x; // Return x from function to caller
try { a; }
catch (T t) { b; } // If a throws a T, then jump here
catch (...) { c; } // If a throws something else, jump here
~~~~
```
## FUNCTIONS
~~~~
int f(int x, int); // f is a function taking 2 ints and returning int
## Functions
```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(int a=0); // f() is equivalent to f(0)
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++(int); // postfix ++ or -- (parameter ignored)
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
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:
~~~~
int main() { statements... } or
```cpp
int main() { statements... } // or
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
higher for errors.
`argv` is an array of `argc` strings from the command line.
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
overloaded. Precedence order is not affected. New operators may not be created.
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.
## Expressions
## EXPRESSIONS
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
checks for arrays out of bounds, invalid pointers, etc.
~~~~
```cpp
T::X // Name X defined in class T
N::X // Name X defined in namespace N
::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
throw x // Throw exception, aborts if not caught
x , y // evaluates x and y, returns y (seldom used)
~~~~
```
## CLASSES
~~~~
## Classes
```cpp
class T { // A new type
private: // Section accessible only to T's member functions
protected: // Also accessable to classes derived from T
public: // Accessable to all
protected: // Also accessuble to classes derived from T
public: // Accessuble to all
int x; // Member data
void f(); // Member function
void g() {return;} // Inline member function
@@ -240,7 +247,7 @@ public: // Accessable to all
{x=t.x; return *this; } // Assignment operator
~T(); // Destructor (automatic cleanup routine)
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
{return x;} // Allows int(t)
friend void i(); // Global function i() has private access
@@ -268,15 +275,16 @@ class W: public T, public U {};
// Multiple inheritance
class X: public virtual T {};
// Classes derived from X have base T directly
~~~~
```cpp
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
constructor (required to create arrays) if the class has no constructors. Constructors, assignment, and
destructors do not inherit.
## TEMPLATES
~~~~
## Templates
```cpp
template <class T> T f(T t);// Overload f for all types
template <class T> class X {// Class with type parameter T
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"
template <class T, class U=T, int n=0>
// Template with default parameters
~~~~
```
## NAMESPACES
~~~~
## Namespaces
```cpp
namespace N {class T {};} // Hide name T
N::T t; // Use name T in namespace 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)
sin(x); cos(x); tan(x); // Trig functions, x (double) is in radians
asin(x); acos(x); atan(x); // Inverses
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
pow(x, y); sqrt(x); // x to the y, square root
ceil(x); floor(x); // Round up or down (as a double)
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)
assert(e); // If e is false, print message and abort
#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)
cin >> x >> y; // Read words x and y (any type) from stdin
cout << "x=" << 3 << endl; // Write line to stdout
@@ -327,23 +339,25 @@ 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 << ...;}
~~~~
```
## 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)
ifstream f1("filename"); // Open text file for reading
if (f1) // Test if open and input available
f1 >> x; // Read object from file
f1 >> x; // Read object from file
f1.get(s); // Read char or line
f1.getline(s, n); // Read line into string s[n]
ofstream f2("filename"); // Open file for writing
if (f2) f2 << x; // Write to file
~~~~
```
## STRING (Variable sized character array)
~~~~
## `string` (Variable sized character `array`)
```cpp
#include <string> // Include string (std namespace)
string s1, s2="hello"; // Create strings
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 = to_string(12.05); // Converts number to string
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)
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
@@ -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<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
~~~~
```
## DEQUE (array/stack/queue)
## `deque` (Array Stack Queue)
deque<T> is like vector&lt;T&gt;, but also supports:
~~~~
`deque<T>` is like `vector<T>`, but also supports:
```cpp
#include <deque> // Include deque (std namespace)
a.push_front(x); // Puts x at a[0], shifts elements toward back
a.pop_front(); // Removes a[0], shifts toward front
~~~~
```
## UTILITY (Pair)
~~~~
## `utility` (Pair)
```cpp
#include <utility> // Include utility (std namespace)
pair<string, int> a("hello", 3); // A 2-element struct
a.first; // "hello"
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)
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)
cout << p.first << p.second; // Prints hello, 3
cout << p.first << p.second; // Prints hello, 3
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)
min(x, y); max(x, y); // Smaller/larger of x, y (any type defining <)
swap(x, y); // Exchange values of variables x and y
sort(a, a+n); // Sort array a[0]..a[n-1] by <
sort(a.begin(), a.end()); // Sort vector or deque
~~~~
```