How to check whether an array is sorted or not using is_sorted function in C++?

梦想与她 提交于 2019-12-23 06:35:35

问题


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


回答1:


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]



来源:https://stackoverflow.com/questions/35989316/how-to-check-whether-an-array-is-sorted-or-not-using-is-sorted-function-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!