我一直在研究平衡化学方程式的程序。我有它所以它根据 =
将等式分成两边.我正在处理我的程序并且做了一些事情,现在当我尝试设置 std::vector<std::string>
的第一个索引时出现运行时错误到 substr
我的等式。我需要帮助来解决这个问题。
std::vector<std::string> splitEquations(std::string fullEquation)
{
int pos = findPosition(fullEquation);
std::vector<std::string> leftAndRightEquation;
leftAndRightEquation.reserve(2);
leftAndRightEquation[0] = fullEquation.substr(0, (pos)); //!!!! Error
leftAndRightEquation[1] = fullEquation.substr( (pos+1), (fullEquation.size() - (pos)) );
removeWhiteSpace(leftAndRightEquation);
std::cout << leftAndRightEquation[0] << "=" << leftAndRightEquation[1] << std::endl;
return leftAndRightEquation;
}
这是我的 findPosition
代码.
int findPosition(std::string fullEquation)
{
int pos = 0;
pos = fullEquation.find("=");
return pos;
}
最佳答案
错误不在 substr
上,而是在 vector 的 operator[]
上。当您尝试在索引 0 和 1 处分配时, vector 仍然是空的。如果需要,它有两个保留点用于扩展,但其“事件区域”的大小为零;访问它会导致错误。
您可以使用push_back
来解决问题,如下所示:
leftAndRightEquation.push_back(fullEquation.substr(0, (pos)));
leftAndRightEquation.push_back(fullEquation.substr( (pos+1), (fullEquation.size() - (pos)) ));
关于c++ - std::string.substr 运行时错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22057128/