C++中的递归列表操作

Recursive List Operation in C++

本文关键字:列表 操作 递归 C++      更新时间:2023-10-16

我一直在寻找创建一个函数,该函数接受 2 个参数、一个数组和一个键值,并递归检查数组的值以查看它们是否与键匹配。

为此,我需要检查数组是否为空。 我还需要一种方法来调用递归函数中的数组。 我找不到任何关于堆栈溢出的东西来提供帮助,但我尝试了此检查 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;

}

你当然可以通过一个简单的循环来完成这样的任务,但是,我猜你想递归地完成。我会这样做如下。这是链接,如果你想尝试它。

#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 向量。使用向量,您不必单独保留数组的大小。如果数组已排序,则可以使用类似的方法来执行二叉搜索。