一:功能
返回区间内第一个无序元素,即返回一个有序的子区间
二:用法
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> data {1, 5, 9, 2, 4, 6};
auto it = std::is_sorted_until(data.begin(), data.end());
std::cout << "*is_sorted_until({1, 5, 9, 2, 4, 6}) == " << *it << "\n";
}
三:实现
#include <algorithm>
#include <cassert>
#include <iostream>
#include <iterator>
#include <random>
#include <string>
template<class ForwardIt, class Compare>
constexpr //< since C++20
ForwardIt my_is_sorted_until(ForwardIt first, ForwardIt last, Compare comp = std::less<>())
{
if (first != last)
{
ForwardIt next = first;
while (++next != last)
{
if (comp(*next, *first))
return next;
first = next;
}
}
return last;
}
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 = my_is_sorted_until(nums, nums + N, std::less<>());
sorted_size = std::distance(nums, sorted_end);
assert(sorted_size >= 1);
for (const auto i : nums)
std::cout << i << ' ';
std::cout << ": " << sorted_size << " initial sorted elements\n"
<< std::string(sorted_size * 2 - 1, '^') << '\n';
}
}