c++ - 在 C++ 中返回具有常量值的矩阵

标签 c++ arrays pointers

如何从函数返回常量值的二维数组? 我需要返回这样的东西:

//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/

相关文章:

arrays - NumPy:用三维数组中的平均值替换第三维的所有元素

c - 在 C 中获取锯齿状数组的长度

c++ - 可变模板函数

c++ - QSqlDatabasePrivate::removeDatabase: connection 'myConnectionName' is still in use, 所有查询将停止工作

c++ - Qt StyleSheet 以编程方式创建QWidget

c++ - 为什么将 unique_ptr 与数组一起使用会导致编译错误?

java - 以整数数组作为参数并返回字符串的静态方法

c++ - 成员包含其他继承类的继承类?

c++ - Const 指针的问题

c++ - Boost序列化树结构