c ++错误:向量下标超出范围,第1201行

时间:2015-09-24 23:49:50

标签: c++ vector

c ++新手。尝试调试代码时,我收到“超出范围”错误消​​息。我试过使用resize(),但它仍然没有修复。代码是将指令读入2d向量并打印出图形。 我做错了什么?

#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 个答案:

答案 0 :(得分: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
}