c++ - 需要帮助编写一个函数来查找 N 维数组 C++ 中的最大值和最小值

标签 c++ arrays algorithm sorting vector

我需要在我的程序中找到不同维度(将是一维、二维和最多 N 维数组)的数组的最大值和最小值。

谁能帮我写一个函数或函数模板,可以接受任意维度数组的输入并找到最大/最小值? * 我正在使用 vector 的 vector 像这样:

#include <vector>
    <template T>
int find_max(T target_array, int dimension);
int main() {
    using namespace std;
    vector<int> array_1d = {1,3,4};
    vector<vector<int> array_2d = {{1,3},{3,5,2},{6,4}};
    vector<vector<vector<int>>> array_3d = {{{1,3},{2,4,5}},{{6,7,2,3}}};
    cout << "Max in 1d array: " << find_max<vector<int>>(array_1d, 1) << endl;
    cout << "Max in 2d array: " << find_max<vector<vector<int>>(array_2d, 2) << endl;
    cout << "Max in 3d array: " << find_max<vector<vector<vector<int>>>>(array_3d, 3) << endl;  
    return 0;          
}

输出:

Max in 1d array: 4
Max in 2d array: 6
Max in 3d array: 7
Program ended with exit code: 0

谢谢

最佳答案

您编写签名的函数可以通过简单调用 std::max_element 来实现。

然后您可以使用接受任何嵌套 vector 的模板重载此函数,它首先递归地将函数应用于 vector 的每个元素,然后再计算它们的最大值。

下面的代码实现了这个想法。第二个参数 int dimension 不是必需的,因为维度数由第一个参数的类型给定。

如果您同时需要 min 和 max 元素,您可以使用类似 std::minmax_element 的基本情况,但递归调用会变得更加复杂。

现场演示:http://ideone.com/kW0ewz

// Forward-declare
template<class T>
int find_max(std::vector<std::vector<T> > target_array);

// First, define the base case
int find_max(std::vector<int> target_array) {
    using namespace std;

    return *max_element(
        target_array.begin(),
        target_array.end());
}

// Then the general case
template<class T>
int find_max(std::vector<std::vector<T> > target_array) {
    using namespace std;

    // Reserve a vector for the recursive call
    vector<int> reduced(target_array.size());

    // Recursively apply this function to each nested vector
    transform(
        target_array.begin(),
        target_array.end(),
        reduced.begin(),
        [](std::vector<T> v){ return find_max(v); });

    // Then find the maximum of the reduced vector
    return *max_element(
        reduced.begin(),
        reduced.end());
}

关于c++ - 需要帮助编写一个函数来查找 N 维数组 C++ 中的最大值和最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25297252/

相关文章:

模板类中的 C++ 模板 static const 成员变量

PHP使用正则表达式将字符串解析为数组

C++ 运算符 '<<' 错误

c++ - Vim 搜索类

c - 在 C 中初始化多维数组

Ruby - 列表减号

algorithm - 具有燃料限制的最短路径

algorithm - AI - 启发式函数要求

algorithm - 应该对算法/代码进行哪些更改才能获得预期的车辆形状?

python - 这段python代码中的大于号是什么意思?