Skip to content

Latest commit

 

History

History
108 lines (85 loc) · 2.45 KB

max_element.md

File metadata and controls

108 lines (85 loc) · 2.45 KB

max_element

  • algorithm[meta header]
  • std[meta namespace]
  • function template[meta id-type]
namespace std {
  template<class ForwardIterator>
  ForwardIterator
    max_element(ForwardIterator first,
                ForwardIterator last); // (1) C++03

  template<class ForwardIterator, class Compare>
  ForwardIterator
    max_element(ForwardIterator first,
                ForwardIterator last,
                Compare comp);         // (2) C++03

  template <class ExecutionPolicy, class ForwardIterator>
  ForwardIterator
    max_element(ExecutionPolicy&& exec,
                ForwardIterator first,
                ForwardIterator last); // (3) C++17

  template <class ExecutionPolicy, class ForwardIterator, class Compare>
  ForwardIterator
    max_element(ExecutionPolicy&& exec,
                ForwardIterator first,
                ForwardIterator last,
                Compare comp);         // (4) C++17
}

概要

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

戻り値

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

計算量

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

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

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

  decltype(v)::iterator i = std::max_element(v.begin(), v.end());
  assert(*i == 4);

  decltype(v)::iterator j = std::max_element(v.begin(), v.end(), [](int a, int b) {
                              return a > b;
                            });
  assert(*j == 1);
}
  • std::max_element[color ff0000]

出力

実装例

template <class ForwardIterator>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last)
{
  if (first == last)
    return first;

  ForwardIterator result = first++;
  for (; first != last; ++first) {
    if (*result < *first) {
      result = first;
    }
  }
  return result;
}

template <class ForwardIterator, class Compare>
ForwardIterator max_element(ForwardIterator first, ForwardIterator last, Compare comp)
{
  if (first == last)
    return first;

  ForwardIterator result = first++;
  for (; first != last; ++first) {
    if (comp(*result, *first)) {
      result = first;
    }
  }
  return result;
}

参照