2

I am trying to create a Vector of Vectors of CStrings; a two dimensional array of CStrings. This will represent the data in a table. (All data is a CString of course).

Here is how I try to initialize the Vector>

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";

And here is how I try to use it

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!
        }
    }

But I think that I am not initializing it properly. I keep getting a vector out of bounds error.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

3 Answers3

2

This is because you need to allocate the memory and construct your vector elements prior to accessing them. This should work:

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");
}

or, slightly more efficient:

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";
Ilya Kobelevskiy
  • 5,245
  • 4
  • 24
  • 41
1

You can't initialize std::vector entries with indexed access via [] if you haven't already pushed anything into the vector or initialized it with a size and fill (see vector's constructor). So this will cause problems when tableData is empty and oTA.rows or oTA.cols are 0.

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

You should use vector::push_back() to add the data:

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");
    }
}
Foggzie
  • 9,691
  • 1
  • 31
  • 48
0

You cannot simple access a std::vector without adding items first. Either use std::vector::push_back() or use a constructor Cplusplus.com

bash.d
  • 13,029
  • 3
  • 29
  • 42