一 概述
C++ 标准库中提供了很多算法,定义于头文件 < algorithm >。本文主要探究以下用于 区间是否排序或局部排序判断 的算法:
is_sorted(C++11) 区间是否排序 is_sorted_until(C++11) 返回区间第一个破坏排序的元素
二 辅助函数
三 std::is_sorted(C++11)
template < class ForwardIt >
bool is_sorted ( ForwardIt first, ForwardIt last ) ; ( 1 ) ( since C++ 11 ) ( until C++ 20 )
template < class ForwardIt >
constexpr bool is_sorted ( ForwardIt first, ForwardIt last ) ; ( 1 ) ( since C++ 20 )
template < class ExecutionPolicy , class ForwardIt >
bool is_sorted ( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last ) ; ( 2 ) ( since C++ 17 )
template < class ForwardIt , class Compare >
bool is_sorted ( ForwardIt first, ForwardIt last,
Compare comp ) ; ( 3 ) ( since C++ 11 ) ( until C++ 20 )
template < class ForwardIt , class Compare >
constexpr bool is_sorted ( ForwardIt first, ForwardIt last, Compare comp ) ; ( 3 ) ( since C++ 20 )
template < class ExecutionPolicy , class ForwardIt , class Compare >
bool is_sorted ( ExecutionPolicy&& policy, ForwardIt first, ForwardIt last,
Compare comp ) ; ( 4 ) ( since C++ 17 )
四 std::is_sorted_until(C++11)
五 Demo
std:: vector< int > vc1{ 3 , 2 , 1 } ;
std:: vector< int > vc2;
fill ( vc2, 1 , 3 ) ;
std:: vector< int > vc3;
fill ( vc3, 1 , 3 ) ;
fill ( vc3, 1 , 3 ) ;
print ( "vc1: " , vc1) ;
print ( "vc2: " , vc2) ;
print ( "vc3: " , vc3) ;
std:: cout << "vc1 is " << ( std:: is_sorted ( vc1. begin ( ) , vc1. end ( ) )
? "" : "not " ) << "sorted" << std:: endl;
std:: cout << "vc2 is " << ( std:: is_sorted ( vc2. begin ( ) , vc2. end ( ) )
? "" : "not " ) << "sorted" << std:: endl;
std:: cout << "vc3 is " << ( std:: is_sorted ( vc3. begin ( ) , vc3. end ( ) )
? "" : "not " ) << "sorted" << std:: endl;
auto it1 = std:: is_sorted_until ( vc1. begin ( ) , vc1. end ( ) ) ;
std:: cout << "until No." << std:: distance ( vc1. begin ( ) , it1)
<< " vc1 is sorted" << std:: endl;
auto it2 = std:: is_sorted_until ( vc2. begin ( ) , vc2. end ( ) ) ;
std:: cout << "until No." << std:: distance ( vc2. begin ( ) , it2)
<< " vc2 is sorted" << std:: endl;
auto it3 = std:: is_sorted_until ( vc3. begin ( ) , vc3. end ( ) ) ;
std:: cout << "until No." << std:: distance ( vc3. begin ( ) , it3)
<< " vc3 is sorted" << std:: endl;
vc1: 3 2 1
vc2: 1 2 3
vc3: 1 2 3 1 2 3
vc1 is not sorted
vc2 is sorted
vc3 is not sorted
until No. 1 vc1 is sorted
until No. 3 vc2 is sorted
until No. 3 vc3 is sorted
说明
结果1, 区间为排序状态,则 is_sorted_until 返回该区间的 end()。
六 参考