std::is_sorted
提供: cppreference.com
ヘッダ <algorithm> で定義
|
||
(1) | ||
template< class ForwardIt > bool is_sorted( ForwardIt first, ForwardIt last ); |
(C++11以上) (C++20未満) |
|
template< class ForwardIt > constexpr bool is_sorted( ForwardIt first, ForwardIt last ); |
(C++20以上) | |
template< class ExecutionPolicy, class ForwardIt > bool is_sorted( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); |
(2) | (C++17以上) |
(3) | ||
template< class ForwardIt, class Compare > bool is_sorted( ForwardIt first, ForwardIt last, Compare comp ); |
(C++11以上) (C++20未満) |
|
template< class ForwardIt, class Compare > constexpr bool is_sorted( ForwardIt first, ForwardIt last, Compare comp ); |
(C++20以上) | |
template< class ExecutionPolicy, class ForwardIt, class Compare > bool is_sorted( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); |
(4) | (C++17以上) |
範囲 [first, last)
の要素が非降順にソートされているかどうか調べます。
1) 要素は
operator<
を用いて比較されます。3) 要素は指定された二項述語
comp
を用いて比較されます。2,4) (1,3) と同じですが、
policy
に従って実行されます。 これらのオーバーロードは、 std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> が true でなければ、オーバーロード解決に参加しません。目次 |
[編集] 引数
first, last | - | 調べる要素の範囲。 |
policy | - | 使用する実行ポリシー。 詳細は実行ポリシーを参照してください |
comp | - | 最初の要素が2番目の要素より小さい (前に順序づけられる) 場合に true を返す、比較関数オブジェクト (Compare の要件を満たすオブジェクト)。 比較関数のシグネチャは以下と同等なものであるべきです。 bool cmp(const Type1 &a, const Type2 &b); シグネチャが const & を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、 |
型の要件 | ||
-ForwardIt は LegacyForwardIterator の要件を満たさなければなりません。
|
[編集] 戻り値
範囲内の要素が昇順にソートされていれば true。
[編集] 計算量
first
と last
の距離に比例。
[編集] 例外
テンプレート引数 ExecutionPolicy
を持つオーバーロードは以下のようにエラーを報告します。
- アルゴリズムの一部として呼び出された関数の実行が例外を投げ、
ExecutionPolicy
が標準のポリシーのいずれかの場合は、 std::terminate が呼ばれます。 それ以外のあらゆるExecutionPolicy
については、動作は処理系定義です。 - アルゴリズムがメモリの確保に失敗した場合は、 std::bad_alloc が投げられます。
[編集] 実装例
1つめのバージョン |
---|
template<class ForwardIt> bool is_sorted(ForwardIt first, ForwardIt last) { return std::is_sorted_until(first, last) == last; } |
2つめのバージョン |
template<class ForwardIt, class Compare> bool is_sorted(ForwardIt first, ForwardIt last, Compare comp) { return std::is_sorted_until(first, last, comp) == last; } |
[編集] ノート
std::is_sorted は空の範囲および長さ1の範囲に対して true を返します。
[編集] 例
Run this code
#include <iostream> #include <algorithm> #include <iterator> int main() { int digits[] = {3, 1, 4, 1, 5}; for (auto i : digits) std::cout << i << ' '; std::cout << ": is_sorted: " << std::boolalpha << std::is_sorted(std::begin(digits), std::end(digits)) << '\n'; std::sort(std::begin(digits), std::end(digits)); for (auto i : digits) std::cout << i << ' '; std::cout << ": is_sorted: " << std::is_sorted(std::begin(digits), std::end(digits)) << '\n'; }
出力:
3 1 4 1 5 : is_sorted: false 1 1 3 4 5 : is_sorted: true
[編集] 関連項目
(C++11) |
最も大きなソート済みの部分範囲を探します (関数テンプレート) |