C++ のpair、struct、enum class
std::pair は2つの値(.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{"Ana", 95};7 std::cout << best.first << " は " << best.second << " 点\n";8 best.second = 98;9 std::pair<std::string, int> next = std::make_pair("Ben", 90);10 std::cout << best.second << " " << next.first << '\n';11 return 0;12}
Ana は 95 点 98 Ben
std::pair<std::string, int> は、一つ目が文字列、二つ目が int という意味です。std::make_pair("Ben", 90) は、山かっこに型を書かなくても、丸かっこの中の二つの値から pair を作ってくれます。関数から二つの値を一度に返したいときによく使います。
std::pair<std::string, int> p{"book", 7}; のあと、p.second は何ですか?
.first は 1 つ目(ここでは文字列 "book")、.second は 2 つ目なので 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) は商を 1 つ目、余りを 2 つ目に入れます。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{"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(struct の定義のあとに ; が必要)と言います。
g++ が expected ';' after struct definition と言っています。セミコロンはどこに足しますか?
struct の定義の閉じかっこのあとには ; が要り、}; になります。メンバーの行にはもともとセミコロンがあります。構造体の vector
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] は 2 番目の要素 {3, 4} なので、x は 3 です。ループはすべての y を足します:2 + 4 + 6 = 12。いちばん高いもの
✓most_expensive を完成させましょう。items をたどって、値段がいちばん高いものを返します。main はもう書いてあり、二つのリストについて調べます。
いちばん高い: headphones 199 いちばん高い: pan 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{{"mouse", 89}, {"headphones", 199}, {"keyboard", 159}};18 std::vector<Item> kitchen{{"kettle", 129}, {"knife", 99}, {"pan", 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{{"Ana", 82}, {"Ben", 95}, {"Cara", 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}
Ben 95 Ana 82 Cara 77
higher_score のうしろに丸かっこはありません。ここでは関数を呼んでいるのではなく、sort に手渡しているからです。sort は比べる必要があるたびに、この関数を呼びます。> なら点数の高い順、< なら低い順になります。レッスン22 で学ぶラムダを使うと、比べ方を sort の呼び出しの中に直接書けます。
点数の低い人を先に並べるには、higher_score の return をどう書きますか?
a が b より前に来るべき」ときに true を返します。低い順なら a.score < b.score です。背の順に並ぼう
✓kids を背の低い順に並べ替える比較関数を書き、名前と身長を一行にひとりずつ表示しましょう。
Mia 121 Leo 128 Sam 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{{"Leo", 128}, {"Mia", 121}, {"Sam", 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'(Size を 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}
enum class と switch
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>は表になります。Itemを関数に渡すときはconst Item&で渡します。- メンバーで並べ替えるには、
boolを返す比較関数を書き、三つ目の引数としてstd::sortに渡します。 enum classは選択肢に名前を付けます(Size::Large)。static_cast<int>なしではintになりません。switchと組み合わせると読みやすくなります。