function template
<algorithm>

std::is_sorted

預設 (1)
template <class ForwardIterator>  bool is_sorted (ForwardIterator first, ForwardIterator last);
自定義 (2)
template <class ForwardIterator, class Compare>  bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);
檢查範圍是否已排序
如果範圍 [first,last) 是升序排列的,則返回 true

元素使用第一個版本的 operator< 進行比較,第二個版本使用 comp 進行比較。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
template <class ForwardIterator>
  bool is_sorted (ForwardIterator first, ForwardIterator last)
{
  if (first==last) return true;
  ForwardIterator next = first;
  while (++next!=last) {
    if (*next<*first)     // or, if (comp(*next,*first)) for version (2)
      return false;
    ++first;
  }
  return true;
}

引數

first, last
Forward iterators 指向序列的初始位置和結束位置。要檢查的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
comp
二元函式,接受範圍中的兩個元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示傳遞為第一個引數的元素是否在它定義的特定嚴格弱序中排在第二個元素之前。
該函式不得修改其任何引數。
這可以是指標函式,也可以是函式物件。

返回值

如果範圍 [first,last) 是升序排列的,則為 true,否則為 false

如果範圍 [first,last) 包含的元素少於兩個,則函式始終返回 true

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// is_sorted example
#include <iostream>     // std::cout
#include <algorithm>    // std::is_sorted, std::prev_permutation
#include <array>        // std::array

int main () {
  std::array<int,4> foo {2,4,1,3};

  do {
    // try a new permutation:
    std::prev_permutation(foo.begin(),foo.end());

    // print range:
    std::cout << "foo:";
    for (int& x:foo) std::cout << ' ' << x;
    std::cout << '\n';

  } while (!std::is_sorted(foo.begin(),foo.end()));

  std::cout << "the range is sorted!\n";

  return 0;
}

輸出
foo: 2 3 4 1
foo: 2 3 1 4
foo: 2 1 4 3
foo: 2 1 3 4
foo: 1 4 3 2
foo: 1 4 2 3
foo: 1 3 4 2
foo: 1 3 2 4
foo: 1 2 4 3
foo: 1 2 3 4
the range is sorted!


複雜度

最多線性於 firstlast 之間距離少 1 的值:比較元素對直到找到不匹配項。

資料競爭

訪問範圍 [first,last) 中的物件。

異常

如果元素比較或迭代器操作引發異常,則丟擲。
請注意,無效引數會導致未定義行為

另見