【问题标题】:What's the most efficient way of declaring a multidimensional array of mixed types?声明混合类型的多维数组的最有效方法是什么?
【发布时间】:2013-03-06 22:35:56
【问题描述】:

我正在创建一个类来帮助创建 excel 文件。我正在考虑在计算最终输出之前将工作表数据存储在内存中的各种方法。理想情况下,我想做std::string myArray["Sheet1"][3][7] = "this is the value of row 3 column 7 in worksheet Sheet1" 之类的事情,但这在 C++ 中似乎是不可能的......或者是吗?

有什么简单的方法可以解决这个问题,还是我必须创建一个多维向量并拥有一个带有相应索引的单独数组来确定工作表名称?即,

std::vector<std::vector<std::vector<std::string> > > Worksheet;
std::vector<std::string> WorksheetNames;
// whenever I create a new worksheet...
WorksheetNames[7] = "Sheet1";
// and then to reference that worksheets' data...
Worksheet[7][1][1] = "value of row 1 column 1";

class ExcelSheet {
    string Code, Worksheet, Style; // temp vars for data manipulation
    std::vector<std::vector<std::vector<std::string> > > Worksheet;

public:
    ExcelSheet();
    ExcelSheet(int,int);
    ~ExcelSheet();
    void Create();
    void Destroy();
    bool SetEntryValue(std::string szWorksheet, int nColumn, int nRow);
    bool SetEntryStyle(std::string szWorksheet, int nColumn, int nRow);
};

【问题讨论】:

  • 你的回答可能很优雅,“结构”对我来说毫无价值/没有任何解释。您愿意详细说明一下吗?

标签: c++ arrays visual-c++ vector


【解决方案1】:

您正在寻找(嵌套)associative containers。这样的事情应该让你开始:

typedef std::map< unsigned, std::string > columns;
typedef std::map< unsigned, columns > rows;
typedef std::map< std::string, rows > sheets;

sheets my_sheets;
my_sheets["Sheet1"][3][7] = "hello";

【讨论】:

    【解决方案2】:

    我猜std::unordered_map&lt;string, ExcelSheet*&gt; 会比存储一个字符串向量来引用您的工作表更好。

    通过这种方式,您可以在恒定时间内访问单个工作表,而不必担心很多事情。当然,这在内存中不会有连续的布局,但我想你不需要它。您仍然可以将名称存储在特定工作表中(如果需要,将它们存储在 std::vector 中)并使用地图作为配对,用于按名称访问特定工作表。

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 2017-06-27
      • 1970-01-01
      • 1970-01-01
      • 2022-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多