Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Latest commit

History

History
840 lines (673 loc) · 19.6 KB

File metadata and controls

840 lines (673 loc) · 19.6 KB
titleC++
date2021-06-01 04:51:44 -0700
iconicon-cpp
backgroundbg-blue-800
tags
categories
Programming
introC++ quick reference cheat sheet that provides basic syntax and methods.

Getting started {.cols-3}

hello.cpp

#include<iostream>intmain() {
std::cout << "Hello QuickRef\n";
return0;
}

Compiling and running

$ g++ hello.cpp -o hello
$ ./hello
Hello QuickRef

Variables

int number = 5; // Integerfloat f = 0.95; // Floating numberdoublePI = 3.14159; // Floating numberchar yes = 'Y'; // Character
std::string s = "ME"; // String (text)bool isRight = true; // Boolean// ConstantsconstfloatRATE = 0.8;

int age {25}; // Since C++11
std::cout << age; // Print 25

Primitive Data Types

Data TypeSizeRange
int4 bytes-2^31^ ^to^ 2^31^-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 ^to^ 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 ^or^ 4 bytes1 wide character
{.show-header}

User Input

int num;
std::cout << "Type a number: ";
std::cin >> num;
std::cout << "You entered " << num;

Swap

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;
// Outputs: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

Comments

// A single one line comment in C++/* This is a multiple line comment in C++ */

If statement

if (a == 10) {
// do something
}

See: Conditionals

Loops

for (int i = 0; i < 10; i++) {
std::cout << i << "\n";
}

See: Loops

Functions

#include<iostream>voidhello(); // Declaringintmain() { // main functionhello(); // Calling
}
voidhello() { // Defining
std::cout << "Hello QuickRef!\n";
}

See: Functions

References

int i = 1;
int& ri = i; // ri is a reference to i
ri = 2; // i is now changed to 2
std::cout << "i=" << i;
i = 3; // i is now changed to 3
std::cout << "ri=" << ri;

ri and i refer to the same memory location.

Namespaces

#include<iostream>namespacens1 {intval(){return5;}}
intmain()
{
std::cout << ns1::val();
}

#include<iostream>namespacens1 {intval(){return5;}}
usingnamespacens1;usingnamespacestd;intmain()
{
cout << val(); }

Namespaces allow global identifiers under a name

C++ Arrays {.cols-3}

Declaration

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// Declare and initializeint marks[3] = {92, 97, 98};
int marks[] = {92, 97, 98};
// With empty membersint marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

Manipulation

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
012345

int marks[6] = {92, 97, 98, 99, 98, 94};
// Print first element
std::cout << marks[0];
// Change 2th element to 99
marks[1] = 99;
// Take input from the user
std::cin >> marks[2];

Displaying

char ref[5] = {'R', 'e', 'f'};
// Range based for loopfor (constint &n : ref) {
std::cout << std::string(1, n);
}
// Traditional for loopfor (int i = 0; i < sizeof(ref); ++i) {
std::cout << ref[i];
}

Multidimensional

 j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘

int x[2][6] = {
{1,2,3,4,5,6}, {6,5,4,3,2,1}
};
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 6; ++j) {
std::cout << x[i][j] << "";
}
}
// Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ Conditionals {.cols-3}

If Clause

if (a == 10) {
// do something
}

int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// Outputs: even

Else if Statement

int score = 99;
if (score == 100) {
std::cout << "Superb";
}
elseif (score >= 90) {
std::cout << "Excellent";
}
elseif (score >= 80) {
std::cout << "Very Good";
}
elseif (score >= 70) {
std::cout << "Good";
}
elseif (score >= 60)
std::cout << "OK";
else
std::cout << "What?";

Operators {.row-span-2}

Relational Operators

a == ba is equal to b
a != ba is NOT equal to b
a < ba is less than b
a > ba is greater b
a <= ba is less than or equal to b
a >= ba is greater or equal to b

Assignment Operators

ExampleEquivalent to
a += bAka a = a + b
a -= bAka a = a - b
a *= bAka a = a * b
a /= bAka a = a / b
a %= bAka a = a % b

Logical Operators

ExampleMeaning
exp1 && exp2Both are true (AND)
`exp1
!expexp is false (NOT)

Bitwise Operators

OperatorDescription
a & bBinary AND
`ab`
a ^ bBinary XOR
a ~ bBinary One's Complement
a << bBinary Shift Left
a >> bBinary Shift Right

Ternary Operator

 ┌── True ──┐
Result = Condition ? Exp1 : Exp2;
└───── False ─────┘

int x = 3, y = 5, max;
max = (x > y) ? x : y;
// Outputs: 5
std::cout << max << std::endl;

int x = 3, y = 5, max;
if (x > y) {
max = x;
} else {
max = y;
}
// Outputs: 5
std::cout << max << std::endl;

Switch Statement

int num = 2;
switch (num) {
case0:
std::cout << "Zero";
break;
case1:
std::cout << "One";
break;
case2:
std::cout << "Two";
break;
case3:
std::cout << "Three";
break;
default:
std::cout << "What?";
break;
}

C++ Loops {.cols-3}

While

int i = 0;
while (i < 6) {
std::cout << i++;
}
// Outputs: 012345

Do-while

int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// Outputs: 12345

Continue statements

for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // Outputs: 13579

Infinite loop

while (true) { // true or 1
std::cout << "infinite loop";
}

for (;;) {
std::cout << "infinite loop";
}

for(int i = 1; i > 0; i++) {
std::cout << "infinite loop";
}

for_each (Since C++11)

#include<iostream>voidprint(int num)
{
std::cout << num << std::endl;
}
intmain()
{
int arr[4] = {1, 2, 3, 4 };
std::for_each(arr, arr + 4, print);
return0;
}

Range-based (Since C++11)

int num_array[] = {1, 2, 3, 4, 5};
for (int n : num_array) {
std::cout << n << "";
}
// Outputs: 1 2 3 4 5

std::string hello = "QuickRef.ME";
for (char c: hello)
{
std::cout << c << "";
}
// Outputs: Q u i c k R e f . M E 

Break statements

int password, times = 0;
while (password != 1234) {
if (times++ >= 3) {
std::cout << "Locked!\n";
break;
}
std::cout << "Password: ";
std::cin >> password; // input
}

Several variations

for (int i = 0, j = 2; i < 3; i++, j--){
std::cout << "i=" << i << ",";
std::cout << "j=" << j << ";";
}
// Outputs: i=0,j=2;i=1,j=1;i=2,j=0;

C++ Functions {.cols-3}

Arguments & Returns

#include<iostream>intadd(int a, int b) {
return a + b; }
intmain() {
std::cout << add(10, 20); }

add is a function taking 2 ints and returning int

Overloading

voidfun(string a, string b) {
std::cout << a + "" + b;
}
voidfun(string a) {
std::cout << a;
}
voidfun(int a) {
std::cout << a;
}

Built-in Functions

#include<iostream>
#include<cmath>// import libraryintmain() {
// sqrt() is from cmath
std::cout << sqrt(9);
}

C++ Classes & Objects {.cols-3}

If statement

If statement

If statement

If statement

C++ Preprocessor {.cols-3}

Preprocessor {.row-span-3}

Includes

#include"iostream"
#include<iostream>

Defines

#defineFOO
#defineFOO"hello"
#undef FOO

If {.row-span-2}

#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif

Error

#if VERSION == 2.0
#error Unsupported
#warning Not really supported
#endif

Macro

#defineDEG(x) ((x) * 57.29)

Token concat

#defineDST(name) name##_s name##_t
DST(object); #=> object_s object_t;

Stringification

#defineSTR(name) #name
char * a = STR(object); #=> char * a = "object";

file and line

#defineLOG(msg) console.log(__FILE__, __LINE__, msg)
#=> console.log("file.txt", 3, "hey")

Miscellaneous {.cols-3}

Escape Sequences

Escape SequencesCharacters
\bBackspace
\fForm feed
\nNewline
\rReturn
\tHorizontal tab
\vVertical tab
\\Backslash
\'Single quotation mark
\"Double quotation mark
\?Question mark
\0Null Character

Keywords {.col-span-2 .row-span-2}

Preprocessor

Also see