问题
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