2013-02-06 2 views
1

CStrings의 Vector of Vector를 만들려고합니다. CStrings의 2 차원 배열입니다. 이것은 테이블의 데이터를 나타냅니다. (모든 데이터는 물론 CString입니다). 여기CStrings의 벡터 벡터 초기화 및 사용

내가 벡터>

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

을 사용하려고하지만 내가 제대로 초기화하지하고 생각하는 방법이다. 나는 경계 밖의 벡터를 계속 얻는다.

답변

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

당신은 []를 통해 인덱스 액세스 std::vector 항목을 초기화 할 수 없습니다 이미 벡터에 어떤 물체도 밀어하거나 초기화하지 않은 경우 크기 및 채우기 (see vector's constructor). 따라서 tableData이 비어 있고 oTA.rows 또는 oTA.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"); 
    } 
} 
+0

@BoPersson 제가 했어요! 네 감사합니다! XD – Foggzie

0

첫 번째 항목을 추가하지 않고 당신은 할 수없는 간단한 액세스 성병 : : 벡터. std :: vector :: push_back()을 사용하거나 생성자를 사용하십시오. Cplusplus.com