C++ 演算法庫 - is_sorted_until() 函式



描述

C++ 函式 std::algorithm::is_sorted_until() 查詢序列中第一個未排序的元素。它使用operator<進行比較。

宣告

以下是來自 std::algorithm 標頭檔案的 std::algorithm::is_sorted_until() 函式宣告。

C++11

template <class ForwardIterator>
ForwardIterator is_sorted_until(ForwardIterator first, ForwardIterator last);

引數

  • first − 指向初始位置的正向迭代器。

  • last − 指向最終位置的正向迭代器。

返回值

返回指向第一個未排序元素的迭代器。如果整個範圍都已排序,則返回last.

異常

如果元素比較或迭代器上的操作丟擲異常,則丟擲異常。

請注意,無效引數會導致未定義的行為。

時間複雜度

線性。

示例

以下示例顯示了 std::algorithm::is_sorted_until() 函式的使用方法。

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

using namespace std;

int main(void) {
   vector<int> v = {1, 2, 3, 5, 4};
   auto it = is_sorted_until(v.begin(), v.end());

   cout << "First unsorted element = " << *it << endl;

   v[3] = 4;

   it = is_sorted_until(v.begin(), v.end());

   if (it == end(v))
      cout << "Entire vector is sorted." << endl;

   return 0;
}

讓我們編譯並執行上述程式,這將產生以下結果:

First unsorted element = 4
Entire vector is sorted.
algorithm.htm
廣告