C++ 範圍 for 和常用演算法
範圍 for 寫成 for (int x : v),依次取出容器裡的每個元素;<algorithm> 提供 sort、reverse、find、count、max_element 等常用演算法。
上一課用下標走遍 vector:for (std::size_t i = 0; i < v.size(); i++)。只是想把每個元素看一遍的時候,有更短的寫法,叫範圍 for:
1#include <iostream>2#include <vector>3 4int main() {5 std::vector<int> scores{90, 85, 77, 68};6 int total = 0;7 for (int s : scores) {8 total += s;9 }10 std::cout << "總分:" << total << '\n';11 return 0;12}
總分:320
for (int s : scores) 讀作「對 scores 裡的每一個 s」:第一圈 s 是 90,第二圈是 85……直到最後一個。不用下標,也就不會越界。
- 第 1 圈
s = 90total 是 90 - 第 2 圈
s = 85total 是 175 - 第 3 圈
s = 77total 是 252 - 第 4 圈
s = 68total 是 320
範圍 for
冒號左邊是每一圈拿到的變數,右邊是要走遍的容器。std::string 也是一個容器,能一個字元一個字元地走:
1#include <iostream>2#include <string>3#include <vector>4 5int main() {6 std::vector<std::string> list{"牛奶", "雞蛋", "麵包"};7 for (std::string item : list) {8 std::cout << "- " << item << '\n';9 }10 std::string code = "A7B";11 for (char c : code) {12 std::cout << "[" << c << "]";13 }14 std::cout << '\n';15 return 0;16}
- 牛奶 - 雞蛋 - 麵包 [A][7][B]
要用到下標(比如顯示編號)的時候,還是用上一課的寫法;只要元素本身,就用範圍 for。
這段程式顯示什麼?
1#include <iostream>2#include <string>3 4int main() {5 std::string w = "abc";6 for (char c : w) {7 std::cout << c << c;8 }9 std::cout << '\n';10 return 0;11}
c 依次是 a、b、c,每一圈把它顯示兩次,所以是 aabbcc。用引用改元素
範圍 for 每一圈拿到的是元素的一份複製。改它,會改到 vector 裡嗎?
這段程式顯示什麼?
1#include <iostream>2#include <vector>3 4int main() {5 std::vector<int> prices{10, 20, 30};6 for (int p : prices) {7 p = p + 5;8 }9 std::cout << prices[0] << '\n';10 return 0;11}
p 是複製出來的,改的是複製品,prices 裡的數沒變。要改元素本身,在型別後面加 &,讓 p 成為元素的引用(第 10 課)。點單步,看格子裡的數一個一個變大:
1#include <iostream>2#include <vector>3 4int main() {5 std::vector<int> prices{10, 20, 30};6 for (int& p : prices) {7 p = p + 5;8 }9 for (int p : prices) {10 std::cout << p << " ";11 }12 std::cout << '\n';13 return 0;14}
15 25 35
for (int p : prices)10 20 30改的是複製品,prices 沒變for (int& p : prices)15 25 35p 就是格子本身,改了就變全場八折
✓用範圍 for 把 prices 裡的每個價格都改成原來的 0.8 倍,再一行一個顯示出來。
40 96 28.4
1#include <iostream>2#include <vector>3 4int main() {5 std::vector<double> prices{50, 120, 35.5};6 7 return 0;8}
const auto&:不復制,也不改
元素是字串這樣的大東西時,每一圈都複製一份很浪費。和傳引數一樣,用 const 引用:不復制,也保證不會改到它。型別寫 auto,讓編譯器自己推出來:
1#include <iostream>2#include <string>3#include <vector>4 5int main() {6 std::vector<std::string> cities{"上海", "成都", "西安"};7 for (const auto& city : cities) {8 std::cout << city << ":" << city.size() << " 個位元組\n";9 }10 return 0;11}
上海:6 個位元組 成都:6 個位元組 西安:6 個位元組
一個漢字在 std::string 裡佔 3 個位元組,所以 size() 是 6。三種寫法怎麼挑:
| 寫法 | 什麼時候用 |
|---|---|
for (int x : v) | 元素是 int、double 這樣的小東西,只讀 |
for (int& x : v) | 要改元素 |
for (const auto& x : v) | 元素是字串這樣的大東西,只讀 |
要把一排 std::string 一個個顯示出來,不改它們。最合適的寫法是?
const auto&:不復制,也不會改到。auto& 可以改元素,只讀時不需要;std::string s 每一圈都複製一份。排序
<algorithm> 裡有一批現成的工具,叫演算法。最常用的是 std::sort,從小到大排好:
1#include <algorithm>2#include <functional>3#include <iostream>4#include <vector>5 6int main() {7 std::vector<int> scores{77, 95, 68, 88};8 std::sort(scores.begin(), scores.end());9 for (int s : scores) {10 std::cout << s << " ";11 }12 std::cout << '\n';13 std::sort(scores.begin(), scores.end(), std::greater<int>());14 for (int s : scores) {15 std::cout << s << " ";16 }17 std::cout << '\n';18 return 0;19}
68 77 88 95 95 88 77 68
scores.begin() 和 scores.end() 告訴 sort 從哪兒排到哪兒:從頭到尾。它們其實是迭代器,第 27 課再細講,現在照著寫就行。要從大到小,多給一個 std::greater<int>()(在 <functional> 裡)。點單步,看 sort 那一步之後格子換了位置。
scores.begin()↑scores.end()字串也能排,按字典順序:
1#include <algorithm>2#include <iostream>3#include <string>4#include <vector>5 6int main() {7 std::vector<std::string> names{"王芳", "李雷", "張偉"};8 std::sort(names.begin(), names.end());9 for (const auto& n : names) {10 std::cout << n << '\n';11 }12 return 0;13}
張偉 李雷 王芳
注意: 漢字按編碼比大小,不是按拼音或筆畫。按拼音,「李」應該在最前面。
前三名
✓把 scores 從大到小排好,顯示前三名,一行一個,像 第 1 名:95 這樣。
第 1 名:95 第 2 名:91 第 3 名:88
1#include <algorithm>2#include <functional>3#include <iostream>4#include <vector>5 6int main() {7 std::vector<int> scores{78, 95, 62, 88, 91};8 9 return 0;10}
翻轉、查詢、數個數
| 寫法 | 做什麼 |
|---|---|
std::reverse(v.begin(), v.end()) | 把順序倒過來 |
std::count(v.begin(), v.end(), x) | x 出現了幾次 |
std::find(v.begin(), v.end(), x) | 找 x;找不到時等於 v.end() |
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> rolls{3, 6, 2, 6, 1};7 std::reverse(rolls.begin(), rolls.end());8 for (int r : rolls) {9 std::cout << r << " ";10 }11 std::cout << '\n';12 std::cout << "6 出現了 " << std::count(rolls.begin(), rolls.end(), 6) << " 次\n";13 if (std::find(rolls.begin(), rolls.end(), 5) == rolls.end()) {14 std::cout << "沒有 5\n";15 }16 return 0;17}
1 6 2 6 3 6 出現了 2 次 沒有 5
find 找不到時給你 end(),就像字串的 find 找不到時給你 npos。
這段程式顯示什麼?
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<int> v{2, 5, 2, 8, 2};7 std::cout << std::count(v.begin(), v.end(), 2) << '\n';8 return 0;9}
std::count 數的是 2 出現了幾次:第 1、3、5 個都是 2,一共 3 次。最大和最小
std::max_element 和 std::min_element 找最大和最小的元素。它們給的是一個指向那個元素的迭代器,前面加 * 才是值:
1#include <algorithm>2#include <iostream>3#include <vector>4 5int main() {6 std::vector<double> temps{18.5, 23.0, 16.5, 21.0};7 std::cout << "最高:" << *std::max_element(temps.begin(), temps.end()) << '\n';8 std::cout << "最低:" << *std::min_element(temps.begin(), temps.end()) << '\n';9 return 0;10}
最高:23 最低:16.5
注意: 空的 vector 沒有最大的元素,這時它們給的是 end(),再加 * 就是未定義行為。先確認不是空的。
std::max_element(v.begin(), v.end()) 給你的是什麼?
max_element 和 find 一樣,給的是迭代器:它指著那個元素。要拿到值,前面加 *。加起來
std::accumulate(在 <numeric> 裡)把所有元素加起來。第三個引數是起點,通常寫 0:
這段程式顯示什麼?
1#include <iostream>2#include <numeric>3#include <vector>4 5int main() {6 std::vector<double> prices{1.5, 2.5, 3.25};7 std::cout << std::accumulate(prices.begin(), prices.end(), 0) << '\n';8 return 0;9}
0 是 int,accumulate 就一路用 int 存結果:0 + 1.5 存成 1,1 + 2.5 存成 3,3 + 3.25 存成 6。每一步都把小數丟了。起點的型別就是結果的型別。加 double 就寫 0.0:
1#include <iostream>2#include <numeric>3#include <vector>4 5int main() {6 std::vector<double> prices{1.5, 2.5, 3.25};7 double total = std::accumulate(prices.begin(), prices.end(), 0.0);8 std::cout << "總價:" << total << '\n';9 std::cout << "平均:" << total / prices.size() << '\n';10 return 0;11}
總價:7.25 平均:2.41667
修好它:丟了零頭的總價
✓這段程式算出來的總價不對。改好它,讓它顯示 總價:25.25。
總價:25.25
1#include <iostream>2#include <numeric>3#include <vector>4 5int main() {6 std::vector<double> prices{9.5, 12.25, 3.5};7 std::cout << "總價:" << std::accumulate(prices.begin(), prices.end(), 0) << '\n';8 return 0;9}
這一課學會了
- 範圍 for
for (int x : v)走遍每個元素,不用下標;std::string也能這樣走。 x是複製品;要改元素寫int& x,只讀大東西寫const auto& x。std::sort(v.begin(), v.end())從小到大排,加std::greater<int>()從大到小;漢字按編碼排。std::reverse倒過來,std::count數個數,std::find找不到時等於v.end()。*std::max_element(...)、*std::min_element(...)是最大和最小的值;空的不能用。std::accumulate(v.begin(), v.end(), 0.0)求和,起點的型別就是結果的型別。