# C++程式筆記(微C語言) 感興趣也就先去學了一下,都會記筆記下來,以便以後忘記的時候可以拿出來看 [TOC] ## 開啟檔案 其實有很多方式,只是我常用這種方式來寫程式 ✔️Code::Blocks方式: ![螢幕擷取畫面 2025-01-03 093720](https://hackmd.io/_uploads/rygAJ64Lkl.png) ![螢幕擷取畫面 2025-01-03 093736](https://hackmd.io/_uploads/HkxAk6VUkl.png) ✔️Dev-C++方式: ![螢幕擷取畫面 2025-04-07 163629](https://hackmd.io/_uploads/ryf3CW-R1e.png=) ![螢幕擷取畫面 2025-04-07 164706](https://hackmd.io/_uploads/SyeXZMbRkx.png) 常使用方法: ```cpp= #include <iostream> #include <cstdio> //使用c語言printf... using namespace std; //就不用前後寫std ``` ## cin 輸入 ```cpp= int i ; cin >> i ; ``` 中間以空白隔開書寫進去兩個數字 ```cpp= int N, T; cin >> N >> T; // 輸入12 15 ``` ---- ### 固定大小(陣列方式) * 輸入12 40 22讀取 使用陣列方式,將資料存入 ```cpp= int arr[3]; // 陣列大小固定為 3 std::cout << "Enter three numbers: "; std::cin >> arr[0] >> arr[1] >> arr[2]; // 直接讀取並存入陣列 std::cout << "You entered: " << arr[0] << " " << arr[1] << " " << arr[2] << std::endl; ``` 🔹 輸入: 12 33 21 🔹 輸出: You entered: 12 33 21 ### 不固定大小(vector方式) ```cpp= while (std::cin >> num) { // 讀取直到輸入結束 numbers.push_back(num); } ``` ### 切割方式 (istringstream) * 將一整行字串當作輸入流來解析。 * 透過 >> 運算子,可以像 std::cin 一樣讀取數據,並自動以空白(空格、Tab、換行)作為分隔符。 ```cpp= std::string input = "12 33 21"; // 假設這是輸入的字串 std::istringstream iss(input); // 創建一個輸入字串流 (istringstream) int num; while (iss >> num) { // 逐個讀取數字 std::cout << "Read number: " << num << std::endl; } ``` ## scanf() 輸入 scanf() 是 C 語言的輸入函式,在 C++ 也可以使用(來自 < cstdio >) ```cpp= #include <cstdio> // 引入 cstdio ``` ```cpp= printf("請輸入整數、小數、單個字元:"); scanf("%d %lf %c", &a, &b, &c); printf("輸入的整數:%d\n", a); printf("輸入的小數:%.2f\n", b); printf("輸入的字元:%c\n", c); ``` ### 格式化字串 | 格式符號 | 讀取類型 | 範例 | | -------- | -------------------- | --------------------------- | | %d | 整數(int) | scanf("%d", &x); | | %ld | 長整數(long) | scanf("%ld", &x); | | %f | 單精度浮點數(float)| scanf("%f", &x); | | %lf | 雙精度浮點數(double)| scanf("%lf", &x); | | %c | 單個字元(char) | scanf("%c", &ch); | | %s | 字串(char 陣列) | scanf("%s", str); | ### %s注意 ⚠️ 注意: * %s 遇到空格會停止讀取,所以 "Hello World" 只會讀取 "Hello"。 * %s 是char陣列模式,如果要輸出string陣列需要轉換 item[i].c_str() ```cpp= #include <cstdio> int main() { char name[50]; // 字串陣列 printf("請輸入你的名字:"); scanf("%s", name); printf("你好, %s!\n", name); return 0; } ``` ### 讀取整行 scanf("%[^\n]s", str); ```cpp= #include <cstdio> int main() { char name[100]; printf("請輸入你的全名:"); scanf(" %[^\n]s", name); // 讀取整行,包括空格 printf("你的全名是: %s\n", name); return 0; } ``` 📌 scanf(" %[^\n]s", name); 解釋 * %[^\n]:表示讀取 直到換行符 \n 為止,即讀取整行文字。 * 前面空格 " ":可以跳過 scanf() 之前殘留的 \n(避免錯誤)。 ### 讀取多個值 ````cpp= #include <cstdio> int main() { int x, y; printf("請輸入兩個數字(用空格分開):"); scanf("%d %d", &x, &y); printf("你輸入的數字是:%d 和 %d\n", x, y); return 0; } ```` --- ### 輸入錯誤示範 將輸入一整個放在int裡面,如果輸入的是正確的會回傳1,否則就是錯誤的輸入 ```cpp= int x; printf("請輸入一個整數:"); int result = scanf("%d", &x); if (result != 1) { printf("輸入錯誤!請輸入有效的整數。\n"); } ``` ## cout 輸出 endl為換行程式碼 ```cpp= cout << “fukk yooo” << endl; // 自動換行 ``` ## printf()輸出 printf()是 C 語言的輸入函式,在 C++ 也可以使用(來自 < cstdio >) ```cpp= #include <cstdio> // 引入 cstdio ``` ```cpp= #include <cstdio> // 引入 cstdio using namespace std; int main() { int a = 10; double b = 3.14159; char c = 'A'; char str[] = "Hello"; printf("整數:%d\n", a); printf("浮點數:%.2f\n", b); printf("字元:%c\n", c); printf("字串:%s\n", str); return 0; } ``` ### 格式符號 | 格式符號 | 類型 | 範例 | |-----------|-------------------|----------------------------------| | %d | 整數(int) | printf("%d", 10); | | %ld | 長整數(long) | printf("%ld", 100000L); | | %f | 浮點數(float) | printf("%f", 3.14); | | %lf | 雙精度浮點數(double) | printf("%lf", 3.14159); | | %.nf | 小數點後 n 位 | printf("%.2f", 3.14159); // 3.14 | | %c | 單個字元(char) | printf("%c", 'A'); | | %s | 字串(char 陣列) | printf("%s", "Hello"); | ### 控制數量 * 控制小數點後 數量 在屬性前面加上.(數量) ```cpp= #include <cstdio> int main() { double pi = 3.1415926535; printf("預設輸出:%f\n", pi); printf("保留 2 位小數:%.2f\n", pi); printf("保留 5 位小數:%.5f\n", pi); return 0; } ``` 輸出: ``` 預設輸出:3.141593 保留 2 位小數:3.14 保留 5 位小數:3.14159 ``` * 控制輸出寬度 ```cpp= #include <cstdio> int main() { int num = 42; printf("數字:%d\n", num); printf("寬度 5:%5d\n", num); printf("左對齊(`-`):%-5d\n", num); printf("補 0,寬度 5:%05d\n", num); return 0; } ``` 輸出: ``` 數字:42 寬度 5: 42 左對齊(`-`):42 補 0,寬度 5:00042 ``` ## 變數 如同數學中的x , 存一個東西在其中 基本分為: * bool布林值分為false、ture在判斷中可以用到 * char單字元'A' 或 '4' * string字串 "asdcs548" 或 "嗨搂你好喔" * int,float,double 皆是存取數字的,int 為存整數沒有任何小數或負數,其他的由左至由存取的數字多越多區分 * auto 是 C++ 中的一個關鍵字,意思是「自動推斷變數型別」。 ### 全域變數 🔹 直接宣告在main外 🔹 方法一:使用 #define(文字替換) 特色: * 編譯前會把所有出現 PI 的地方直接換成 3.14。 * 沒有資料型別。 * 是在編譯前「取代文字」。 * 全域有效(任何地方都能用)。 ```cpp= #include <iostream> #define PI 3.14 // 定義符號常數 int main() { float radius = 2; float area = PI * radius * radius; std::cout << "面積 = " << area << std::endl; return 0; } ``` 🔹 方法二:使用 const (值固定不變) 特色: * 有資料型別。 * 編譯器可以檢查型別正確性。 * 可以限制作用範圍(區域或全域都行)。 * 推薦用 const,比 #define 更安全。 ```cpp= #include <iostream> const float PI = 3.14f; // 全域常數 int main() { float radius = 2; float area = PI * radius * radius; std::cout << "面積 = " << area << std::endl; return 0; } ``` ```cpp= #include <iostream> int count = 0; // 全域變數(通常不建議濫用) const int MAX_SCORE = 100; // 🔅全域常數 int main() { } ``` 🔹 各類全域變數 小小總結: | 宣告方式 | 範例 | 範圍 | 建議用法 | |------------------|--------------------------|--------|----------------------| | #define | #define PI 3.14 | 全域 | ❌ 不推薦,容易出錯 | | const (區域) | const int x = 5; | 區域 | ✅ 安全 | | const (全域) | const float PI = 3.14f; | 全域 | ✅ 很推薦 | | 全域變數 | int count = 0; | 全域 | ⚠️ 慎用 | 🔹#define與const差別 | 特性 | #define | const | |--------------------------|-------------------------------|----------------------------------| | 本質 | 編譯前的文字替換 | 有型別的變數,執行期存在記憶體 | | 型別安全 | ❌ 沒型別 | ✅ 有型別(例如 int, float) | | 可否取記憶體位址 | ❌ 不可取位址 | ✅ 可以取址(如 &constVar) | | 可否除錯顯示變數值 | ❌ 不行,因為不存在變數 | ✅ 可以 | | 範圍(scope) | 全檔案有效(無作用域) | 有作用域(block / file) | | 預設 linkage | 無 | const 有 internal linkage | | 編譯期常數 | ✅ 是 | ✅ 是(若搭配 const int x = 3) | | 是否佔用記憶體 | ❌ 不會 | ✅ 會佔空間(儲存在記憶體中) | ### 屬性轉換 * string 轉換為 int stoi>>> ```cpp= string str = "456"; int number = stoi(str); ``` * int 轉換為 string to_string>>> ```cpp= int number = 123; string str = to_string(number); ``` * char 轉換為 int 去減掉數字 0 ! ```cpp= string inpu1="65482" int digit = inpu1[3] - '0'; ``` * int ↔ float ↔ double ```cpp= int a = 10; double b = a; // 自動轉成 double:10.0 -------------------------------------- double x = 3.14; int y = (int)x; // y 變成 3(小數會被砍掉) ``` * string轉成 C-style 字串 因為C語言裡沒有string,就需要轉換成 ```cpp= string str = "Hello"; printf("%s\n", str.c_str()); // 用 .c_str() 轉成 C-style 字串 ``` ### 顯示 2 位小數 ```cpp= #include <iomanip> // 設定小數位數 int main() { // 設定小數點後兩位 cout << fixed << setprecision(2); } ``` ### C語言char[] = string 在C語言裡面沒有string,如果要使用到字串,則需要使用到char[] ```css= #include <stdio.h> int main() { char name[20] = "Hello"; // 至少要多留一個空間給 '\0' printf("%s\n", name); return 0; } ``` | 函式 | 功能 | 範例 | |---------------|----------------------------|-------------------------------| | strlen(str) | 傳回字串長度(不含 \0) | strlen("abc") ➜ 3 | | strcpy(dest, src) | 複製字串 | strcpy(a, b) | | strcat(dest, src) | 將 src 接到 dest 後面 | strcat(a, b) | | strcmp(a, b) | 比較字串(相等回傳 0) | strcmp("hi", "hi") | | strchr(str, c) | 找某個字元第一次出現的位置 | strchr("abc", 'b') | | strstr(a, b) | 找子字串的位置 | strstr("apple", "pl") | ## isNumber 判斷是否為數字 ```cpp= // 檢查字串是否都是數字 bool isNumber(const string& str) { for (char c : str) { if (!isdigit(c)) return false; // 只要有一個非數字就回傳 false } return !str.empty(); // 避免空字串 } string answ; int much; cout << "請輸入一個數字:"; cin >> answ; if (isNumber(answ)) { much = stoi(answ); cout << "轉換後的數字:" << much << endl; } else { cout << "錯誤!請輸入有效的數字!" << endl; } ``` ## 陣列(限制範圍) 皆為從0開始載入數值 此為有固定的大小,設定5個則為5個 ```cpp= int sco[10]={50,30,55} sort(sco.begin(), sco.end()); //從小排到大 ``` ### 加入元素 ```cpp= int size = 5; score[size] = 6; ``` ### 刪除元素 在意義上是沒有刪除的,就是讓他重新排序,覆蓋掉要刪掉的數值 ## 二維陣列 ```cpp= int arr[2][2] = { {2, 3}, {4, 3} }; ---------------------- int arr[2][2] = {{2,3}, {4,3}}; ``` ### 二維陣列(foreach) 如果你使用的是 固定大小的二維陣列(如 int arr[3][4]),是可以用兩層 range-based for: ```cpp= int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; for (auto& row : arr) { for (auto& col : row) { cout << col << " "; } cout << endl; } ``` 這裡 row 是 int[4] 的參考(也就是一整列),col 就是每一個整數。 ### 二維陣列 取得長度 * sizeof(arr[0]) 取得第一個設定的大小長度 * sizeof(arr[0][0]) 取得第二個長度 ```cpp= int arr[3][4]; int row_count = sizeof(arr) / sizeof(arr[0]); // 3 int col_count = sizeof(arr[0]) / sizeof(arr[0][0]); // 4 ``` ### vector<vector< int >>(動態大小的二維陣列) ```cpp= #include <vector> using namespace std; vector<vector<int>> arr = { {2, 3}, {4, 3} }; ``` 👉 這種方式可以用在不知道大小的情況,也可以後續 push_back() 新的列進去,非常彈性。 * 初始化為全部 0 如果你想要先建立一個固定大小、初始為 0 的陣列,可以這樣: ```cpp= int arr[2][2] = {}; // 每個元素自動初始化為 0 // 或 vector 版本: vector<vector<int>> arr(2, vector<int>(2, 0)); // 2x2 全為 0 ``` ## Vector 陣列(無限制範圍) 皆為從0開始載入數值 ```cpp= vector<int> arr = {1, 2, 3, 4, 5}; ``` ### 加入元素 ```cpp= arr.push_back(6); // 在末尾加入6 arr.insert(arr.begin() + 2, 99); // 在索引2位置插入99 ``` ### 刪除元素 ```cpp= arr.pop_back(); // 刪除末尾元素 arr.erase(arr.begin() + 1); // 刪除索引1的元素 ``` ### 取得vector長度 ```cpp= vector.size(); ``` ### 排列 ```cpp= sort(v.begin(), v.end()); ``` ### 二微陣列 ```cpp= vector<vector<int>> n; // 第一行 vector<int> row1 = {1, 2, 3}; n.push_back(row1); // 第二行 vector<int> row2; row2.push_back(4); row2.push_back(5); n.push_back(row2); // 第三行也可以直接加: n.push_back({6, 7}); ``` ## unordered_set 你可以在 C++ 裡用 `unordered_set` 來存放「不重複的元素」,查找速度 **平均 O(1)**,非常快。 ### 1. 引入標頭 ```cpp #include <unordered_set> ``` ### 2. 創建 `unordered_set` ```cpp unordered_set<int> s; ``` ### 3. 插入元素(重複的不會加入) ```cpp s.insert(10); s.insert(20); s.insert(10); // 不會重複加入 ``` ### 4. 判斷某個值在不在裡面 ```cpp if (s.count(10)) { cout << "10 在集合中"; } ``` 或用: ```cpp if (s.find(20) != s.end()) { cout << "20 有找到"; } ``` ### 5. 刪除元素 ```cpp s.erase(10); ``` ### 6. 查現在集合裡有多少元素 ```cpp cout << s.size(); ``` ### 7. 迭代整個集合 `unordered_set` 裡的順序是亂的(以 hash 配置)。 ```cpp for (int v : s) { cout << v << " "; } ``` ### 8. 清空 ```cpp s.clear(); ``` ### 9. 小示範(完整可編譯) ```cpp #include <iostream> #include <unordered_set> using namespace std; int main() { unordered_set<int> s; s.insert(3); s.insert(7); s.insert(3); // 不會出現第二次 if(s.count(7)) cout << "7 存在\n"; s.erase(7); for(int v : s){ cout << v << " "; } cout << endl; return 0; } ``` ## map (似Dictionary字典) 「鍵(key)」與「值(value)」的對應關係。 🔅 key不可使用到重複的值 ```cpp= map<string, int> score; score["小明"] = 90; score["小美"] = 85; ``` ### 使用 * first 是 key(數字本身) * second 是 value(出現次數) ```cpp= // 新增或修改值 score["Tom"] = 80; score["Amy"] = 95; // 取出值 cout << "Tom 的分數是 " << score["Tom"] << endl; // 判斷是否存在 key if (score.count("Amy")) { cout << "有找到 Amy!" << endl; } // 用迴圈列出所有 key-value for (auto it : score) { cout << it.first << " 的分數是 " << it.second << endl; } ``` ## set * set 是一種 自動排序 且 元素唯一 的容器。 * 插入時,若插入重複資料,set 不會重複儲存。 * 適合用來 去除重複元素,例如你 threeSum() 得到的 [ -1, 0, 1 ] 有重複時,就可以自動處理。 ### 範例: | 操作 | 範例 | 說明 | | -------------------- | --------------------- | --------------- | | 宣告 set<int> | `set<int> s;` | 儲存整數,唯一且排序 | | 插入元素 | `s.insert(4);` | 插入元素(重複自動忽略) | | 檢查是否存在 | `s.count(4)` | 回傳 1 表示有,0 表示沒有 | | 刪除元素 | `s.erase(4);` | 刪除某元素 | | 清空 | `s.clear();` | 移除所有元素 | | 取得大小 | `s.size();` | 回傳目前有幾個元素 | | 迴圈走訪 | `for (int x : s)` | 所有元素(已排序) | | 宣告 set\<vector<int>> | `set<vector<int>> s;` | 去除重複的陣列(記得排序) | ```cpp= s.insert(3); s.insert(1); s.insert(2); s.insert(3); // 重複插入不會成功 ``` ### 二微陣列 ```cpp= set<vector<int>> s; vector<int> a = {-1, 0, 1}; vector<int> b = {0, -1, 1}; // 相同數字但順序不同 sort(a.begin(), a.end()); // 先排序 sort(b.begin(), b.end()); s.insert(a); s.insert(b); // 不會重複插入 ``` ## stack ### 範例: ```cpp= #include <stack> #include <iostream> using namespace std; int main() { stack<int> s; s.push(1); s.push(2); s.push(3); // 堆疊為 1,2,3,3在最上面 cout << s.top(); // 輸出3 s.pop(); //彈出(移除最上層元素) cout << s.top(); // 輸出2 if(st.empty()) { cout << "空的"; } cout << st.size(); //大小:2 } ``` ### 與vector比較 | 比較項目 | `vector` | `stack` | | ------ | ------------------- | -------------------------- | | 結構類型 | 動態陣列 | 堆疊(LIFO) | | 支援隨機存取 | ✅ 是 | ❌ 否 | | 典型操作 | `[]`, `push_back()` | `push()`, `pop()`, `top()` | | 適用場景 | 任意資料處理 | 括號比對、遞迴處理等 LIFO 場景 | ## sort() 排序函數 使用時,要引入 `#include <algorithm>` ```cpp= sort(開始位址, 結束位址); ``` 它會將指定範圍的資料 由小到大排序(預設)。 ### 從「大到小排序」 你可以加入第三個參數(比較函數): ```cpp= #include <functional> // 為了 greater<int>() int arr[] = {5, 2, 8, 1, 4}; sort(arr, arr + 5); // 對 arr[0] 到 arr[4] 排序 ``` ### 二維陣列 🔹 範例1:對每一列個別排序 ```cpp= int arr[3][4] = { {5, 2, 4, 1}, {8, 7, 3, 6}, {9, 10, 12, 11} }; for (int i = 0; i < 3; i++) { sort(arr[i], arr[i] + 4); // 排第 i 列 } ``` 🔹 範例2:整張二維陣列看成一維,排序全部資料 ```cpp= int arr[3][4] = { {5, 2, 4, 1}, {8, 7, 3, 6}, {9, 10, 12, 11} }; // 強制把二維陣列轉成一維來排 sort(&arr[0][0], &arr[0][0] + 3 * 4); ``` 🔹 範例3:自定排序條件(二維陣列每列看成一組) 這用在 vector 更簡單,但這裡示範用 C-style: ```cpp= #include <algorithm> using namespace std; bool cmp(const int a[2], const int b[2]) { return a[0] < b[0]; // 根據第一欄排序 } int arr[3][2] = { {3, 10}, {1, 20}, {2, 30} }; ``` ### 在 vector 使用 ```cpp= vector<int> v = {3, 1, 5, 2}; sort(v.begin(), v.end()); ``` 🔹 vector (似二維陣列) 改用 vector<vector< int >> 寫法(推薦) ```cpp= #include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { vector<vector<int>> arr = { {3, 10}, {1, 20}, {2, 30} }; // 根據每列的第0個元素(第一欄)來排序 sort(arr.begin(), arr.end(), [](vector<int>& a, vector<int>& b) { return a[0] < b[0]; }); for (auto row : arr) { cout << row[0] << " " << row[1] << endl; } // 輸出: // 1 20 // 2 30 // 3 10 return 0; } ``` ## struct 一次裝多個不同型別資料的容器 ### 語法: ```cpp struct 結構名稱 { 資料型別 成員1; 資料型別 成員2; ... }; ``` ```cpp #include <iostream> using namespace std; struct Student { string name; int age; double score; }; int main() { Student s1; s1.name = "Tom"; s1.age = 17; s1.score = 95.5; cout << s1.name << " is " << s1.age << " years old, score: " << s1.score << endl; return 0; } ``` 結構陣列 ```cpp Student classList[3] = { {"Tom", 17, 95.5}, {"Amy", 16, 88.0}, {"John", 18, 78.5} }; for (int i = 0; i < 3; i++) { cout << classList[i].name << " 分數:" << classList[i].score << endl; } ``` 當作函式參數 ```cpp void printStudent(Student s) { cout << s.name << " - " << s.score << endl; } ``` | 用法 | 說明 | | ------- | --------------------------- | | `.成員名` | 取出成員資料(用在普通變數) | | `->成員名` | 用在指標變數(像 `Student* ptr`)時使用 | ## For/While/Do...while 迴圈 ⚠️注意一下C語言int變數不可以設定在迴圈()裡面 ```css= int i; for(i = 0; i <= 5; i++){ } ``` 滿足t<=5(條件)則執行程式 ### For 1. int t=0;只在一開始進入時執行,他是設定這個迴圈的初始值 2. 然後進行t是否小於等於5的條件判斷 3. 條件成立>執行程式 4. 程式執行完便回來進行t++(t+1) 5. 回到 2.如此進行 ```cpp= For(int t=0 ; t<=5 ; t++){ } ``` ### For (類foreach) ```cpp= for (元素類型 變數 : 容器) { // 迴圈內部處理 } ``` 範例: ```cpp= int main() { vector<int> numbers = {10, 20, 30, 40, 50}; // 使用 range-based for loop (foreach) for (int num : numbers) { cout << num << " "; } } ``` ### While 判斷條件是否繼續執行,成立就執行程式碼 ```cpp= While(t<=5){ } ``` ### Do...while 先執行do迴圈當中的程式,然後判斷條件是否繼續執行 ```cpp= Do{ }while(t<=5); //要分號! ``` Continue:回到條件判斷 Break:跳出迴圈 ```cpp= For(條件) { 敘述區段; Continue; } ``` ## If/else 如果...那麼... If(條件) {達成執行} 不達成>> else if(條件) {達成執行} 不達成>> eles{達成執行} ![If(條件) 1 of 1](https://hackmd.io/_uploads/By3f1cGLye.png) ### 判斷語法 * 等於 == * 大於等於 >= * 小於等於 <= * 小於 < * 大於 > * 或 || * 且 && ## Switch/case ```cpp= Switch(條件運算源頭) { case(條件等於): 執行程式; Break; // 結束以內的程式 Default: // 都沒有相等的則執行以下程式 執行程式; Break; } ``` ## 亂數 0-110隨機取一個數>>58 ### rand() 這是 C++ 傳統的隨機數產生方式,但隨機性較差,每次執行可能產生相同的數字。 ```cpp= #include <cstdlib> // 使用 rand() #include <ctime> // 使用 time() 設定種子 srand(time(0)); // 設定隨機種子,使每次執行結果不同 int randomNumber = rand() % 100; // 產生 0~99 之間的隨機數 ``` 💡解釋: * srand(time(0)):使用當前時間作為隨機種子,避免每次執行都產生相同的數字。 * rand() % 100:產生 0~99 之間的隨機數。 ### std::random C++11 以上推薦 ```cpp= #include <random> // C++11 隨機數 random_device rd; // 取得真實隨機數據 mt19937 gen(rd()); // 產生器 uniform_int_distribution<int> dist(1, 100); // 產生 1~100 的隨機數 int randomNumber = dist(gen); ``` 💡解釋: * random_device rd;:取得更隨機的種子(硬體支援時更好)。 * mt19937 gen(rd());:Mersenne Twister 亂數產生器,比 rand() 更好。 * uniform_int_distribution< int > dist(1, 100);:產生 1~100 之間的均勻隨機數。 ## 函式 函式可以讓程式碼更加簡潔,是一個很常用到的功能 ### 講解: ```cpp= 返回類型 函式名稱(參數列表) { 函式主體 return 回傳值; // 如果是 void 可以省略 } ``` ### 應用: ```cpp= void sayHello() { cout << "Hello, World!" << endl; } int add(int a, int b) { return a + b; // 回傳兩數相加的結果 } ``` ## Math 一些方便計算的數學內建函式 ```cpp= #include <cmath> // 引入數學函式庫 cout << "平方根 sqrt(25): " << sqrt(25) << endl; cout << "次方 pow(2, 5): " << pow(2, 5) << endl; cout << "絕對值 abs(-10): " << abs(-10) << endl; ``` ## system() 它可以執行命令提示字元(Windows)或終端機(Linux / macOS)的指令。 ```cpp= #include <cstdlib> // 或 <stdlib.h> system("命令"); ``` ### 常見用法(Windows) | 指令 | 功能 | |------------------------------|---------------------------| | system("cls"); | 清除畫面(Clear Screen) | | system("pause"); | 暫停程式並顯示「Press any key」暫停執行觀看結果指令| | system("dir"); | 顯示目錄下的檔案(列出資料夾) | | system("echo Hello"); | 顯示文字「Hello」 | | system("color 0A"); | 更改終端字體顏色(黑底綠字) | | system("title 我的程式"); | 更改視窗標題 | | system("start"); | 開新視窗(打開新cmd) | | system("shutdown /s"); | 關機 | | system("shutdown /r"); | 重新啟動 | ### 顏色變更(color 指令) ```cpp= system("color 1F"); // 文字:白色,背景:藍色 ``` | 色碼 | 顏色 | |------|--------| | 0 | 黑 | | 1 | 藍 | | 2 | 綠 | | 3 | 青 | | 4 | 紅 | | 5 | 紫 | | 6 | 黃 | | 7 | 白 | | 8 | 灰 | | 9 | 淺藍 | | A | 淺綠 | | B | 淺青 | | C | 淺紅 | | D | 淺紫 | | E | 淺黃 | | F | 亮白 | # 與C語言的差別 C 語言的輸入函式,在 C++ 也可以使用(來自 < cstdio >) ````cpp= #include <cstdio> // 引入 cstdio ```` | 特性 | C | C++ | |--------------------|-----------------------|-------------------------| | 程式風格 | 程序導向 | 物件導向 + 程序導向 | | 輸出方式 | printf | cout ( iostream ) | | 類別與物件 | 無 | 有 | | 函式/運算子多載 | 無 | 有 | | 範型(Template) | 無 | 有 | | 命名空間 | 無 | 有 ( namespace std ) | # 開發者方便小秘訣 ## 快速整理畫面 |功能 |Dev-C++ |Code::Blocks |Visual Studio Code| |----|---- |--- |--- | |自動縮排 / 排版| Ctrl + A → Ctrl + I |Ctrl + A → Ctrl + Shift + I |Alt + Shift + F| ## 註解篇 除了普通的註解//這裡是註解 * 註解一定範圍:/* ....... */ ```cpp= /* int old1; hiii */ ``` ## `#include <bits/stdc++.h>` 標頭檔。 它的作用是: ### ✔ 功能 等同於同時 include: ``` <iostream> <vector> <algorithm> <string> <queue> <stack> <map> <unordered_map> <unordered_set> <cmath> <cstring> <set> <bitset> <deque> <limits> <numeric> <functional> … (幾乎全部 STL) ``` 也就是說: ### ✔ 有了 `#include <bits/stdc++.h>` 你 **基本上不用再 include 任何標頭**。 --- ### ✘ 但缺點是: 1. **不是 C++ 標準的一部分** → 在 Windows VC++、某些編譯器 **不能用** → 但 ZeroJudge、APCS、Codeforces、AtCoder 都可以用(因為是 GNU g++) 2. **編譯會比較慢** 因為你把整個 STL monster 包下來。 --- ### ✔ 在競賽使用的人原因 因為快速又方便: ```cpp #include <bits/stdc++.h> using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(nullptr); vector<int> v={1,2,3}; sort(v.begin(), v.end()); } ``` 非常簡短。 --- ### ✔ 建議你何時使用? | 場景 | 建議 | | ----------------- | --------------------------- | | APCS、ZeroJudge、競賽 | **用 `<bits/stdc++.h>` 最方便** | | 學校課堂要交作業 | 不要用,老師會扣分 | | 正式專案 / 工作 | 絕對不要用 |