Skip to content

Latest commit

 

History

History
117 lines (91 loc) · 3.14 KB

is_sorted_until.md

File metadata and controls

117 lines (91 loc) · 3.14 KB

is_sorted_until

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

  template <class ForwardIterator>
  constexpr ForwardIterator
    is_sorted_until(ForwardIterator first,
                    ForwardIterator last); // (1) C++20

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

  template <class ForwardIterator, class Compare>
  constexpr ForwardIterator
    is_sorted_until(ForwardIterator first,
                    ForwardIterator last,
                    Compare comp);         // (2) C++20

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

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

概要

ソート済みか判定し、ソートされていない位置のイテレータを取得する

戻り値

distance(first, last) < 2 なら last を返す。そうでない場合、[first,last] の中でソートされている範囲を [first,i) としたとき、そのイテレータ i を返す。

計算量

線形時間

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

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

  std::cout << std::boolalpha;
  std::cout << "before: is sorted? "
            << (std::is_sorted_until(v.begin(), v.end()) == v.end()) << std::endl;

  std::sort(v.begin(), v.end());

  std::cout << " after: is sorted? "
            << (std::is_sorted_until(v.begin(), v.end()) == v.end()) << std::endl;
}
  • std::is_sorted_until[color ff0000]

出力

before: is sorted? false
 after: is sorted? true

実装例

template <class ForwardIterator>
ForwardIterator is_sorted_until(ForwardIterator first, ForwardIterator last)
{
  auto it = first;
  if (it == last || ++it == last)
    return last;
  while (it != last && *first < *it)
    ++first, ++it;
  return it;
}

バージョン

言語

  • C++11

処理系

参照