2016-04-28 47 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向量的数组。使用向量,您不必分开保存数组的大小。如果对数组进行排序,则可以使用类似的方法进行二分搜索。