Boost 学习之算法篇 is_sorted

来源:互联网 发布:中国流行音乐发展知乎 编辑:程序博客网 时间:2024/06/04 22:16
is_sorted

头文件 <boost/algorithm/cxx11/is_sorted.hpp>包含一个方法用来判断一个值序列是否是排好序的。

函数 is_sorted(sequence) 判断一个值序列是否严格按照某些标准排序。假如判断之前没有声明任何的比较方法 ,那么使用std::less_equal(比如看该序列是否是非降序的)。

官方API

namespace boost { namespace algorithm {template <typename ForwardIterator, typename Pred>bool is_sorted ( ForwardIterator first, ForwardIterator last, Pred p );template <typename ForwardIterator>bool is_sorted ( ForwardIterator first, ForwardIterator last );template <typename Range, typename Pred>bool is_sorted ( const Range &r, Pred p );template <typename Range>bool is_sorted ( const Range &r );}}



is_sorted_until

假如 distance(first,last)<2,则is_sorted(first,last) 返回last.否则(distance(first,last)>2的话),返回[first,last]中的某一个元素i,这个i保证了 [first,i)这个区间是被排好序的。

简言之,返回第一个不是排好序的元素。如果整个参数序列是排好序的,则返回最后一个元素的下一个位置(想想迭代器的end()位置)。

NOTE:可能不太好理解,何谓"第一个不是拍好序的元素"?这样理解:第一个破坏序列排序完整性的元素.

官方API

namespace boost { namespace algorithm {template <typename ForwardIterator, typename Pred>FI is_sorted_until ( ForwardIterator first, ForwardIterator last, Pred p );template <typename ForwardIterator>ForwardIterator is_sorted_until ( ForwardIterator first, ForwardIterator last );template <typename Range, typename Pred>typename boost::range_iterator<const R>::type is_sorted_until ( const Range &r, Pred p );template <typename Range>typename boost::range_iterator<const R>::type is_sorted_until ( const Range &r );}}

注意:is_sorted_until 不能作用于input iterator.

时间复杂度:至多调用N-1次.

例子
假如有一个序列{1,2,3,4,5,3},is_sorted_until(beg,end,std::less<int>()) 将会返回一个迭代器指向第二次出现的元素3。(显然就是这个元素破坏了排序的完整性)
假如有一个序列{1,2,3,4,5,9},is_sorted_until(beg,end,std::less<int>()) 将返回end.

现在也有许多的is_order的"封装函数",使得验证一个序列是否是排序的更加清楚明白。这些函数返回一个boolean值来提示成功或者失败,而不是返回一个迭代器来指出破坏排序的最后一个元素在哪个位置。


验证一个序列是否是升序的(序列中的后一个元素至少比前一个元素大或者相等)

namespace boost { namespace algorithm {template <typename Iterator>bool is_increasing ( Iterator first, Iterator last );template <typename R>bool is_increasing ( const R &range );}}

验证一个序列是否是降序的(序列中的后一个元素至少比前一个元素小或者相等)

namespace boost { namespace algorithm {template <typename ForwardIterator>bool is_decreasing ( ForwardIterator first, ForwardIterator last );template <typename R>bool is_decreasing ( const R &range );}}

验证一个序列是否是严格升序的(序列中的后一个元素比前一个元素大)

namespace boost { namespace algorithm {template <typename ForwardIterator>bool is_strictly_increasing ( ForwardIterator first, ForwardIterator last );template <typename R>bool is_strictly_increasing ( const R &range );}}

验证一个序列是否是严格降序的(序列中的后一个元素比前一个元素小)

namespace boost { namespace algorithm {template <typename ForwardIterator>bool is_strictly_decreasing ( ForwardIterator first, ForwardIterator last );template <typename R>bool is_strictly_decreasing ( const R &range );}}

时间复杂度: 与is_sorted 的时间复杂度相同

0 0
原创粉丝点击