C++中有STL算法可以检查范围是否严格排序吗?

18

“严格”指的是“没有等效元素”。

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

无法满足我的目标,因为它会对类似于1,2,2,4,5的范围返回true。

Translated:

由于返回真实值,例如1、2、2、4、5等范围,无法达到我的目标。

is_sorted(v.begin(), v.end(), std::less_equal<>()) 
根据这里给出的实现,应该能够正常工作。但不幸的是,is_sorted要求Compare谓词是严格顺序关系(Compare(a,a)必须为false),而std::less_equal显然不是。因此,我需要为此编写自己的循环吗?

2
公平地说,这似乎并不是一项艰巨的任务。 - Matteo Italia
3
也许可以使用 std::adjacent_find - Robᵩ
3
@JonathanWakely: 使用std::greater_equalstd::adjacent_find应该可以解决问题——它将找到第一个元素,该元素大于或等于下一个元素。如果存在这样的元素,则该序列不是严格递减的。很棒的建议@Rob,我之前不知道这个函数。 - Matteo Italia
2个回答

19

引用评论流程:

  

使用std::adjacent_findstd::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


谢谢!只需将“if such element exists”改为“if no such element exists”,或者改为“the sequence is not strictly increasing”。 - Dmitry J
糟糕,现在好些了吗? - Robᵩ

3

您还可以利用unique函数。如果向量是唯一的,它将返回列表的末尾。

bool is_strict_sorted(vector <int> a) {
    return is_sorted(a.begin(), a.end()) && unique(a.begin(), a.end()) == a.end();
}

警告:std::unique会修改您传递给它的原始数组。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接