如何从函数返回常量值的二维数组? 我需要返回这样的东西:
//I don't even know if this is the best way to do 2d arrays in c++.
const int matrix[4][2] = {
{10,11},
{12,13},
{14,15},
{16,17}
};
这是我尝试过的:
#include <iostream>
using namespace std;
int** createMatrix();
int main(){
int **m = createMatrix();
return 0;
}
const int** createMatrix(){
const int **matrix = new const int*[4];
matrix[0] = new const int[2] = {10,11};
matrix[1] = new const int[2] = {12,13};
matrix[2] = new const int[2] = {14,15};
matrix[3] = new const int[2] = {16,17};
return matrix;
}
我得到的输出:
main.cpp: In function ‘const int** createMatrix()’: main.cpp:12:13: error: ambiguating new declaration of ‘const int** createMatrix()’ const int** createMatrix(){ ^~~~~~~~~~~~
main.cpp:5:7: note: old declaration ‘int** createMatrix()’ int** createMatrix(); ^~~~~~~~~~~~
main.cpp:15:29: error: uninitialized const in ‘new’ of ‘const int’ matrix[0] = new const int[2] = {10,11}; ^
main.cpp:16:29: error: uninitialized const in ‘new’ of ‘const int’ matrix[1] = new const int[2] = {12,13}; ^
main.cpp:17:29: error: uninitialized const in ‘new’ of ‘const int’ matrix[2] = new const int[2] = {14,15}; ^
main.cpp:18:29: error: uninitialized const in ‘new’ of ‘const int’ matrix[3] = new const int[2] = {16,17};
最佳答案
简单的解决方案是创建一个数组数组,就像您首先展示的那样,然后返回它。
在函数内部让它成为static
,这样它的生命周期就不会结束。并记住返回正确的类型(数组的数组与指向指针的指针不同)。
可选择使用 std::array
而不是普通的 C 风格数组。
如果大小可在运行时配置,则使用 std::vector
.
关于c++ - 在 C++ 中返回具有常量值的矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49256862/