如何使用C++中的is_sorted函数检查数组是否已排序? [英] How to check whether an array is sorted or not using is_sorted function in C++?

查看:84
本文介绍了如何使用C++中的is_sorted函数检查数组是否已排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 std::is_sorted() 函数检查数组是否已排序.我不确定如何使用 begin()end() 所以我只是将数组传递给函数.

I need to check whether an array is sorted or not using the std::is_sorted() function. I am not sure how I would use begin() and end() so I just passed the array to the function.

void sorted(bool value){
    if(value)
        cout << "Array is sorted" << endl;
    else
        cout << "Array is not sorted" << endl;
}

int main(){
    int a[10], i;
    cout << "Enter the sequence" << endl;
    for(i=0; i<5; i++){
        cin >> a[i];
    }
    bool value = is_sorted(a);
    sorted(value);
    return 0;
}

当我这样做时,虽然我得到了一个错误

When I do that though I get an error like

没有匹配的 is_sorted 函数调用

there is no matching call for is_sorted function

推荐答案

std::is_sorted 适用于一系列迭代器而不是容器".要使用它,您需要将迭代器传递到要检查的范围的开头和要检查的范围末尾的迭代器.大多数(如果不是全部)标准容器都有 begin()end() 成员,这非常方便,但不幸的是原始数组没有.

std::is_sorted works on a range of iterators not on a "container". To use it you need to pass an iterator to the start of the range you want to check and one past the end of the range you want to check. Most if not all standard containers have a begin() and end() members which is very convenient but unfortunately a raw array does not.

幸运的是,虽然我们有 std::beginstd::end 这将返回一个迭代器并将处理原始数组(如果数组被传递给像 void foo(int arr[]) 这样的函数,这将不起作用,因为它衰减为指针而不是数组函数).

Fortunately though we have std::begin and std::end which will return an iterator and will work with raw arrays(this will not work if the array was passed to a function like void foo(int arr[]) as it decays to a pointer and is not an array in the function).

因此,如果您想将 std::is_sorted 与原始数组一起使用,您可以使用

So if you want to use std::is_sorted with a raw array you can use

std::is_sorted(std::begin(array_name), std::end(array_name));

这将检查整个数组.

此外,您还可以使用指针表示法,因为这就是迭代器对 like 的抽象

Additionally you can also use pointer notation as that is what iterators are an abstraction of like

std::is_sorted(array_name + x, array_name + y)

其中 x[0, array_size - 1] 范围内,y[x 范围内+ 1, array_size]

Where x is in the range of [0, array_size - 1] and y is in the range of [x + 1, array_size]

这篇关于如何使用C++中的is_sorted函数检查数组是否已排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆