7.4 常用內建函式
C++ 標準函式庫已經為我們實現了很多常用的功能,不用重複造輪子。認識這些內建函式能大幅加快寫程式的速度。
內建函式住在各種不同的「函式庫」(library)裡。使用前必須用 #include<...> 把對應的函式庫引入。
¶常用內建函式清單
¶1. swap(a, b) —— 交換兩個值
- 位置:
#include<algorithm> - 用途:交換兩個變數的值
- 限制:a 和 b 的型態必須一樣,不能傳數字字面常數
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int a = 5, b = 3;
cout << "Before swap: " << a << " " << b << "\n";
swap(a, b); // 直接交換,比自己寫三行迴圈方便多了
cout << "After swap: " << a << " " << b << "\n";
return 0;
}
執行結果:
Before swap: 5 3
After swap: 3 5
¶2. max(a, b) 和 min(a, b) —— 找最大/最小值
- 位置:
#include<algorithm> - 用途:找兩個數中的最大/最小值,或用大括號列出多個數
- 限制:所有參數型態必須一致
#include<iostream>
#include<algorithm>
using namespace std;
int main() {
int a = 5, b = 3;
cout << max(a, b) << "\n"; // 輸出 5
cout << min(a, b) << "\n"; // 輸出 3
// 找多個數的最大值:用大括號
cout << max({1, 5, 3, 9, 2}) << "\n"; // 輸出 9
cout << min({1, 5, 3, 9, 2}) << "\n"; // 輸出 1
return 0;
}
執行結果:
5
3
9
1
¶3. abs(x) —— 絕對值
- 位置:
#include<cstdlib>(整數絕對值) - 用途:計算一個數的絕對值
#include<iostream>
#include<cstdlib>
using namespace std;
int main() {
int a = -5;
cout << abs(a) << "\n"; // 輸出 5
cout << abs(-3 - 7) << "\n"; // 輸出 10
return 0;
}
執行結果:
5
10
¶4. gcd(x, y) 和 lcm(x, y) —— 最大公因數與最小公倍數
- 位置:
#include<numeric>(C++17 及以後) - 用途:計算最大公因數(greatest common divisor)和最小公倍數(least common multiple)
#include<iostream>
#include<numeric>
using namespace std;
int main() {
int a = 12, b = 8;
cout << "gcd(12, 8) = " << gcd(a, b) << "\n"; // 輸出 4
cout << "lcm(12, 8) = " << lcm(a, b) << "\n"; // 輸出 24
return 0;
}
執行結果:
gcd(12, 8) = 4
lcm(12, 8) = 24
動手試試看:寫一個程式,讀入三個整數,用 max 找出最大的,用 min 找出最小的,用 abs 計算最大值和最小值的差。