【问题标题】:Initialize 2d Array at compile and allow user input在编译时初始化二维数组并允许用户输入
【发布时间】:2021-12-31 15:03:38
【问题描述】:

我正在尝试通过重载构造函数声明一个在运行时/编译时调整大小的数组。

private:
auto** arr = new int[n][n];


overloadConstruct(int n){
arr[n][n] = {0,0};
}

这不起作用,它说第二个 n 需要保持不变,并且不允许使用 auto。任何帮助,将不胜感激。我不确定数组的所有规则,尤其是二维数组。我只需要能够在运行时调整二维数组的大小/通过输入进行编译。

【问题讨论】:

  • 运行时和编译时是两个不同的阶段。你想选择哪一个? runtime/compile-time 在您的情况下没有意义。请更清楚地询问。
  • auto 不允许用于班级成员。数组大小必须在 C++ 编译时知道。 gcc 允许可变数组长度作为扩展,但在此上下文中不允许。考虑改用vector
  • @digito_evo 运行时是我想要的
  • 然后检查我的答案。
  • @digito_evo 谢谢

标签: c++ arrays gcc multidimensional-array adjacency-matrix


【解决方案1】:

改为使用向量的向量:

#include <iostream>
#include <vector>


class Foo
{
public:
    Foo( const int rowCount, const int colCount )
    : m_2dArray( rowCount, std::vector<int>( colCount ) ) // initialize the vector
    {                                                     // member like this
    }

    void printArr() const
    {
        for ( size_t row = 0; row < m_2dArray.size( ); ++row )
        {
            for ( size_t col = 0; col < m_2dArray[ 0 ].size( ); ++col )
            {
                std::cout << m_2dArray[ row ][ col ] << " ";
            }

            std::cout << '\n';
        }
    }

private:
    std::vector< std::vector<int> > m_2dArray; // the vector member
};


int main ()
{
    int rowCount { };
    int colCount { };

    std::cout << "Enter row count: ";
    std::cin >> rowCount;
    std::cout << "Enter column count: ";
    std::cin >> colCount;

    std::cout << "\nThe contents of 2D array:\n";

    Foo obj( rowCount, colCount ); // construct the object using user's input
    obj.printArr( );
}

输出:

Enter row count: 10
Enter column count: 20

The contents of 2D array:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

如您所见,用户可以在运行时输入值。

【讨论】:

    猜你喜欢
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 2012-05-20
    相关资源
    最近更新 更多