この章では、C++における「拡張for文(range-based for)」の使い方を学びます。 配列やベクタのすべての要素に対して繰り返し処理を行うとき、より簡潔に記述できます。 また、後半ではイテレータの概要にも触れます。
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {10, 20, 30, 40};
// 通常のfor文
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
cout << endl;
// 拡張for文(範囲for)
for (int n : nums) {
cout << n << " ";
}
cout << endl;
return 0;
}for (データ型 変数名 : コンテナ名) {
// 処理
}int や autoint& を使うconst int& にすると安全・高速for (const int& n : nums) { ... } // 読み取り専用
for (int& n : nums) { ... } // 値を変更したい場合#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> nums = {1, 2, 3, 4, 5};
for (int& n : nums) {
n *= 2; // すべて2倍
}
for (int n : nums) {
cout << n << " ";
}
cout << endl;
return 0;
}次のコードは何を出力しますか?
vector<int> data = {3, 6, 9};
for (const int& d : data) {
cout << d * 10 << " ";
}30 60 90
5人分のテスト点数が入ったベクタ scores に対して:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> scores = {70, 80, 90, 60, 85};
for (int s : scores) {
cout << s << " ";
}
cout << endl;
int total = 0;
for (int s : scores) {
total += s;
}
cout << "平均: " << (double)total / scores.size() << endl;
return 0;
}vector や list
のようなコンテナは、要素を順にたどるために「イテレータ」という仕組みを持っています。for (auto it = vec.begin(); it != vec.end(); ++it) {
cout << *it << " ";
}→ *it で要素、++it
で次の要素へ進む。C++のSTLでは頻繁に使われる概念です。
int&)で扱うconst int& が安全