gpt4 book ai didi

C++ 错误 : vector subscript out of range, 行 1201

转载 作者:行者123 更新时间:2023-11-28 06:03:49 24 4
gpt4 key购买 nike

C++ 新手。尝试调试代码时收到“超出范围”错误消​​息。我尝试使用 resize(),但仍未修复。代码是将指令读入二维 vector 并打印出图形。我做错了什么?

#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;
}
}
}

最佳答案

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
}

关于C++ 错误 : vector subscript out of range, 行 1201,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com