我撰寫了這個 isSorted 函式,它將檢查陣列是否已排序如果陣列已排序,它將回傳 0,否則將回傳 1,但由于某種原因,即使陣列未排序,該函式也會繼續回傳 0 . 這是具有功能的完整程式
struct array {
int A[10];
int size;
int length;
};
void displayArray(struct array arr) {
std::cout << "the elements are :-" << std:: endl << '\t';
for (int i = 0; i < arr.length; i ) {
std::cout << arr.A[i] << ',';
}
std::cout << std::endl;
}
int ifSorted(int *a, int n, int i) {
if (n >0) {
if (*(a i) > *(a 1 i))
return -1;
else {
i ;
ifSorted(a, n - 1, i);
}
return 0;
}
}
int main()
{
struct array arr = {{1,2,3,10,5,6,7}, 10, 7};
int* p;
std::cout << ifSorted(&(arr.A[0]), arr.length, 0);
}
我嘗試除錯程式,它按預期作業,但不是回傳 -1,而是回傳 0。
uj5u.com熱心網友回復:
但不是回傳 -1 ,而是回傳 0
當您寫入時return -1;,該值僅傳遞回呼叫者。現在,到那時,您可能會多次呼叫遞回。之前呼叫的那一行是這樣的:
ifSorted(a, n - 1, i);
因此,在該呼叫回傳后會發生什么,您丟棄 -1 的回傳值并繼續從該呼叫執行。然后你最終回傳 0,因為那是下一條陳述句。
要解決此問題,您必須將遞回呼叫回傳的任何內容傳回給呼叫者:
return ifSorted(a, n - 1, i);
現在,您還有其他一些問題。首先,讓我們看看如果n為零(或負數)會發生什么......
int ifSorted(int *a, int n, int i) {
if (n > 0) {
// this code is never reached
}
// there is no return value
}
這是個問題。對于一個非常重要的案例,您有未定義的行為。在某些時候,如果所有內容都已排序,那么您的最終遞回將詢問是否對空陣列進行了排序。當然可以,但是你的函式必須回傳一些東西。所以讓我們解決這個問題:
int ifSorted(int *a, int n, int i) {
if (n > 0) {
// this code is never reached
}
return 0;
}
現在,讓我們考慮另一種特殊情況。如果陣列中只有一個元素(即 n1)怎么辦?好吧,你正在這樣做:
if (*(a i) > *(a 1 i))
return -1;
但問題是*(a 1 i)陣列末尾的元素。
因此,實際上,您的“零大小陣列已排序”邏輯確實應該擴展到“零或一大小陣列已排序”。這將解決這個討厭的問題。
另一方面,我建議您不要使用指標演算法來訪問您的陣列元素。使用陣列索引。編譯器將生成相同的指令,但代碼更易于人類閱讀。
if (a[i] > a[i 1])
return -1;
此外,添加引數不是很“遞回友好” i。這有點表明您仍然將其視為回圈。相反,遞回是將問題分解為更小的問題。您可以做的是在將陣列指標的大小減 1 時將其前移 1。這i完全是多余的。
Finally, because the function never intends to modify the array's contents, it's best to enforce that by declaring a as const. This way, your function can operate on arrays that are already const, and you can't accidentally write code that modifies the array because that will be a compiler error.
Phew.... Well, let's put all of this together:
int ifSorted(const int *a, int n)
{
if (n < 2)
return 0;
else if (a[0] > a[1])
return -1;
return ifSorted(a 1, n - 1);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/430123.html
上一篇:使用開始和結束迭代器時出錯
