最終更新日時(UTC):
が更新

履歴 編集

function template
<algorithm>

std::ranges::max_element(C++20)

namespace std::ranges {
  template <forward_iterator I,
            sentinel_for<I> S,
            class Proj = identity,
            indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less>
  constexpr I
    max_element(I first,
                S last,
                Comp comp = {},
                Proj proj = {}); // (1) C++20

  template <forward_range R,
            class Proj = identity,
            indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less>
  constexpr borrowed_iterator_t<R>
    max_element(R&& r,
                Comp comp = {},
                Proj proj = {}); // (2) C++20

  template <execution-policy Ep,
            random_access_iterator I,
            sized_sentinel_for<I> S,
            class Proj = identity,
            indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less>
  I max_element(Ep&& exec,
                I first,
                S last,
                Comp comp = {},
                Proj proj = {}); // (3) C++26

  template <execution-policy Ep,
            sized-random-access-range R,
            class Proj = identity,
            indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less>
  borrowed_iterator_t<R>
    max_element(Ep&& exec,
                R&& r,
                Comp comp = {},
                Proj proj = {}); // (4) C++26
}

概要

[first, last)の範囲において、最大要素を指す最初のイテレータを取得する。

  • (1): イテレータ範囲を指定する
  • (2): Rangeを直接指定する
  • (3): (1)の並列アルゴリズム版。実行ポリシーを指定する
  • (4): (2)の並列アルゴリズム版。実行ポリシーを指定する

戻り値

比較 invoke(comp, invoke(proj, *i), invoke(proj, *j)) によって最大と判断された最初の要素を指すイテレータ

計算量

max((last - first) - 1, 0)回の比較を行う

基本的な使い方

#include <algorithm>
#include <cassert>
#include <utility>
#include <vector>

int main()
{
  std::vector<int> v1 = {3, 1, 4};

  auto v1_max_element = std::ranges::max_element(v1);
  assert(*v1_max_element == 4);


  std::vector<std::pair<int, int>> v2 = {{0, 3}, {1, 1}, {2, 4}};

  auto v2_max_element = std::ranges::max_element(v2, {}, &std::pair<int, int>::second);
  assert(v2_max_element->first == 2);
  assert(v2_max_element->second == 4);
}

出力

並列アルゴリズムの例 (C++26)

#include <iostream>
#include <vector>
#include <algorithm>
#include <execution>

int main()
{
  std::vector<int> v = {3, 1, 4, 1, 5, 9, 2, 6};

  // 並列に最大要素を検索する
  auto it = std::ranges::max_element(std::execution::par, v);

  std::cout << "max: " << *it << std::endl;
}

出力

max: 9

バージョン

言語

  • C++20

処理系

参照