std::ranges::is_sorted
來自 cppreference.com
定義於標頭檔案 <algorithm> |
||
呼叫簽名 (Call signature) |
||
template< std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, |
(1) | (C++20 起) |
template< ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< |
(2) | (C++20 起) |
檢查範圍 [
first,
last)
中的元素是否按非降序排序。
如果對於指向序列的任何迭代器 it
和任何非負整數 n
(使得 it + n
是指向序列元素的有效迭代器),std::invoke(comp, std::invoke(proj, *(it + n)), std::invoke(proj, *it)) 評估為 false,則序列相對於比較器 comp 是已排序的。
1) 使用給定的二元比較函式 comp 比較元素。
本頁描述的類函式實體是 演算法函式物件(非正式地稱為 niebloids),即
目錄 |
[編輯] 引數
first, last | - | 定義要檢查是否排序的元素 範圍 的迭代器-哨兵對 |
r | - | 要檢查是否排序的元素範圍 |
comp | - | 應用於投影元素的比較函式 |
proj | - | 應用於元素的投影 |
[編輯] 返回值
如果範圍中的元素根據 comp
已排序,則為 true。
[編輯] 複雜度
與 first 和 last 之間的距離呈線性關係。
[編輯] 可能的實現
struct is_sorted_fn { template<std::forward_iterator I, std::sentinel_for<I> S, class Proj = std::identity, std::indirect_strict_weak_order<std::projected<I, Proj>> Comp = ranges::less> constexpr bool operator()(I first, S last, Comp comp = {}, Proj proj = {}) const { return ranges::is_sorted_until(first, last, comp, proj) == last; } template<ranges::forward_range R, class Proj = std::identity, std::indirect_strict_weak_order< std::projected<ranges::iterator_t<R>, Proj>> Comp = ranges::less> constexpr bool operator()(R&& r, Comp comp = {}, Proj proj = {}) const { return (*this)(ranges::begin(r), ranges::end(r), std::ref(comp), std::ref(proj)); } }; inline constexpr is_sorted_fn is_sorted; |
[編輯] 注意
ranges::is_sorted
對於空範圍和長度為一的範圍返回 true。
[編輯] 示例
執行此程式碼
#include <algorithm> #include <array> #include <functional> #include <iostream> #include <iterator> int main() { namespace ranges = std::ranges; std::array digits {3, 1, 4, 1, 5}; ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); ranges::is_sorted(digits) ? std::cout << ": sorted\n" : std::cout << ": not sorted\n"; ranges::sort(digits); ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); ranges::is_sorted(ranges::begin(digits), ranges::end(digits)) ? std::cout << ": sorted\n" : std::cout << ": not sorted\n"; ranges::reverse(digits); ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); ranges::is_sorted(digits, ranges::greater {}) ? std::cout << ": sorted (with 'greater')\n" : std::cout << ": not sorted\n"; }
輸出
3 1 4 1 5 : not sorted 1 1 3 4 5 : sorted 5 4 3 1 1 : sorted (with 'greater')
[編輯] 參閱
(C++20) |
尋找最大的已排序子範圍 (演算法函式物件) |
(C++11) |
檢查一個範圍是否按升序排序 (函式模板) |