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



描述

C++ 函式std::algorithm::is_sorted() 測試範圍是否已排序。它使用二元函式進行比較。

宣告

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

C++11

template <class ForwardIterator, class Compare>
bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);

引數

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

  • last − 指向結束位置的正向迭代器。

  • comp − 一個接受兩個引數並返回 bool 值的二元函式。

返回值

如果範圍已排序則返回 true,否則返回 false。

異常

如果二元函式或迭代器上的操作丟擲異常,則丟擲異常。

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

時間複雜度

線性。

示例

以下示例演示了 std::algorithm::is_sorted() 函式的用法。

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

using namespace std;

bool ignore_case(char a, char b) {
   return (tolower(a) == tolower(b));
}

int main(void) {
   vector<char> v = {'A', 'b', 'C', 'd', 'E'};
   bool result;

   result = is_sorted(v.begin(), v.end());

   if (result == false)
      cout << "Vector elements are not sorted in ascending order." << endl;

   result = is_sorted(v.begin(), v.end(), ignore_case);

   if (result == true)
      cout << "Vector elements are sorted in ascending order." << endl;

   return 0;
}

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

Vector elements are not sorted in ascending order.
Vector elements are sorted in ascending order.
algorithm.htm
廣告