c++ - 如何在 C++ 中递归查找最大元素的索引?

标签 c++ arrays recursion max

获得最大值似乎并不难:

int getMax(int arr[], int size) {
    if(size == 1) {
        return arr[0]
    }
    return max(arr[size - 1], getMaxIndex(arr, size - 1));
}

但是我怎样才能找到它所在位置的索引呢?如果我创建一个计数变量,它会在我递归调用时立即被删除。我在网上找不到任何地方有人只使用数组和大小参数递归地执行此操作。感谢您的帮助。

最佳答案

你可以这样做:

int getMaxIndex(int arr[], int size) {
    if (size == 1) {
        return 0;
    }
    const auto recMaxIndex = getMaxIndex(arr, size - 1);
    if (arr[recMaxIndex] < arr[size - 1]) {
        return size - 1;
    } else {
        return recMaxIndex;
    }
}

关于c++ - 如何在 C++ 中递归查找最大元素的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52563234/

相关文章:

sql-server-2008 - 优化SQL Server 2008中的 Twig 数据聚合(递归)

c++ - 使用枚举指定的函数填充 vector

c++ - 将您自己的 QT C++ 数据模型与 QML 集成

java - 如何解析Sub JSONArray并显示图像?

python - 使用 Python 中的列表列表进行矢量化

javascript - 在 Javascript 中实现 Foldl 函数

c - 是否有任何 C 编译器可以向我显示递归函数的每一步?

c++ - 回调(std::function/std::bind)与接口(interface)(抽象类)的优缺点

c++ - 删除智能指针,但仍然可以访问指针?

c - c 中的结构数组 : giving all the strings same values (with the int it works well). 我该怎么办?