函数调用无法与 C++ 中的候选模板定义(通过引用接收二维数组的函数)匹配

Function call cannot be matched to a candidate template definition (of a function to receive 2D array by reference) in C++

这里的新手尝试用不同的方法在 C++ 中传递 array-by-reference。
对于 C++,geeksforgeeks(在标题 模板方法(对数组的引用) 下)展示了一种通过创建模板在 C++ 中通过引用传递数组的方法。我正在尝试它,因为它似乎是一种不使用指针并且仍然在每个不同的函数调用上传递不同大小的数组的方法。

请注意,在以下来自 geeksforgeeks 的代码中,为数组的大小指定了一个模板参数。

// CPP Program to demonstrate template approach
#include <iostream>
using namespace std;

template <size_t N> void print(int (&a)[N])
{
    for (int e : a) {
        cout << e << endl;
    }
}

// Driver Code
int main()
{
    int a[]{ 1, 2, 3, 4, 5 };
    print(a);
}

我试图通过制作一个模板来扩展二维数组的逻辑:

template <size_t r, size_t c>
float approach_mean(vector<int>& n, float (&a)[r][c], float m, float d) {
    return 0;
}

class Solution {
public:
    int minimumDeviation(vector<int>& nums) {
        float m = accumulate(nums.begin(), nums.end(), 0) / nums.size();
        float dev = 0, devp = 0;
        long double s = 0;
        float r[2][nums.size()];
        for (int i0 = 0; i0 < nums.size(); ++i0) {
            r[0][i0] = nums.at(i0);
            r[1][i0] = m - nums.at(i0);
            dev = dev + abs(m - nums.at(i0));
        }
        dev = dev / nums.size();
        while (devp < dev) {
            devp = dev;
            dev = approach_mean(nums, r, m, dev);
            break;
        }
        return devp;
    }
    
//     float approach_mean() {
        
//     }
};

根据运行这段代码,我得到一个错误

Line 21: Char 19: error: no matching function for call to 'approach_mean'
            dev = approach_mean(nums, r, m, dev);
                  ^~~~~~~~~~~~~~~
Line 2: Char 7: note: candidate template ignored: could not match 'float' against 'float'
float approach_mean(vector<int>& n, float (&a)[r][c], float m, float d) {
      ^
1 error generated.

我实在想不出解决这个错误的办法。我知道由于某些原因它无法匹配 return 类型,即使它们相同。

整个逻辑是 Problem 1675 on Leetcode 的解决方案的 WIP,它是关于减少数组中的偏差。

这里是问题的部分描述:

You are given an array nums of n positive integers.

You can perform two types of operations on any element of the array any number of times:

If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the last element, and the array will be [1,2,3,2].

If the element is odd, multiply it by 2. For example, if the array is [1,2,3,4], then you can do this operation on the first element, and the array will be [2,2,3,4].

The deviation of the array is the maximum difference between any two elements in the array.

Return the minimum deviation the array can have after performing some number of operations.

问题float r[2][nums.size()];不是标准的C++,因为数组的大小必须是编译时间常数 .

但由于nums.size()不是常量表达式所以它不能用于指定数组的大小而且它不能被使用作为模板非类型参数作为模板非类型参数必须是编译时常量。

您可以通过在 float r[2][nums.size()]; 中用一些常量表达式更改 nums.size() 来验证这一点,您会发现提到的错误消失了。

//-----------------v------>nums.size() replaced with 5
        float r[2][5];

Demo with no compile time error