首页 > 解决方案 > 如何在此代码中将数字添加到我的数组中?

问题描述

我想制作一个包含所有数字的 3 维列表。示例:N=2 我的数组必须包含所有变体:

000
001
002
003
010
...
210
211
212
213

如何将数字添加到我的数组中?

#include <iostream>
using namespace std;

int main ()
{
int N;
cin >> N;

int array[N][2][4]={0};

    for (int i=0; i<N; ++i)
    {
        for (int j=0; j<2; ++j)
        {
            for (int k=0; k<4 ; ++k)
            { 
                cout << array [i][j][k]<< endl;
            }
        }
    }
return 0;
}

标签: c++arrays

解决方案


嗯,我很难理解你的问题。你只想动态分配内存?然后你可以使用该new语句。

就像下面的例子:

#include <iostream>
#include <iomanip>

constexpr unsigned int DimensionZ = 4;
constexpr unsigned int DimensionY = 2;

using YZArray = int[DimensionY][DimensionZ];

int main() {

    unsigned int dimensionX{};
    if ((std::cin >> dimensionX) and (dimensionX > 0)) {

        
        YZArray* xyzArray = new YZArray[dimensionX]{};

        for (unsigned int x = 0; x < dimensionX; ++x)
            for (unsigned int y = 0; y < DimensionY; ++y)
                for (unsigned int z = 0; z < DimensionZ; ++z)
                    xyzArray[x][y][z] = 100 * x + 10 * y + z;

        for (unsigned int x = 0; x < dimensionX; ++x)
            for (unsigned int y = 0; y < DimensionY; ++y)
                for (unsigned int z = 0; z < DimensionZ; ++z)
                    std::cout << std::right << std::setfill('0') << std::setw(3) << xyzArray[x][y][z] << '\n';

        delete[] xyzArray;
    }
}

请在上面的示例中输入 3,然后您将获得您的序列。


但是,因为答案很简单,所以我想这是错误的。我的猜测是你想要 3 个并行的一维数组,然后构建它们的组合。请更清楚地说明。


推荐阅读