C++ 備忘單

2022-06-13 15:28 更新

提供基本語法和方法的 C++ 快速參考備忘單。

開始

Hello.cpp

#include <iostream>

int main() {
    std::cout << "Hello QuickRef\n";
    return 0;
}

編譯和運(yùn)行

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

變量

int number = 5;       // Integer
float f = 0.95;       // Floating number
double PI = 3.14159;  // Floating number
char yes = 'Y';       // Character
std::string s = "ME"; // String (text)
bool isRight = true;  // Boolean

// Constants
const float RATE = 0.8;

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

原始數(shù)據(jù)類型

數(shù)據(jù)類型 尺寸 范圍
int 4字節(jié) -2 31 ~ 2 31 -1
float 4字節(jié) 不適用
double 8 字節(jié) 不適用
char 1 字節(jié) -128 ~ 127
bool 1 字節(jié) true / false
void 不適用 不適用
wchar_t 或 4 個(gè)字節(jié) 1 個(gè)寬字符

用戶輸入

int num;

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

std::cout << "You entered " << num;

交換

int a = 5, b = 10, temp;
temp = a;
a = b;
b = temp;

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

注釋

// A single one line comment in C++

/* This is a multiple line comment
   in C++ */

if 語句

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

請(qǐng)參閱:條件

for 循環(huán)

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

請(qǐng)參閱:循環(huán)

函數(shù)

#include <iostream>
 
void hello(); // Declaring
 
int main() {  // main function
    hello();    // Calling
}
 
void hello() { // Defining
    std::cout << "Hello QuickRef!\n";
}

請(qǐng)參閱:函數(shù)

參考

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;

rii引用相同的內(nèi)存位置。

命名空間

#include <iostream>
namespace ns1 {int val(){return 5;}}
int main()
{
    std::cout << ns1::val();
}

#include <iostream>
namespace ns1 {int val(){return 5;}}
using namespace ns1;
using namespace std;
int main()
{
    cout << val(); 
}

命名空間允許名稱下的全局標(biāo)識(shí)符

C++ 數(shù)組

聲明

int marks[3]; // Declaration
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;

// Declare and initialize
int marks[3] = {92, 97, 98};
int marks[]  = {92, 97, 98};

// With empty members
int marks[3] = {92, 97};
std::cout << marks[2]; // Outputs: 0

操作

┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92  | 97  | 98  | 99  | 98  | 94  |
└─────┴─────┴─────┴─────┴─────┴─────┘
   0     1     2     3     4     5

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];

顯示

char ref[5] = {'R', 'e', 'f'};

// Range based for loop
for (const int &n : ref) {
    std::cout << std::string(1, n);
}

// Traditional for loop
for (int i = 0; i < sizeof(ref); ++i) {
    std::cout << ref[i];
}

多維數(shù)組

     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++ 條件

if 語句

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

int number = 16;

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

// Outputs: even

Else if 語句

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

運(yùn)算符

關(guān)系運(yùn)算符

a == b a 等于 b
a != b a 不等于 b
a < b a 小于 b
a > b a 更大 b
a <= b a 小于或等于 b
a >= b a 大于或等于 b

賦值運(yùn)算符

a += b 又名 a = a + b
a -= b 又名 a = a - b
a *= b 又名 a = a * b
a /= b 又名 a = a / b
a %= b 又名 a = a % b

邏輯運(yùn)算符

exp1 && exp2 兩者都是真的(AND)
exp1 || exp2 要么為真(或)
!exp exp是假的(不是)

位運(yùn)算符

a & b 二進(jìn)制與
a | b 二進(jìn)制或
a ^ b 二進(jìn)制異或
a ~ b 二進(jìn)制補(bǔ)碼
a << b 二進(jìn)制左移
a >> b 二進(jìn)制右移

三元運(yùn)算符

           ┌── 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 語句

int num = 2;
switch (num) {
    case 0:
        std::cout << "Zero";
        break;
    case 1:
        std::cout << "One";
        break;
    case 2:
        std::cout << "Two";
        break;
    case 3:
        std::cout << "Three";
        break;
    default:
        std::cout << "What?";
        break;
}

C++ 循環(huán)

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 語句

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

無限循環(huán)

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 (從 C++11 版本開始)

#include <iostream>

void print(int num)
{
    std::cout << num << std::endl;
}

int main()
{
    int arr[4] = {1, 2, 3, 4 };
    std::for_each(arr, arr + 4, print);
    return 0;
}

Range-based (從 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 語句

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

幾種變體

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++ 函數(shù)

參數(shù)和返回

#include <iostream>

int add(int a, int b) {
    return a + b;  
}

int main() {
    std::cout << add(10, 20); 
}

add 是一個(gè)接受 2 個(gè)整數(shù)并返回整數(shù)的函數(shù)

Overloading 超載

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

內(nèi)置函數(shù)

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

C++ 預(yù)處理器

Includes 包括

#include "iostream"
#include <iostream>

Defines 定義

#define FOO
#define FOO "hello"

#undef FOO

If 如果

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

Error 錯(cuò)誤

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

Macro 宏

#define DEG(x) ((x) * 57.29)

Token concat 令牌連接

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

Stringification 字符串化

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

file and line 文件和行

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

另見


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)