如何在 c++ 中从普通数组制作多维数组
How to make a multidimensional array from a normal array in c++
如果我有一个数组,假设有 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;
}
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '