繁体   English   中英

我需要一个在 C++ 中具有一个动态维度的二维数组

[英]I need a 2-dimensional array with one dynamic dimension in C++

我需要创建一个二维数组,其中有 8 个“行”但“列”不是预先确定的

一些沿着这个例子:

[0], ['mum', 'dad', 'uncle']
[1], ['brother', 'sister']
[2], ['friend', 'colleague', 'boss', 'employee']
.... and so on

比我必须滚动第一个索引(1 到 8)并读取所有列的每个可能值(对于每个“索引”,我都有其中包含多少元素的计数。

我需要使用类似的东西阅读

ary[2][3]    --->that would return "boss"

按照我正在使用的其他示例

unsigned char (*ary)[n] = malloc(sizeof(unsigned char[8][n]));

但它不会编译并给出:

错误:无法使用“void *”类型的右值初始化“unsigned char **”类型的变量

我如何在 C++ 中正确声明和读取这种数组?

如果在编译时知道行数,则可以使用std::array

std::array<std::vector<std::string>, number_of_rows>

您也可以使用

std::vector<std::string>[number_of_rows]

但是使用原始数组不如std::array方便。

如果行数直到运行时才知道,则可以有一个向量向量,例如

std::vector<std::vector<std::string>>

使用C ++时,请避免使用malloc 最好改用new

假设n是一个编译时间常数,则可以使用:

unsigned char (*ary)[n] = new unsigned char[8][n];

如果n是运行时变量,则很可能需要使用:

unsigned char (*ary)[8] = new unsigned char[n][8];

在以下情况下,您可以避免处理动态分配的内存的问题:

  1. 您将std::array用于unsigned char数组。
  2. 您可以使用std::vector捕获数据的动态性质。

std::struct<std::array<unsigned char, 8>> ary(n);

首先,此语法比C ++更具C语言(例如,熟悉new的知识,或者熟悉数组/向量/ STL等)。 在您的情况下,如果您确实想要C语法(malloc),则只有在知道在运行时要分配多少malloc时,才使用malloc。 您说过,您不希望所有行都使用相同的n ,因此您的行没有逻辑意义(除了是非法的):

char *a[8];
a[0] = malloc(sizeof(char)*the_amount_of_chars_plus_null_termination_in_all_strings);
/* You have to test malloc succeeded! */
/*For each row a different size, which must be known at run time*/

您没有说如何获取每一行,所以我不知道您是打算对这些值进行逐个计算,还是从输入中获取字符串,然后就可以对每个行使用strlen+1了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM