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

履歴 編集

function template
<algorithm>

std::ranges::is_sorted_until(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
    is_sorted_until(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>
    is_sorted_until(R&& r,
                    Comp comp = {},
                    Proj proj = {}); // (2) C++20
}

概要

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

戻り値

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::ranges::is_sorted_until(v) == v.end()) << std::endl;

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

  std::cout << " after: is sorted? "
            << (std::ranges::is_sorted_until(v) == v.end()) << std::endl;
}

出力

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

実装例

struct is_sorted_until_impl {
  template<forward_iterator I, sentinel_for<I> S, class Proj = identity,
           indirect_strict_weak_order<projected<I, Proj>> Comp = ranges::less>
  constexpr I operator()(I first, S last, Comp comp = {}, Proj proj = {}) {
    auto it = first;
    if (it == last || ++it == last)
      return last;
    while (it != last && *first < *it)
      ++first, ++it;
    return it;
  }

  template<forward_range R, class Proj = identity,
           indirect_strict_weak_order<projected<iterator_t<R>, Proj>> Comp = ranges::less>
  constexpr borrowed_iterator_t<R> operator()(R&& r, Comp comp = {}, Proj proj = {}) {
    return (*this)(begin(r), end(r), ref(comp), ref(proj));
  }
};

inline constexpr is_sorted_until_impl is_sorted_until;

バージョン

言語

  • C++20

処理系

参照