void 值没有被忽略,因为它应该是(试图将 void 分配给非 void 变量?

Void value not ignored as it ought to be (Trying to assign void to non-void variable?)

本文关键字:void 分配 变量 因为      更新时间:2023-10-16
vector<vector<int>> matrixReshape(vector<vector<int>>& nums, int r, int c) {
int row = nums.size();
int col = nums[0].size();
vector<vector<int>> newNums;
if((row*col) < (r*c)){
return nums;
}
else{
deque<int> storage;
for(int i = 0; i < row; i++){
for(int k = 0; k < col; k++){
storage.push_back(nums[i][k]);
}
}
for(int j = 0; j < r; j++){
for(int l = 0; l < c; l++){
newNums[j][l] = storage.pop_front();
}
}
}
return newNums;
}

嘿伙计们,我遇到了一个问题,我遇到了上面标题的上述错误"无效值没有被忽略,因为它应该是"。当我查找错误消息时,提示指出"这是一个 GCC 错误消息,这意味着函数的返回值是'void',但您正在尝试将其分配给非 void 变量。不允许将 void 分配给整数或任何其他类型。读完这篇文章后,我以为我的 deque 没有被填充;但是,我无法找出为什么我的deque没有被填充。如果你们想知道我试图解决的问题,我将在下面发布。此外,我无法通过调试器运行它,因为它不会:(编译。提前谢谢。

在 MATLAB 中,有一个非常有用的函数称为"reshape",它可以将矩阵重塑为具有不同大小但保留其原始数据的新矩阵。

你得到一个由二维数组表示的矩阵,以及两个正整数 r 和 c,分别表示所需整形矩阵的行号和列号。

重塑后的矩阵需要以与它们相同的行遍历顺序填充原始矩阵的所有元素。

如果使用给定参数的"整形"操作是可能的且合法的,则输出新的整形矩阵;否则,输出原始矩阵。

Example 1:
Input: 
nums = 
[[1,2],
[3,4]]
r = 1, c = 4
Output: 
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.

这条线有两个问题:

newNums[j][l] = storage.pop_front();

首先,pop_front()不会返回弹出的元素。要获取双端格式的第一个元素,请使用storage[0]。然后调用pop_front()将其删除。

你也不能分配给newNums[j][i],因为你没有分配向量的那些元素。您可以通过像这样声明来预分配所有内存。

vector<vector<int>> newNums(r, vector<int>(c));

所以上面的行应该替换为:

newNums[j][l] = storage[0];
storage.pop_front();