

// std::is_sorted 简化版(默认比较器)
template <typename ForwardIt>
bool is_sorted(ForwardIt first, ForwardIt last) {
if (first == last) return true; // 空序列
for (ForwardIt next_it = std::next(first); next_it != last; ++first, ++next_it) {
if (*next_it < *first) { // 发现逆序对
return false;
}
}
return true;
}
// std::is_sorted_until 简化版(默认比较器)
template <typename ForwardIt>
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last) {
if (first == last) return last;
for (ForwardIt next_it = std::next(first); next_it != last; ++first, ++next_it) {
if (*next_it < *first) { // 发现逆序对,返回后一个元素迭代器
return next_it;
}
}
return last; // 完全有序
}#include <algorithm> // for std::adjacent_find
// 利用 adjacent_find 查找逆序对
template <typename ForwardIt>
bool is_sorted(ForwardIt first, ForwardIt last) {
// adjacent_find 返回第一个满足 *it > *(it+1) 的 it
return std::adjacent_find(first, last, std::greater<>) == last;
}
template <typename ForwardIt>
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last) {
auto it = std::adjacent_find(first, last, std::greater<>);
return (it == last) ? last : std::next(it);
}// 自定义比较器版本(以降序为例)
template <typename ForwardIt, typename Compare>
bool is_sorted(ForwardIt first, ForwardIt last, Compare comp) {
if (first == last) return true;
for (ForwardIt next_it = std::next(first); next_it != last; ++first, ++next_it) {
if (comp(*next_it, *first)) { // 使用 comp 判断逆序
return false;
}
}
return true;
}
template <typename ForwardIt, typename Compare>
ForwardIt is_sorted_until(ForwardIt first, ForwardIt last, Compare comp) {
if (first == last) return last;
for (ForwardIt next_it = std::next(first); next_it != last; ++first, ++next_it) {
if (comp(*next_it, *first)) {
return next_it;
}
}
return last;
}#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// 基本用法
std::vector<int> v1 = {1, 2, 3, 4, 5};
std::vector<int> v2 = {1, 3, 2, 4, 5};
std::cout << "v1 is sorted: " << std::boolalpha << std::is_sorted(v1.begin(), v1.end()) << "\n"; // true
std::cout << "v2 is sorted: " << std::is_sorted(v2.begin(), v2.end()) << "\n"; // false
auto it1 = std::is_sorted_until(v1.begin(), v1.end());
auto it2 = std::is_sorted_until(v2.begin(), v2.end());
std::cout << "v1 sorted until index: " << (it1 - v1.begin()) << "\n"; // 5(end)
std::cout << "v2 sorted until index: " << (it2 - v2.begin()) << "\n"; // 2(元素2的位置)
// 自定义比较器(降序检查)
std::vector<int> v3 = {5, 4, 3, 2, 1};
std::cout << "v3 is sorted descending: " << std::is_sorted(v3.begin(), v3.end(), std::greater<int>()) << "\n"; // true
return 0;
}std::distance(first, is_sorted_until(first, last)))。原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。