2015-09-24 82 views
0

新增至C++。嘗試調試代碼時,我收到「超出範圍」的錯誤消息。我試圖使用resize(),但它仍然沒有修復。代碼是將指令讀入2d矢量並打印出圖形。 我在做什麼錯?C++錯誤:向量下標超出範圍,行1201

#include<iostream> 
#include<fstream> 
#include<vector> 
#include<string> 
#include<sstream> 

using namespace std; 

typedef struct Pattern{ 
    int rowNum; 
    int colNum; 
    char token; 
    bool isTriangular; 
    bool isOuter; 
}Pattern; 

void CommandProcessing(vector<string>&, Pattern&); 
void Builder(Pattern&, vector<vector<char>>&); 
void Printer(vector<vector<char>>&); 

int main() 
{ 
    Pattern characters; 
    vector<vector<char>> key; 

    characters.colNum = 3; 
    characters.rowNum = 3; 
    characters.token = '@'; 
    characters.isOuter = false; 
    characters.isTriangular = false; 

    Builder(characters, key); 
    Printer(key); 
} 

void Builder(Pattern& character, vector<vector<char>>& matrix) 
{ 
    int i = 0, j = 0; 
    char c; 

    if (character.token == 0) 
     c = 'a'; 
    else 
     c = character.token; 

    matrix.resize(character.rowNum); 
    for (int i = 0; i < character.rowNum; i++){ 
     if (character.isTriangular) 
      matrix[i].resize(i + 1); 
     else 
      matrix[i].resize(character.colNum); 

     if (character.isOuter) 
     { 
      if (character.isTriangular) 
      { 
       if (i = j) 
        matrix[i][j] = c; 
       else 
        matrix[character.rowNum - 1][i] = matrix[i][0] = c; 
      } 
      else 
       matrix[0][j] = matrix[i][0] = matrix[character.rowNum - 1][j] = matrix[i][character.colNum - 1] = c; 
      i++; 
      j++; 
     } 

     else 
     { 
      if (character.isOuter) 
      { 
       while (i <= j){ 
        for (i = 0; i < character.rowNum; i++) 
         for (j = 0; i < character.colNum; j++) 
          matrix[i][j] = c; 
       } 
      } 
      else 
       for (i = 0; i < character.rowNum; i++) 
        for (j = 0; i < character.colNum; j++) 
         matrix[i][j] = c; 
     } 
     c++; 
    } 

} 
void Printer(vector<vector<char>>& print) 
{ 
    for (int i = 0; i < print.size(); i++){ 
     for (int j = 0; j < print[i].size(); j++) 
     { 
      cout << print[i][j] << endl; 
     } 
    } 
} 
+1

讓步標題行的數目無標記的地方是在你的代碼的發佈是無用的(幸運的是,你不要張貼1200+線)... – Jarod42

+0

@ Jarod42我不知道它爲什麼說線1201,這是我所有的線 –

+0

它應該是在向量標題線...順便說一句,與調試器,你應該知道並突出你的代碼哪一行有問題。 – Jarod42

回答

1

if (i = j)應該是if (i == j)

if (i = j)做一個任務和測試是否i != 0

其他問題:

while (i <= j){ 
    for (i = 0; i < character.rowNum; i++) 
     for (j = 0; i < character.colNum; j++) // You test `i` instead of j 
      matrix[i][j] = c; 
    // Once test fixed 
    // Here `i == character.rowNum` and `j == character.colNum` (if `character.rowNum != 0`) 
    // So the while loop condition doesn't change and may so do infinite loop 
} 
+0

剛剛發佈的問題是在'for(j = 0; i YePhIcK

+0

我已經修復了測試,但我仍然不明白'如果character.rowNum!= 0'部分 –

+0

簡而言之,我說'while(i <= j)'應該被移除(或者內部的邏輯應該被改變)。 – Jarod42