std::ranges::max_element
From cppreference.com
| ヘッダー <algorithm> で定義 |
||
| 呼び出しシグネチャ |
||
| template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less > |
(1) | (C++20以降) |
| template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< |
(2) | (C++20以降) |
1) 範囲
[first, last) における最大の要素を検索します。このページで説明されている関数のようなエンティティは、アルゴリズム関数オブジェクト(非公式にはニーブロイドとして知られている)です。つまり、
- これらのいずれかを呼び出す際に、明示的なテンプレート引数リストを指定することはできません。
- これらのいずれも実引数依存の名前探索には見えません。
- これらのいずれかが関数呼び出し演算子の左側の名前として通常の非修飾名探索によって見つかった場合、実引数依存の名前探索は抑制されます。
目次 |
[編集] パラメータ
| first, last | - | 調査する要素の範囲を定義するイテレータとセンチネルのペア |
| r | - | 検査する range |
| comp | - | 射影された要素に適用される比較 |
| proj | - | 要素に適用する射影 |
[編集] 戻り値
範囲 [first, last) における最大の要素へのイテレータ。範囲内に最大の要素と同等な要素が複数ある場合、それらのうち最初の要素へのイテレータを返します。範囲が空の場合(つまり first == last の場合)、last を返します。
[編集] 計算量
max(N - 1, 0) 回の比較。ここで N = ranges::distance(first, last) です。
[編集] 実装例
struct max_element_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { if (first == last) return last; auto largest = first; while (++first != last) if (std::invoke(comp, std::invoke(proj, *largest), std::invoke(proj, *first))) largest = first; return largest; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr ranges::borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr max_element_fn max_element; |
[編集] 例
このコードを実行
#include <algorithm> #include <cmath> #include <iostream> int main() { namespace ranges = std::ranges; const auto v = {3, 1, -14, 1, 5, 9, -14, 9}; auto result = ranges::max_element(v.begin(), v.end()); std::cout << "Max element at pos " << ranges::distance(v.begin(), result) << '\n'; auto abs_compare = [](int a, int b) { return std::abs(a) < std::abs(b); }; result = ranges::max_element(v, abs_compare); std::cout << "Absolute max element at pos " << ranges::distance(v.begin(), result) << '\n'; }
出力
Max element at pos 5 Absolute max element at pos 2
[編集] 関連項目
| (C++20) |
範囲内で最小の要素を返す (アルゴリズム関数オブジェクト) |
| (C++20) |
範囲内で最小の要素と最大の要素を返す (アルゴリズム関数オブジェクト) |
| (C++20) |
与えられた値のうち大きい方を返す (アルゴリズム関数オブジェクト) |
| 範囲内で最大の要素を返す (関数テンプレート) |