c ++是否有STL算法来检查范围是否严格排序?

时间:2017-04-04 22:49:23

标签: c++ stl

“严格地”是指“没有相同的元素”。

is_sorted(v.begin(), v.end(), std::less<>()) 

不符合我的目标,因为它对1,2,2,4,5等范围返回true。

is_sorted(v.begin(), v.end(), std::less_equal<>()) 

根据here给出的实现工作,但不幸的是is_sorted要求Compare谓词严格排序(Compare(a,a)必须为false),{{1}当然不是。

我应该为此目的编写自己的循环吗?

2 个答案:

答案 0 :(得分:6)

引用评论流:

  带有std::adjacent_find

std::greater_equal应该可以做到 - 它会找到第一个元素大于或等于下一个元素;如果不存在这样的元素,则序列严格增加。

#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> v1{0, 1, 2, 3, 40, 41};

    auto i2 = std::adjacent_find(v1.begin(), v1.end(), std::greater_equal<int>());
    if (i2 == v1.end()) {
        std::cout << "The entire vector is sorted in strictly ascending order\n";
    } else {
        std::cout << "The vector is not sorted\n";
    }
}

源自http://en.cppreference.com/w/cpp/algorithm/adjacent_find

的示例

答案 1 :(得分:0)

您还可以将is_sorted与自定义排序功能一起使用。

bool is_sorted (ForwardIterator first, ForwardIterator last, Compare comp);

如果容器不是strictly increasing,则以下内容返回true:

if(!is_sorted(begin(v),end(v),[](int a,int b){return a<=b;})) return true;