【问题标题】:Vector of Vectors of CStrings initialization and usageVector of CStrings的Vectors初始化和使用
【发布时间】:2013-02-06 19:47:18
【问题描述】:

我正在尝试创建一个 CString 向量的向量; CStrings 的二维数组。这将表示表格中的数据。 (当然,所有数据都是 CString)。

这是我尝试初始化向量的方式>

std::vector<std::vector<CString>> tableData;
    for(int r = 0; r < oTA.rows; r++)
        for(int c = 0; c < oTA.cols; c++)
            tableData[r][c] = "Test";

这是我尝试使用它的方法

for(int r = 0; r < tabAtt.rows; r++)
    {
        // TextYpos = bottom of table + 5(padding) + (row height * row we're on)
        HPDF_REAL textYpos = tabAtt.tabY + 5 + (r*tabAtt.rowH);
        for(int c = 0; c < tabAtt.cols; c++)
        {
            // TextXpos = left of table + 5(padding) + (col width * col we're on)
            HPDF_REAL textXpos = tabAtt.tabX + 5 + c*tabAtt.colW;
            HPDF_Page_TextOut (page, textXpos, textYpos, (CT2A)tableData[r][c]); // HERE!
        }
    }

但我认为我没有正确初始化它。我不断得到一个向量超出范围的错误。

【问题讨论】:

    标签: c++ arrays c-strings libharu


    【解决方案1】:

    这是因为您需要在访问矢量元素之前分配内存并构造矢量元素。这应该有效:

    std::vector<std::vector<CString>> tableData;
    for(int r = 0; r < oTA.rows; r++)
    {
        tableData.push_back(std::vector<CString>());
        for(int c = 0; c < oTA.cols; c++)
           tableData.back().push_back("Test");
    }
    

    或者,效率稍高:

    std::vector<std::vector<CString>> tableData(oTA.rows,std::vector<CString>(oTA.cols));
    for(int r = 0; r < oTA.rows; r++)
        for(int c = 0; c < oTA.cols; c++)
           tableData[r][c]="Test";
    

    【讨论】:

      【解决方案2】:

      如果您尚未将任何内容推入向量或使用大小和填充 (see vector's constructor) 对其进行初始化,则无法通过 [] 使用索引访问初始化 std::vector 条目。因此,当tableData 为空且oTA.rowsoTA.cols0 时,这将导致问题。

      for(int r = 0; r < oTA.rows; r++)
          for(int c = 0; c < oTA.cols; c++)
              tableData[r][c] = "Test";
      

      您应该使用vector::push_back() 添加数据:

      for(int r = 0; r < oTA.rows; r++) {
          tableData.push_back(std::vector<CString>());
          for(int c = 0; c < oTA.cols; c++) {
              tableData.back().push_back("Test");
          }
      }
      

      【讨论】:

        【解决方案3】:

        如果不先添加项目,您将无法简单地访问 std::vector。要么使用 std::vector::push_back() 要么使用构造函数Cplusplus.com

        【讨论】:

          猜你喜欢
          • 2013-06-06
          • 2014-07-28
          • 1970-01-01
          • 2020-05-14
          • 1970-01-01
          • 2015-09-17
          • 1970-01-01
          • 1970-01-01
          • 2015-05-22
          相关资源
          最近更新 更多