如何在 c++ 中从普通数组制作多维数组

How to make a multidimensional array from a normal array in c++

本文关键字:数组 c++      更新时间:2023-10-16

如果我有一个数组,假设有 15 个元素,我是否可以将其制作成具有 5x3 的 2d 数组?或者,如果我有一个带有 15 个字母的字符串,是否可以将其制作成具有 5x3 的 2d 数组?

这就是我所拥有的(使用变量,但在控制台中使用 5 作为 a,3 作为 b)

    void finishMap(string map, int a, int b)
{
    string finalMap[a][b];
    for(int i = 0; b>i; i++)
    {
        for(int x = 0; a>x; x++)
        {
            finalMap[a][b] += {{map[x]}, {i}};
        }
    }
}

对 c++ 也很陌生,所以如果你看到我不应该看到的东西,请告诉我:3

我在答案中使用 char 数组(c 字符串),因为我认为它们对于说明数组的工作原理很有用 - 而且在您的情况下使用 std::string 真的不是重点。 std::string隐藏了很多潜在的细节,所以我通常建议先使用C字符串以了解std::string的工作原理。另外,请查看本教程:http://www.cplusplus.com/doc/tutorial/arrays/

二维数组具有与一维数组相同的内存布局。在内存布局方面,char[3][5]char[3*5]相同,与char[15]相同。您可以使用 char[column+row*width] 将一维数组用作二维数组。如果您使用下标,唯一的区别是编译器会记住有多少个维度,并将为您完成整个column+row*width计算。

举个例子:

char temp[5] = "abcd"; //need 5 for string termination char ``
for(int i = 0; i < 4; ++i) {
    std::cout << temp[i];
}        
std::cout << "nn";
for(int i = 0; i < 2; ++i) {
    for(int j = 0; j < 2; ++j) {
        std::cout << temp[j+2*i];
    }
    std::cout << std::endl;
}

将打印:

abcd
ab
cd

您始终可以大步访问数组。下面是一个使用模板将 1D 数组作为 2D 数组的可能示例:

template <typename T, unsigned int N1, unsigned int N2>
struct strider
{
    using array_type = T[N1 * N2];
    array_type & data_;
    Strider(array_type & data) : data_(data) {}
    T & operator()(std::size_t i1, std::size_t i2)
    {
        return data_[i1 * N2 + i2];
    }
};
template <unsigned int N1, unsigned int N2, T>
strider<T, N1, N2> stride(T (&a)[N1, N2]) { return {a}; }

用法:

int a[15] = {};
strider<int, 3, 5> s(a);
s(1, 2) = 20;
assert(a[7] == 20);
stride<5, 3>(a)(4, 2) = 10;
assert(a[14] == 10);

我已经为跨步访问重载了operator(),因为与operator[]不同,它可以具有树架签名。

通过更多的工作,您可以使跨步视图的排名变频。

Okey所以我使用了一些与我提到的有点不同的东西。我所做的是让用户输入 3 行 5 个长度的字母,我想出了如何添加到 2d 数组中。如果您遇到与我相同的问题,这是我的代码:

int main()
{
    string path;
    int a, b;
    cin >> a >> b;
    string finalMap[a][b];
    for(int i = 0; b>i; i++){
        cin >> path;
        for(int x = 0; a>x; x++){
            finalMap[x][i] = (path[x]);
        }
    }
    for(int x = 0; b>x; x++)
    {
        for(int y = 0; a>y; y++)
        {
            cout << finalMap[y][x];
        }
        cout << endl;
    }
    return 0;
}

感谢您的尝试,真的很感激^.-

您可以尝试使用 reinterpret_cast .完整示例:

#include <iostream>
using namespace std;
typedef char mtrx[5][3];
int main(){
   char data[15] = "Some String";
   mtrx &m = *reinterpret_cast<mtrx*>(&data);
   m[1][2] = '*';
   cout << data << endl;
   return 0;
}