如何检查数组是否使用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 :: begin
和 std :: 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::being(array_name), std::end(array_name));
这将检查整个数组。
另外你也可以使用指针符号,因为这是迭代器是一个像
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]