std::ranges::is_sorted
来自 cppreference.cn
定义于头文件 <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) |
检查一个范围是否按升序排序 (函数模板) |