C++ pair、struct 和 enum class
std::pair 把兩個值放在一起(.first、.second),struct 把多個有名字的成員放在一起;enum class 定義一組有名字的選項,比如 Color::Red。
一個商品有名字、數量、價格;一個學生有名字和分數。幾樣東西總是一起出現,就把它們放在一起。最簡單的是 std::pair:正好兩樣,用 .first 和 .second 取出來,和上一課 map 裡的每一對一樣。要 #include <utility>。
1#include <iostream>2#include <string>3#include <utility>4 5int main() {6 std::pair<std::string, int> best{"小林", 95};7 std::cout << best.first << " 考了 " << best.second << " 分\n";8 best.second = 98;9 std::pair<std::string, int> next = std::make_pair("小王", 90);10 std::cout << best.second << " " << next.first << '\n';11 return 0;12}
小林 考了 95 分 98 小王
std::pair<std::string, int>:第一樣是字串,第二樣是 int。std::make_pair("小王", 90) 用括號裡的兩個值做出一個 pair,不用寫尖括號裡的型別;函式要一次交回兩個值時,常用它。
std::pair<std::string, int> p{"書", 7}; 之後,p.second 是什麼?
.first 是第一樣(這裡是字串 "書"),.second 是第二樣,也就是 7。pair:一次返回兩個值
函式只能回傳一個值。要返回兩個,就回傳一個 pair:
1#include <iostream>2#include <utility>3#include <vector>4 5std::pair<int, int> low_high(const std::vector<int>& temps) {6 int low = temps[0];7 int high = temps[0];8 for (int t : temps) {9 if (t < low) {10 low = t;11 }12 if (t > high) {13 high = t;14 }15 }16 return std::make_pair(low, high);17}18 19int main() {20 std::vector<int> week{18, 23, 16, 21, 19};21 std::pair<int, int> r = low_high(week);22 std::cout << "最低 " << r.first << ",最高 " << r.second << '\n';23 return 0;24}
最低 16,最高 23
兩個 pair 也能比大小:先比 .first,一樣再比 .second。所以一個裝 pair 的 vector 可以直接 sort:
排好以後,v[1] 是哪一對?
1#include <algorithm>2#include <iostream>3#include <utility>4#include <vector>5 6int main() {7 std::vector<std::pair<int, int>> v{{2, 9}, {1, 5}, {2, 3}};8 std::sort(v.begin(), v.end());9 std::cout << v[1].first << " " << v[1].second << '\n';10 return 0;11}
.first:{1, 5} 最小,排第一。剩下兩對的 .first 都是 2,再比 .second:3 比 9 小,所以 {2, 3} 排第二。divide 用一個 pair 同時交回商和餘數。把 first 和 second 填進空格,讓程式顯示 3 2。
1#include <iostream>2#include <utility>3 4std::pair<int, int> divide(int a, int b) {5 return std::make_pair(a / b, a % b);6}7 8int main() {9 std::pair<int, int> r = divide(17, 5);10 std::cout << r. << ' ' << r. << '\n';11 return 0;12}
std::make_pair(a / b, a % b) 把商放在第一樣、餘數放在第二樣:17 / 5 = 3 放在 .first,17 % 5 = 2 放在 .second。struct:自己的型別
pair 只有兩樣,名字也只叫 first 和 second,看不出是什麼。三樣以上,或者想起清楚的名字,就用 struct 自己定義一個型別。裡面的變數叫成員,用 . 取:
1#include <iostream>2#include <string>3 4struct Item {5 std::string name;6 int count;7 double price;8};9 10int main() {11 Item pen{"圓珠筆", 3, 2.5};12 pen.count += 2;13 std::cout << pen.name << ":" << pen.count << " 支,";14 std::cout << "共 " << pen.count * pen.price << " 元\n";15 return 0;16}
圓珠筆:5 支,共 12.5 元
struct Item { ... }; 定義了一個新型別 Item,之後就能像 int 一樣用它宣告變數。Item pen{"圓珠筆", 3, 2.5} 按成員的順序給值。點單步,看 pen 顯示成三個欄位。
struct Item① { std::string name;② int count; double price;};③
- ①新型別的名字
- ②成員:型別 + 名字,和宣告變數一樣
- ③右花括號後面要有分號
定義 struct 的右花括號後面要有分號,這是最常忘的一個:
1#include <iostream>2#include <string>3 4struct Item {5 std::string name;6 int count;7}8 9int main() {10 Item cup{"杯子", 4};11 std::cout << cup.name << '\n';12 return 0;13}
main.cpp:7:2: error: expected ';' after struct definition
7 | }
| ^
| ;g++ 指著第 7 行的 } 說:expected ';' after struct definition。
g++ 報 expected ';' after struct definition,分號該加在哪?
struct 的右花括號後面要寫 ;,寫成 };。成員那幾行本來就有分號。vector 裡放 struct
struct 和 vector 放在一起,就是一張表:每個元素是一行,每個成員是一列。傳給函式也和別的大東西一樣,用 const Item&:
1#include <iostream>2#include <string>3#include <vector>4 5struct Item {6 std::string name;7 int count;8 double price;9};10 11double value(const Item& item) {12 return item.count * item.price;13}14 15int main() {16 std::vector<Item> stock{{"圓珠筆", 5, 2.5}, {"筆記本", 3, 8.0}, {"橡皮", 10, 1.5}};17 double total = 0;18 for (const auto& item : stock) {19 std::cout << item.name << ":" << value(item) << " 元\n";20 total += value(item);21 }22 std::cout << "合計:" << total << " 元\n";23 return 0;24}
圓珠筆:12.5 元 筆記本:24 元 橡皮:15 元 合計:51.5 元
花括號裡每個 {...} 是一個 Item。
| name | count | price |
|---|---|---|
| 圓珠筆 | 5 | 2.5 |
| 筆記本 | 3 | 8.0 |
| 橡皮 | 10 | 1.5 |
這段程式顯示什麼?
1#include <iostream>2#include <vector>3 4struct Point {5 int x;6 int y;7};8 9int main() {10 std::vector<Point> v{{1, 2}, {3, 4}, {5, 6}};11 int sum = 0;12 for (const auto& p : v) {13 sum += p.y;14 }15 std::cout << v[1].x << ' ' << sum << '\n';16 return 0;17}
v[1] 是第二個元素 {3, 4},它的 x 是 3。迴圈把每個 y 加起來:2 + 4 + 6 = 12。最貴的一件
✓寫好 most_expensive:走一遍 items,把價格最高的那件交回去。main 已經寫好了,會對兩組商品各問一次。
最貴:耳機 199 最貴:鍋 268
1#include <iostream>2#include <string>3#include <vector>4 5struct Item {6 std::string name;7 int price;8};9 10Item most_expensive(const std::vector<Item>& items) {11 Item best = items[0];12 13 return best;14}15 16int main() {17 std::vector<Item> desk{{"滑鼠", 89}, {"耳機", 199}, {"鍵盤", 159}};18 std::vector<Item> kitchen{{"水壺", 129}, {"刀", 99}, {"鍋", 268}};19 Item a = most_expensive(desk);20 std::cout << "最貴:" << a.name << " " << a.price << '\n';21 Item b = most_expensive(kitchen);22 std::cout << "最貴:" << b.name << " " << b.price << '\n';23 return 0;24}
按成員排序
std::sort 不知道兩個 Item 誰大誰小。你寫一個函式告訴它:兩個引數,第一個應該排在前面就返回 true。把函式名作為第三個引數交給 sort:
1#include <algorithm>2#include <iostream>3#include <string>4#include <vector>5 6struct Student {7 std::string name;8 int score;9};10 11bool higher_score(const Student& a, const Student& b) {12 return a.score > b.score;13}14 15int main() {16 std::vector<Student> cls{{"小林", 82}, {"小王", 95}, {"小張", 77}};17 std::sort(cls.begin(), cls.end(), higher_score);18 for (const auto& s : cls) {19 std::cout << s.name << " " << s.score << '\n';20 }21 return 0;22}
小王 95 小林 82 小張 77
higher_score 後面沒有括號:這裡不是呼叫它,是把它交給 sort,讓 sort 需要比的時候自己去呼叫。用 > 是分數高的在前,用 < 就是低的在前。第 22 課會學 lambda,那時可以把比較直接寫在 sort 的括號裡。
想讓分數低的排在前面,higher_score 裡的 return 該寫成什麼?
a 應該排在 b 前面」時返回 true。分數低的在前,就是 a.score < b.score。按身高排隊
✓寫一個比較函式,把 kids 按身高從矮到高排好,再一行一個顯示名字和身高。
豆豆 121 樂樂 128 果果 134
1#include <algorithm>2#include <iostream>3#include <string>4#include <vector>5 6struct Kid {7 std::string name;8 int height;9};10 11int main() {12 std::vector<Kid> kids{{"樂樂", 128}, {"豆豆", 121}, {"果果", 134}};13 14 return 0;15}
enum class:給選項起名字
有些值只能是幾個選項之一:尺碼是小、中、大,訂單是待付款、已發貨、已送達。用 0、1、2 表示,過幾天就忘了 2 是什麼。enum class 給每個選項起名字:
1#include <iostream>2 3enum class Size { Small, Medium, Large };4 5int main() {6 Size s = Size::Large;7 int code = s;8 std::cout << code << '\n';9 return 0;10}
main.cpp: In function 'int main()':
main.cpp:7:16: error: cannot convert 'Size' to 'int' in initialization
7 | int code = s;
| ^
| |
| Sizeenum class Size 定義了一個型別,它的值只能是 Size::Small、Size::Medium、Size::Large。它們不是 int,所以 int code = s; 編譯不過:cannot convert 'Size' to 'int'。這是故意的:尺碼不該被當成數隨便加減。
真要它對應的數,就用 static_cast<int>:
這段程式顯示什麼?
1#include <iostream>2 3enum class Size { Small, Medium, Large };4 5int main() {6 Size s = Size::Large;7 std::cout << static_cast<int>(s) << '\n';8 return 0;9}
Small 是 0,Medium 是 1,Large 是 2。修好它:尺碼不是數
✓這段程式編譯不過。改好它,讓它顯示 尺碼編號:1。
尺碼編號:1
1#include <iostream>2 3enum class Size { Small, Medium, Large };4 5int main() {6 Size s = Size::Medium;7 int code = s;8 std::cout << "尺碼編號:" << code << '\n';9 return 0;10}
switch 配 enum class
enum class 和 switch 是一對好搭檔:每個 case 寫一個選項,讀起來就像一張說明:
1#include <iostream>2#include <string>3 4enum class Status { Unpaid, Shipped, Delivered };5 6std::string describe(Status s) {7 switch (s) {8 case Status::Unpaid:9 return "待付款";10 case Status::Shipped:11 return "已發貨";12 case Status::Delivered:13 return "已送達";14 }15 return "不明";16}17 18int main() {19 Status order = Status::Unpaid;20 std::cout << describe(order) << '\n';21 order = Status::Shipped;22 std::cout << describe(order) << '\n';23 return 0;24}
待付款 已發貨
每個 case 都直接 return 了,不用 break。switch 後面那個 return "不明"; 讓函式在任何情況下都有回傳值。
小技巧: 用 g++ -Wall 編譯時,switch 漏寫了某個選項,g++ 會提醒你。以後給 Status 加一個新選項,編譯器就幫你找出所有要改的地方。
這段程式顯示什麼?
1#include <iostream>2 3enum class Light { Red, Yellow, Green };4 5int wait(Light l) {6 switch (l) {7 case Light::Red:8 return 30;9 case Light::Yellow:10 return 3;11 case Light::Green:12 return 0;13 }14 return -1;15}16 17int main() {18 std::cout << wait(Light::Yellow) + wait(Light::Red) << '\n';19 return 0;20}
wait(Light::Yellow) 走到 case Light::Yellow,返回 3;wait(Light::Red) 返回 30。3 + 30 = 33。這一課學會了
std::pair<A, B>裝兩樣,用.first、.second取;std::make_pair自己推出型別;函式可以返回pair。pair先比.first再比.second,所以能直接排序。struct定義自己的型別,成員用.取;右花括號後面要有分號。std::vector<Item>是一張表;傳給函式用const Item&。- 按成員排序:寫一個返回
bool的比較函式,交給std::sort當第三個引數。 enum class給選項起名字(Size::Large),不能直接當int,要static_cast<int>;和switch一起用最清楚。