2016-04-28 32 views
-1

我正在創建一個函數,它需要2個參數,一個數組和一個鍵值,並遞歸檢查數組的值以查看它們是否與鍵匹配。在C++中的遞歸列表操作

爲了達到這個目的,我需要檢查數組是否爲空。我也需要一種方法來在我的遞歸函數中調用數組。我無法找到任何堆棧溢出來幫助,但我嘗試了這個Check if list is empty in C#後建議的方法,並且代碼給出了一個錯誤。

TLDR需要弄清楚如何檢查數組是否爲空,以及如何對接受數組作爲參數的函數進行遞歸調用。

// recursive method: increment count for each recursive call; return the value of count when the key matches the value, then decrement count on 
int Search::ReKeySearch(int arr[], int key){ 
//bool isEmpty = !list.Any(); tried to use this code, found on StackExchange, gave following error: "Cannot refer to class template 'list' without a template argument list" 

if (arr[count] == 0){ //if the key matches the list index's value 
    store = count; // so that I can reset count to zero, I use a storing variable 
    count = 0;  // count should always be zero on exiting or entering a function 
    return store; 
} 

else{ 
    count++; 
    if (/*need to check if list is empty*/){ 
     ReKeySearch(arr[1:], key); //recursive call to function on list after zeroth member 
             //returns error "expected ']'", pointing to the colon 
     }// using pointer to attack problem of list index 
    else 
     ; 
    count--; 
} 
if (count == 0) 
    return -1; 

}

+2

這個'arr [1:]'看起來不像C++代碼。 –

+0

他們可能是想說'arr + 1'。 – paddy

+0

你可以寫模板函數,並專門爲0的情況,或者,只需使用std :: vector – Incomputable

回答

0

當然你也可以做到用一個簡單的循環這樣的任務,但是,我猜測你想遞歸地做到這一點。我會這樣做。如果你想試驗它,這裏是link

#include <iostream> 
#include <vector> 
using namespace std; 

int searchHelper(const int arr[], int start, int stop, int key) 
{ 
    if(start == stop) return -1; 
    if(arr[start] == key) return start; 
    return searchHelper(arr, start + 1, stop, key); 
} 

int search(const int arr[], int size, int key) 
{ 
    return searchHelper(arr, 0, size, key); 
} 

int search(vector<int> const& vec, int key) 
{ 
    return searchHelper(vec.data(), 0, (int)vec.size(), key); 
} 

int main() { 
    int arr[] = {3,10,2,5,6,1}; 

    cout << search(arr, 6, 10) << endl; 
    cout << search(arr, 6, 20) << endl; 

    return 0; 
} 

請注意,我提供了兩種方法,一種是使用STL向量的數組。使用向量,您不必分開保存數組的大小。如果對數組進行排序,則可以使用類似的方法進行二分搜索。