[英]How to check whether an array is sorted or not using is_sorted function in C++?
我需要使用std::is_sorted()
函數檢查數組是否已排序。 我不確定如何使用begin()
和end()
所以我只是將數組傳遞給函數。
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;
}
當我這樣做時,雖然我收到了類似的錯誤
is_sorted 函數沒有匹配的調用
std::is_sorted
適用於不在“容器”上的一系列迭代器。 要使用它,您需要將迭代器傳遞到要檢查的范圍的開頭和要檢查的范圍末尾的迭代器。 大多數(如果不是全部)標准容器都有一個begin()
和end()
成員,這非常方便,但不幸的是原始數組沒有。
幸運的是,盡管我們有std::begin
和std::end
,它們將返回一個迭代器並可以處理原始數組(如果數組被傳遞給像void foo(int arr[])
這樣的函數,這將不起作用,因為它衰減到一個指針,而不是函數中的數組)。
因此,如果您想將std::is_sorted
與原始數組一起使用,您可以使用
std::is_sorted(std::begin(array_name), std::end(array_name));
這將檢查整個數組。
此外,您還可以使用指針表示法,因為迭代器是類似的抽象
std::is_sorted(array_name + x, array_name + y)
其中x
在[0, array_size - 1]
范圍內, y
在[x + 1, array_size]
范圍內
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.