国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片

C++ 備忘清單

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

入門

hello.cpp

#include <iostream>
int main() {
    std::cout << "Hello Quick Reference\n";
    return 0;
}

編譯運行

$ g++ hello.cpp -o hello
$ ./hello
Hello Quick Reference

變量

int number = 5;       // 整數
float f = 0.95;       // 浮點數
double PI = 3.14159;  // 浮點數
char yes = 'Y';       // 特點
std::string s = "ME"; // 字符串(文本)
bool isRight = true;  // 布爾值
// 常量
const float RATE = 0.8;

int age {25};      // 自 C++11
std::cout << age;  // 打印 25

原始數據類型

數據類型大小范圍
int4 bytes-231 到 231-1
float4 bytesN/A
double8 bytesN/A
char1 byte-128 到 127
bool1 bytetrue / false
voidN/AN/A
wchar_t2 到 4 bytes1 個寬字符

用戶輸入

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

交換

int a = 5, b = 10;
std::swap(a, b);
// 輸出: a=10, b=5
std::cout << "a=" << a << ", b=" << b;

注釋

// C++中的單行注釋
/* 這是一個多行注釋
    在 C++ 中 */

If 語句

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

查看: 條件

循環(huán)

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

查看: 循環(huán) Loops

函數

#include <iostream>
 
void hello();   // 聲明
 
int main() {    // 主函數
    hello();    // 執(zhí)行函數
}
 
void hello() { // 定義
  std::cout << "Hello Quick Reference!\n";
}

查看: 函數 Functions

引用

int i = 1;
int& ri = i; // ri 是對 i 的引用
ri = 2; // i 現在改為 2
std::cout << "i=" << i;
i = 3;   // i 現在改為 3
std::cout << "ri=" << ri;

rii 指的是相同的內存位置

命名空間

#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(); 
}

名稱空間允許名稱下的全局標識符

C++ 數組

定義

std::array<int, 3> marks; // 定義
marks[0] = 92;
marks[1] = 97;
marks[2] = 98;
// 定義和初始化
std::array<int, 3> = {92, 97, 98};
// 有空成員
std::array<int, 3> marks = {92, 97};
std::cout << marks[2]; // 輸出: 0

操控

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

std::array<int, 6> marks = {
  92, 97, 98, 99, 98, 94
};
// 打印第一個元素
std::cout << marks[0];
// 將第 2 個元素更改為 99
marks[1] = 99;
// 從用戶那里獲取輸入
std::cin >> marks[2];

展示

char ref[5] = {'R', 'e', 'f'};
// 基于范圍的for循環(huán)
for (const int &n : ref) {
    std::cout << std::string(1, n);
}
// 傳統(tǒng)的for循環(huán)
for (int i = 0; i < sizeof(ref); ++i) {
    std::cout << ref[i];
}

多維

     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] << " ";
    }
}
// 輸出: 1 2 3 4 5 6 6 5 4 3 2 1 

C++ 條件

If Clause

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

int number = 16;
if (number % 2 == 0)
{
    std::cout << "even";
}
else
{
    std::cout << "odd";
}
// 輸出: 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?";

運算符

關系運算符

:----
a == ba 等于 b
a != ba 不等于 b
a < ba 小于 b
a > ba 大于 b
a <= ba 小于或等于 b
a >= ba 大于或等于 b

賦值運算符

范例相當于
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

邏輯運算符

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

位運算符

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

三元運算符

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

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

int x = 3, y = 5, max;
if (x > y) {
    max = x;
} else {
    max = y;
}
// 輸出: 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++;
}
// 輸出: 012345

Do-while

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

Continue 語句

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

無限循環(huán)

while (true) { // true or 1
    std::cout << "無限循環(huán)";
}

for (;;) {
    std::cout << "無限循環(huán)";
}

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

for_each (C++11 起)

#include <iostream>
int main()
{
    auto print = [](int num) {
      std::cout << num << std::endl;
    };
    std::array<int, 4> arr = {1, 2, 3, 4};
    std::for_each(arr.begin(), arr.end(), print);
    return 0;
}

基于范圍 (C++11 起)

for (int n : {1, 2, 3, 4, 5}) {
    std::cout << n << " ";
}
// 輸出: 1 2 3 4 5

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

中斷語句

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 << ";";
}
// 輸出: i=0,j=2;i=1,j=1;i=2,j=0;

C++ 函數

參數和返回

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

add 是一個接受 2 個整數并返回整數的函數

重載

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

內置函數

#include <iostream>
#include <cmath> // 導入庫
 
int main() {
    // sqrt() 來自 cmath
    std::cout << sqrt(9);
}

Lambda 表達式

Lambda 表達式可以在函數內定義,可以理解為在函數內定義的臨時函數。格式:

auto func = []() -> return_type { };
  • []為捕獲列表,能夠捕獲其所在函數的局部變量

    • 一個空的捕獲列表代表Lambda表達式不捕獲任何的變量

    • 對于值捕獲,直接在中括號中填寫要捕獲的變量即可:

      int val = 5;
      auto func = [val]() -> return_type { };
      
  • 對于引用捕獲,需要在捕獲的變量前添加&

    string str("hello world!");
    auto func = [&str]() -> return_type { };
    
  • 如果變量太多,需要編譯器根據我們編寫的代碼自動捕獲,可以采用隱式捕獲的方式。

    • 全部值捕獲:

      int val1, val2;
      auto func = [=]() -> int
          {
              return val1 + val2;
          };
      
    • 全部引用捕獲:

      string str1("hello"), str2("word!");
      auto func = [&]() -> string
          {
              return str1 + str2;
          };
      
    • 混合隱式捕獲:

      如果希望對一部分變量采用值捕獲,對其他變量采用引用捕獲,可以混合使用:

      int val1 = 123, val2 = 456;
      string str1("123"), str2(456);
      
      auto func1 = [=, &str1]() -> int
          {
              return   val1 == std::stoi(str1) 
                    ? val1 : val2;
          };
          
      auto func2 = [&, val1]() -> int
          {
              return   str1 == std::to_string(val1) 
                    ? str1 : str2;
          };
      
  • () 是參數列表,我們只需要按照普通函數的使用方法來使用即可

  • return_type 是函數的返回類型,-> return_type 可以不寫,編譯器會自動推導

  • {} 中的內容就是函數體,依照普通函數的使用方法使用即可

此處給出一個 Lambda 表達式的實際使用例子(當然可以使用 str::copy):

// vec中包含1, 2, 3, 4, 5
std::vector<int> vec({1, 2, 3, 4, 5});  
std::for_each(vec.begin(), vec.end(), 
              [](int& ele) -> void
          {
              std::cout << ele 
                          << " ";
          });

C++多線程

多線程介紹

g++編譯選項:-std=c++11。包含頭文件:

  • #include <thread>:C++多線程庫
  • #include <mutex>:C++互斥量庫
  • #include <future>:C++異步庫

線程的創(chuàng)建

以普通函數作為線程入口函數:

void entry_1() { }
void entry_2(int val) { }

std::thread my_thread_1(entry_1);
std::thread my_thread_2(entry_2, 5);

以類對象作為線程入口函數:

class Entry
{
    void operator()() { }
    void entry_function() { }
};

Entry entry;
// 調用operator()()
std::thread my_thread_1(entry);  
// 調用Entry::entry_function
std::thread my_thread_2(&Entry::entry_function, &entry);  

以lambda表達式作為線程入口函數:

std::thread my_thread([]() -> void 
      {
         // ... 
      });

線程的銷毀

thread my_thread;
// 阻塞
my_thread.join();
// 非阻塞
my_thread.detach();

this_thread

// 獲取當前線程ID
std::this_thread::get_id();  
// 使當前線程休眠一段指定時間
std::this_thread::sleep_for();  
// 使當前線程休眠到指定時間
std::this_thread::sleep_until();
// 暫停當前線程的執(zhí)行,讓別的線程執(zhí)行
std::this_thread::yield();    

#include <mutex>

鎖的基本操作

創(chuàng)建鎖

std::mutex m;

上鎖

m.lock();

解鎖

m.unlock();

嘗試上鎖:成功返回true,失敗返回false

m.try_lock();

解鎖

m.unlock();

更簡單的鎖 —— std::lock_guard<Mutex>

構造時上鎖,析構時解鎖

std::mutex m;
std::lock_guard<std::mutex> lock(m);

額外參數:std::adopt_lock:只需解鎖,無需上鎖

// 手動上鎖
m.lock();
std::lock_guard<mutex> lock(m, 
    std::adopt_lock);

unique_lock<Mutex>

構造上鎖,析構解鎖

std::mutex m;
std::unique_lock<mutex> lock(m);
std::adopt_lock

只需解鎖,無需上鎖

// 手動上鎖
m.lock();
std::unique_lock<mutex> lock(m, 
    std::adopt_lock);
std::try_to_lock

嘗試上鎖,可以通過std::unique_lock<Mutex>::owns_lock()查看狀態(tài)

std::unique_lock<mutex> lock(m, 
    std::try_to_lock);
if (lock.owns_lock())
{
    // 拿到了鎖
}
else
{
    // 沒有
}
std::defer_lock

綁定鎖,但不上鎖

std::unique_lock<mutex> lock(m,
    std::defer_lock);
lock.lock();
lock.unlock();
std::unique_lock<Mutex>::release

返回所管理的mutex對象指針,**釋放所有權。**一旦釋放了所有權,那么如果原來互斥量處于互斥狀態(tài),程序員有責任手動解鎖。

std::call_once

當多個線程通過這個函數調用一個可調用對象時,只會有一個線程成功調用。

std::once_flag flag;

void foo() { }

std::call_once(flag, foo);

std::condition_variable

創(chuàng)建條件變量

std::condition_variable cond;

等待條件變量被通知

std::unique_lock<std::mutex>
    lock;
extern bool predicate();

// 調用方式 1
cond.wait(lock);
// 調用方式 2
cond.wait(lock, predicate);

  • wait不斷地嘗試重新獲取并加鎖該互斥量,如果獲取不到,它就卡在這里并反復嘗試重新獲取,如果獲取到了,執(zhí)行流程就繼續(xù)往下走
  • wait在獲取到互斥量并加鎖了互斥量之后:
    • 如果wait被提供了可調用對象,那么就執(zhí)行這個可調用對象:
      • 如果返回值為false,那么wait繼續(xù)加鎖,直到再次被 notified
      • 如果返回值為true,那么wait返回,繼續(xù)執(zhí)行流程
    • 如果wait沒有第二個參數,那么直接返回,繼續(xù)執(zhí)行

std::condition_variable::notify_one

notify_one 喚醒一個調用 wait 的線程。注意在喚醒之前要解鎖,否則調用 wait 的線程也會因為無法加鎖而阻塞。

std::condition_variable::notify_all

喚醒所有調用 wait 的線程。

獲取線程的運行結果

#include <future>

創(chuàng)建異步任務

double func(int val); 

// 使用std::async創(chuàng)建異步任務
// 使用std::future獲取結果
// future模板中存放返回值類型
std::future<double> result = 
    std::async(func, 5);

獲取異步任務的返回值

等待異步任務結束,但是不獲取返回值:

result.wait();

獲取異步任務的返回值:

int val = result.get();

注:

  • get()返回右值,因此只可調用一次
  • 只要調用上述任意函數,線程就會一直阻塞到返回值可用(入口函數運行結束)

std::async 的額外參數

額外參數可以被放在 std::async 的第一個參數位置,用于設定 std::async 的行為:

  • std::launch::deferred:入口函數的運行會被推遲到std::future<T>::get()或者std::future<T>::wait()被調用時。此時調用線程會直接運行線程入口函數,換言之,不會創(chuàng)建子線程
  • std::launch::async:立即創(chuàng)建子線程,并運行線程入口函數
  • std::launch::deferred | std::launch::async:默認值,由系統(tǒng)自行決定

返回值的狀態(tài)

讓當前線程等待一段時間(等待到指定時間點),以期待返回值準備好:

extern double foo(int val) {}

std::future<double> result = 
    async(foo, 5);

//返回值類型
std::future_status status;
// 等待一段時間
status = result.wait_for(
  std::chrono::seconds(1)
  );
// 等待到某一時間點
status = result.wait_for(
  std::chrono::now() +
    std::chrono::seconds(1)
  );

在指定的時間過去后,可以獲取等待的結果:

// 返回值已經準備好
if (status == 
     std::future_status::ready)
{
    
}
// 超時:尚未準備好
else if (status ==
    std::future_status::timeout)
{ }
// 尚未啟動: std::launch::deferred
else if (status ==
    std::future_status::deferred)
{ }

多個返回值

std::shared_future<T> result;

如果要多次獲取結果,可以使用std::shared_future,其會返回結果的一個拷貝

對于不可拷貝對象,可以在std::shared_future中存儲對象的指針,而非指針本身。

C++ 預處理器

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

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

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

令牌連接

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

字符串化

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

文件和行

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

另見