我正在实现一个 3 维数组。很像 Excel 文档的单元格和工作表。 x 和 y 是页面大小,z 是页数。目前,每个页面的 x 和 y 索引可以相同。
我想用 vector 来解决这个问题(现在我们只说字符串),但声明如下:
std::vector<std::string> sheets;
//x and y being the x-y coordinates and z being the number of pages.
int size = x*y*z;
sheets.reserve(size);
因此给了我一 block 很好的连续内存(就像 std::vector 的定义一样),这是快速和高效的。
我的问题是:有没有办法用 std::array 做到这一点? 有没有一种方法可以在创建对象时创建数组大小,或者必须在编译时知道这一点?
class sheetsObj
{
int x, y, z;
int size;
//Where size is x * y * z.
std::array<std::string, size> sheets;
public:
sheetsObj(int xInd, int yInd, int zInd) : x{ xInd }, y{ yInd }, z{ zInd } {};
....
}
提前致谢。
最佳答案
最好的经验法则是尽可能使用 std::vector
,必要时使用 std::array
。在这种情况下,std::vector
是您的最佳选择。正如您所说,std::array
的大小必须在编译时已知,因此如果您需要动态大小的存储,这是一个明智的选择。
关于c++ - C++ 中的 3 维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25811634/