C++中的递归列表操作
Recursive List Operation in C++
我一直在寻找创建一个函数,该函数接受 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 向量。使用向量,您不必单独保留数组的大小。如果数组已排序,则可以使用类似的方法来执行二叉搜索。
相关文章:
- 为什么在popback()操作之后,它仍然打印完整的矢量
- Pybind11:将元组列表从Python传递到C++
- 从push_front操作中获取常规 MPL 列表
- 如何让迭代器使用赋值运算符对列表进行操作
- 自定义张量流操作获取可变输入张量的列表
- 操作可变参数模板参数列表
- 成员初始化器列表中的分配操作
- C 在给定列表中执行每种类型的操作
- 使用 rapidjson 从 json 解析操作列表
- 如何在C 中的用户提交变量列表中执行多个操作
- Python扩展在操作大列表时会创建无效指针
- C++列表迭代器如果列表更改则重新启动操作
- C++中的递归列表操作
- 在 UML 中使用变量参数列表的操作
- Rcpp犰狳:对列表元素的"-="操作
- 使用语义操作分析逗号分隔的范围和数字列表
- 构造函数初始化列表vs昂贵操作
- 操作迭代器列表+指针
- 如何在MITK中访问图像属性列表和操作
- 如何根据列表中的对象的运行时类型而不是基本类型对其进行操作