且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查数组是否排序或C ++中不使用将已排序功能?

更新时间:2023-11-26 10:06:16

的std ::已排序在一系列的迭代器作品不是一个容器。要使用它,你需要一个迭代器传递给您要检查一过去,你要检查的范围结束范围的开始。如果不是所有的标准容器有一个开始()端()的成员,这是非常方便的,但不幸的是原数组没有。

但幸运的是我们有 的std ::开始 的std ::结束 它会返回一个迭代器,并与原工作数组(如果该阵列传递给函数如无效美孚,这将不起作用( INT ARR [])因为它衰减到一个指针,而不是在函数数组)。

所以,如果你想使用的std ::已排序与原始阵列可以使用

 的std ::将已排序(性病::是(ARRAY_NAME)的std ::结束(ARRAY_NAME));

这将检查整个数组。

此外,你还可以使用指针符号因为这是迭代器是像

抽象
 的std ::将已排序(ARRAY_NAME + X,ARRAY_NAME + Y)

其中, X 的范围[0,ARRAY_SIZE - 1] 的范围[X + 1,ARRAY_SIZE]

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

there is no matching call for is_sorted function

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.

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).

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

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

Which will check the whole array.

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)

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