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

Cha*_*how 1 c++ arrays sorting algorithm vector

我需要在我的程序中找到不同维度(将是1维,2维和最多N维数组)的数组的最大值和最小值.

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

#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;          
}
Run Code Online (Sandbox Code Playgroud)

OUTPUT:

Max in 1d array: 4
Max in 2d array: 6
Max in 3d array: 7
Program ended with exit code: 0
Run Code Online (Sandbox Code Playgroud)

谢谢

lee*_*mes 5

您编写签名的功能可以通过简单的调用来实现std::max_element.

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

以下代码实现了这个想法.第二个参数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());
}
Run Code Online (Sandbox Code Playgroud)