gpt4 book ai didi

c++ - 二维 vector ( vector 下标超出范围)

转载 作者:行者123 更新时间:2023-11-28 06:26:04 38 4
gpt4 key购买 nike

我编写了将字符串解析为称为输入的二维 vector 的代码。我想将第一个索引的字符串放入一个 vector 中,该 vector 存储具有 lhs 和 rhs 的节点。每个 vector 的第一个索引应该在 lhs 中,每个其他字符都应该在 rhs 中。我使用循环 3 次或更多次的代码得到一个超出范围的 vector 下标。我做错了什么?

struct finalNode
{
string rhs;
string lhs;
bool isTerm;

};

void fillGramRules()
{
for (int i = 0; i < input.size(); i++)
{
finalNode fNode;

//attempts to copy first position 0 of every array to string lhs of fnode, this crashes the program
fNode.lhs = input[i][0].symbol;
newNode.isTerm = input[i][0].isTerminal;
for (int j = 1; j < input[i].size()-1; j++)
{
newNode.rhs.append(input[i][j].symbol);
newNode.isTerm = input[i][j].isTerminal;
}
gramRules.push_back(fNode);
}
}

最佳答案

如果 input[i] 为空,则尝试访问 input[i][0] 将导致崩溃,因此您可能需要先检查一下。

if(!input[i].empty()) {
fNode.lhs = input[i][0].symbol;
newNode.isTerm = input[i][0].isTerminal;
}

关于c++ - 二维 vector ( vector 下标超出范围),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28511564/

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