std::ranges::is_sorted
来自 zh.cppreference.net
| 定义于头文件 <algorithm>
|
||
| 调用签名 |
||
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
is_sorted( I first, S last, Comp comp = {}, Proj proj = {} );
|
(1) | (从 C++20 起) |
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
is_sorted( R&& r, Comp comp = {}, Proj proj = {} );
|
(2) | (从 C++20 起) |
检查范围 [first, last) 中的元素是否按非降序排序。
如果对于指向该序列的任何迭代器 comp 以及任何非负整数 it(使得 n 是一个指向序列中元素的有效迭代器),it + n 求值为 std::invoke(comp, std::invoke(proj, *(it + n)), std::invoke(proj, *it)),则序列相对于比较器 false 是有序的。
1) 使用给定的二元比较函数
comp 比较元素。2) 与 (1) 相同,但使用
r 作为源范围,就像使用 ranges::begin(r) 作为 first 以及 ranges::end(r) 作为 last 一样。此页面上描述的类似函数的实体是 算法函数对象(非正式地称为 niebloids),即:
参数
| first, last | - | 定义待检查是否有序的 范围 的迭代器-哨位对 |
| r | - | 待检查是否有序的元素范围 |
| comp | - | 应用于投影元素的比较函数 |
| proj | - | 应用于元素的投影 |
返回值
true
如果范围内的元素已根据
comp
排序。
复杂度
与 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
对于空范围和长度为1的范围返回
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 << ": 已排序\n" : std::cout << ": 未排序\n"; ranges::sort(digits); ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); ranges::is_sorted(ranges::begin(digits), ranges::end(digits)) ? std::cout << ": 已排序\n" : std::cout << ": 未排序\n"; ranges::reverse(digits); ranges::copy(digits, std::ostream_iterator<int>(std::cout, " ")); ranges::is_sorted(digits, ranges::greater {}) ? std::cout << ": 已排序(使用 'greater')\n" : std::cout << ": 未排序\n"; }
输出:
3 1 4 1 5 : 未排序 1 1 3 4 5 : 已排序 5 4 3 1 1 : 已排序(使用 'greater')
参见
(C++20) |
找出最大的已排序子范围 (算法函数对象) |
(C++11) |
检查范围是否已排序 (函数模板) |