c++ - C++ 中的 3 维数组

标签 c++ arrays c++11 vector

我正在实现一个 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/

相关文章:

模板类型的 C++ Constexpr 成员

php - Mysqli - 将结果绑定(bind)到数组

C++ 可变类模板和成员函数

c++ - 使 Stack Walker 在启用优化的应用程序中工作

c++ - GDB:运行没有符号的cpp进程调试

c++ - 无法在 C++ 中创建结构 vector

jquery - 从键值数组中获取值

arrays - node.js,restify - 处理数组类型的参数

c++ - 将 unique_ptrs 从一个 vector move 到另一个 vector

c++ - C++ std::unordered_map 中使用的默认哈希函数是什么?