std::is_sorted_until
来自cppreference.com
<tbody>
</tbody>
| 在标头 <algorithm> 定义
|
||
template< class ForwardIt > ForwardIt is_sorted_until( ForwardIt first, ForwardIt last ); |
(1) | (C++11 起) (C++20 起为 constexpr) |
template< class ExecutionPolicy, class ForwardIt > ForwardIt is_sorted_until( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ); |
(2) | (C++17 起) |
template< class ForwardIt, class Compare > ForwardIt is_sorted_until( ForwardIt first, ForwardIt last, Compare comp ); |
(3) | (C++11 起) (C++20 起为 constexpr) |
template< class ExecutionPolicy, class ForwardIt, class Compare > ForwardIt is_sorted_until( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last, Compare comp ); |
(4) | (C++17 起) |
检验范围 [first, last),并寻找从 first 开始且其中元素已按非降序排序的最大范围。
3) 寻找元素已按
comp 排序的最大范围。2,4) 同 (1,3),但按照
policy 执行。 这些重载只有在满足以下所有条件时才会参与重载决议:
|
|
(C++20 前) |
|
|
(C++20 起) |
参数
| first, last | - | 要检验的元素范围的迭代器对 |
| policy | - | 所用的执行策略 |
| comp | - | 比较函数对象(即满足比较 (Compare) 概念的对象),在第一参数小于(即先 序于)第二参数时返回 true。比较函数的签名应等价于如下:
虽然签名不必有 |
| 类型要求 | ||
-ForwardIt 必须满足老式向前迭代器 (LegacyForwardIterator) 。
| ||
-Compare 必须满足比较 (Compare) 。
| ||
返回值
从 first 开始且其中元素已按升序排序的最大范围。即满足使范围 [first, it) 有序的最后迭代器 it。
对于空范围和长度为一的范围返回 last。
复杂度
给定 N 为 std::distance(first, last):
1,2) 应用 O(N) 次
operator<(C++20 前)std::less{}(C++20 起) 进行比较。3,4) 应用 O(N) 次比较函数
comp。异常
拥有名为 ExecutionPolicy 的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
可能的实现
| is_sorted_until (1) |
|---|
template<class ForwardIt>
constexpr //< C++20 起
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last)
{
return std::is_sorted_until(first, last, std::less<>());
}
|
| is_sorted_until (2) |
template<class ForwardIt, class Compare>
constexpr //< C++20 起
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last, Compare comp)
{
if (first != last)
{
ForwardIt next = first;
while (++next != last)
{
if (comp(*next, *first))
return next;
first = next;
}
}
return last;
}
|
示例
运行此代码
#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <random>
#include <string>
int main()
{
std::random_device rd;
std::mt19937 g(rd());
const int N = 6;
int nums[N] = {3, 1, 4, 1, 5, 9};
const int min_sorted_size = 4;
for (int sorted_size = 0; sorted_size < min_sorted_size;)
{
std::shuffle(nums, nums + N, g);
int *const sorted_end = std::is_sorted_until(nums, nums + N);
sorted_size = std::distance(nums, sorted_end);
assert(sorted_size >= 1);
for (const auto i : nums)
std::cout << i << ' ';
std::cout << ": " << sorted_size << " 个初始有序元素\n"
<< std::string(sorted_size * 2 - 1, '^') << '\n';
}
}
可能的输出:
4 1 9 5 1 3 : 1 个初始有序元素
^
4 5 9 3 1 1 : 3 个初始有序元素
^^^^^
9 3 1 4 5 1 : 1 个初始有序元素
^
1 3 5 4 1 9 : 3 个初始有序元素
^^^^^
5 9 1 1 3 4 : 2 个初始有序元素
^^^
4 9 1 5 1 3 : 2 个初始有序元素
^^^
1 1 4 9 5 3 : 4 个初始有序元素
^^^^^^^
参阅
(C++11) |
检查范围是否已按升序排列 (函数模板) |
(C++20) |
找出最大的有序子范围 (算法函数对象) |