Kodewick
開始學 →
範圍 for 和常用演算法12 / 30

C++ 範圍 for 和常用演算法

第 12 課,共 30 課 · 第 3 部分 · 容器 · 約 15 分鐘

範圍 for 寫成 for (int x : v),依次取出容器裡的每個元素;<algorithm> 提供 sort、reverse、find、count、max_element 等常用演算法。

上一課用下標走遍 vector:for (std::size_t i = 0; i < v.size(); i++)。只是想把每個元素看一遍的時候,有更短的寫法,叫範圍 for:

main.cpp
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. 第 1 圈s = 90total 是 90
  2. 第 2 圈s = 85total 是 175
  3. 第 3 圈s = 77total 是 252
  4. 第 4 圈s = 68total 是 320
每一圈,s 拿到下一個元素,total 加上它

範圍 for

冒號左邊是每一圈拿到的變數,右邊是要走遍的容器。std::string 也是一個容器,能一個字元一個字元地走:

main.cpp
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}

用引用改元素

範圍 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 成為元素的引用(第 10 課)。點單步,看格子裡的數一個一個變大:

main.cpp
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 就是格子本身,改了就變
加不加 &:p 是一份複製,還是格子本身
練習 1

全場八折

用範圍 for 把 prices 裡的每個價格都改成原來的 0.8 倍,再一行一個顯示出來。

要顯示
40
96
28.4
exercise1.cpp
1#include <iostream>2#include <vector>3 4int main() {5    std::vector<double> prices{50, 120, 35.5};6 7    return 0;8}
輸出
點「執行」或按 Ctrl+Enter

const auto&:不復制,也不改

元素是字串這樣的大東西時,每一圈都複製一份很浪費。和傳引數一樣,用 const 引用:不復制,也保證不會改到它。型別寫 auto,讓編譯器自己推出來:

main.cpp
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 一個個顯示出來,不改它們。最合適的寫法是?

排序

<algorithm> 裡有一批現成的工具,叫演算法。最常用的是 std::sort,從小到大排好:

main.cpp
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 那一步之後格子換了位置。

77956888 
01234
↑scores.begin()↑scores.end()
begin() 指著第一個元素;end() 指著最後一個後面的空位,不是最後一個

字串也能排,按字典順序:

main.cpp
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}
輸出
張偉
李雷
王芳

注意: 漢字按編碼比大小,不是按拼音或筆畫。按拼音,「李」應該在最前面。

練習 2

前三名

把 scores 從大到小排好,顯示前三名,一行一個,像 第 1 名:95 這樣。

要顯示
第 1 名:95
第 2 名:91
第 3 名:88
exercise2.cpp
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}
輸出
點「執行」或按 Ctrl+Enter

翻轉、查詢、數個數

寫法做什麼
std::reverse(v.begin(), v.end())把順序倒過來
std::count(v.begin(), v.end(), x)x 出現了幾次
std::find(v.begin(), v.end(), x)找 x;找不到時等於 v.end()
main.cpp
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::max_element 和 std::min_element 找最大和最小的元素。它們給的是一個指向那個元素的迭代器,前面加 * 才是值:

main.cpp
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()) 給你的是什麼?

加起來

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}

起點的型別就是結果的型別。加 double 就寫 0.0:

main.cpp
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
練習 3

修好它:丟了零頭的總價

這段程式算出來的總價不對。改好它,讓它顯示 總價:25.25。

要顯示
總價:25.25
exercise3.cpp
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}
輸出
點「執行」或按 Ctrl+Enter

這一課學會了

  • 範圍 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) 求和,起點的型別就是結果的型別。
第 12 課學完了嗎?第 12 課,共 30 課 · 進度存在這個瀏覽器裡
下一課 · 第 13 課 · 15 分鐘map 和 set用 std::map 按名字存數:存、取、按鍵排好序走一遍、count 和 find 查有沒有、erase、m[key] 會悄悄新建的坑;用 std::set 去重;數單詞。下一課 →
點按鈕會順便把這一課標記學完,然後開啟下一課。