導入
並べ替え・検索・合計・最大値――こうした「よくある処理」は、自分でループを書かなくても <algorithm> の関数で済みます。バグが少なく、意図が読みやすく、しかも高速です。「車輪の再発明をしない」のが実務の鉄則です。
説明
多くのアルゴリズムは「範囲」を begin() と end() のイテレータで受け取ります。まずは並べ替え sort と、最大・最小 max_element / min_element を見ます。
flowchart LR v["vector v"] --> s["sort(v.begin(), v.end())<br/>昇順に並べ替え"] v --> f["find(...) / count(...)<br/>探す・数える"] v --> m["max_element / min_element<br/>最大・最小の位置"]
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> v = {30, 10, 50, 20, 40};
sort(v.begin(), v.end()); // 昇順に並べ替え
for (int x : v) cout << x << " "; // 10 20 30 40 50
cout << endl;
auto it = max_element(v.begin(), v.end()); // 最大値の位置
cout << "最大: " << *it << endl; // 50
int c = count(v.begin(), v.end(), 20); // 20 の個数
cout << "20 の数: " << c << endl; // 1
return 0;
}
降順に並べたいときは、比較の仕方を渡します。greater<int>() を第3引数に渡すと大きい順になります。合計は <numeric> の accumulate が便利です。
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric> // accumulate
using namespace std;
int main() {
vector<int> v = {30, 10, 50, 20};
sort(v.begin(), v.end(), greater<int>()); // 降順
for (int x : v) cout << x << " "; // 50 30 20 10
cout << endl;
int total = accumulate(v.begin(), v.end(), 0); // 合計(初期値 0)
cout << "合計: " << total << endl; // 110
return 0;
}
まとめ
sort find count max_element accumulate など、定番処理は <algorithm> / <numeric> にそろっています。範囲は begin()〜end() で渡します。並べ替えの基準を変えたい――そこで次の「ラムダ式」が効いてきます。