提供基本語法和方法的 C++ 快速參考備忘單
#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
| 數據類型 | 大小 | 范圍 |
|---|---|---|
int | 4 bytes | -231 到 231-1 |
float | 4 bytes | N/A |
double | 8 bytes | N/A |
char | 1 byte | -128 到 127 |
bool | 1 byte | true / false |
void | N/A | N/A |
wchar_t | 2 到 4 bytes | 1 個寬字符 |
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 (a == 10) {
// do something
}
查看: 條件
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;
ri 和 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();
}
名稱空間允許名稱下的全局標識符
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
if (a == 10) {
// do something
}
int number = 16;
if (number % 2 == 0)
{
std::cout << "even";
}
else
{
std::cout << "odd";
}
// 輸出: even
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 == b | a 等于 b |
a != b | a 不等于 b |
a < b | a 小于 b |
a > b | a 大于 b |
a <= b | a 小于或等于 b |
a >= b | a 大于或等于 b |
| 范例 | 相當于 |
|---|---|
a += b | Aka a = a + b |
a -= b | Aka a = a - b |
a *= b | Aka a = a * b |
a /= b | Aka a = a / b |
a %= b | Aka a = a % b |
| Example | Meaning |
|---|---|
exp1 && exp2 | Both are true (AND) |
| `exp1 | |
!exp | exp is false (NOT) |
| Operator | Description |
|---|---|
a & b | Binary AND |
| `a | b` |
a ^ b | Binary XOR |
a ~ b | Binary One's Complement |
a << b | Binary Shift Left |
a >> b | Binary 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;
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;
}
int i = 0;
while (i < 6) {
std::cout << i++;
}
// 輸出: 012345
int i = 1;
do {
std::cout << i++;
} while (i <= 5);
// 輸出: 12345
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue;
}
std::cout << i;
} // 輸出: 13579
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";
}
#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;
}
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
}
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;
#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 表達式可以在函數內定義,可以理解為在函數內定義的臨時函數。格式:
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
<< " ";
});
g++編譯選項:-std=c++11。包含頭文件:
#include <thread>:C++多線程庫#include <mutex>:C++互斥量庫#include <future>:C++異步庫以普通函數作為線程入口函數:
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_variablestd::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ù)加鎖,直到再次被 notifiedtrue,那么wait返回,繼續(xù)執(zhí)行流程wait沒有第二個參數,那么直接返回,繼續(xù)執(zhí)行std::condition_variable::notify_onenotify_one 喚醒一個調用 wait 的線程。注意在喚醒之前要解鎖,否則調用 wait 的線程也會因為無法加鎖而阻塞。
std::condition_variable::notify_all喚醒所有調用 wait 的線程。
#include <future>
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)自行決定讓當前線程等待一段時間(等待到指定時間點),以期待返回值準備好:
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中存儲對象的指針,而非指針本身。
#include "iostream"
#include <iostream>
#define FOO
#define FOO "hello"
#undef FOO
#ifdef DEBUG
console.log('hi');
#elif defined VERBOSE
...
#else
...
#endif
#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")
| 轉義序列 | 說明 |
|---|---|
\b | 退格鍵 |
\f | 換頁 |
\n | 換行 |
\r | 返回 |
\t | 水平制表符 |
\v | 垂直制表符 |
\\ | 反斜杠 |
\' | 單引號 |
\" | 雙引號 |
\? | 問號 |
\0 | 空字符 |
感谢您访问我们的网站,您可能还对以下资源感兴趣:
国产成人精品999视频&日本一区二区亚洲人妻精品&久久久精品国产99久久精&99热这里只有成人精品国产&精品国产剧情av一区二区&成人亚洲精品久久久久app&国产精品美女高潮抽搐A片