std::string.substr 运行时错误

std::string.substr Run Time Error

本文关键字:运行时错误 substr string std      更新时间:2023-10-16

我一直在研究一个平衡化学方程式的程序。我有它,所以它根据=将方程分成两边。我正在处理我的程序并做了一些事情,现在当我尝试将 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上,而是在向量的operator[]上。当您尝试在索引 0 和 1 处赋值时,向量仍然是空的。如果需要,它有两个保留用于扩展的位置,但其"活动区域"的大小为零;访问它会导致错误。

您可以使用push_back来解决问题,如下所示:

leftAndRightEquation.push_back(fullEquation.substr(0, (pos)));
leftAndRightEquation.push_back(fullEquation.substr( (pos+1), (fullEquation.size() - (pos)) ));

成员函数 reserve

leftAndRightEquation.reserve(2);

std::vector 不创建向量的元素。它只是为将来将添加到向量的元素保留内存。

因此,由于向量没有元素,因此您不能使用下标运算符。取而代之的是,您必须使用成员函数push_back所以第二个子字符串可以指定得更简单。

leftAndRightEquation.push_back( fullEquation.substr( 0, pos ) );
leftAndRightEquation.push_back( fullEquation.substr( pos + 1 ) );

class std::basic_string的成员函数substr按以下方式声明

basic_string substr(size_type pos = 0, size_type n = npos) const;

也就是说,它有两个带有默认参数的参数。

如果要使用下标运算符,则最初应创建具有两个元素的向量。您可以通过以下方式进行操作

std::vector<std::string> leftAndRightEquation( 2 );

之后你可以写

leftAndRightEquation[0] = fullEquation.substr( 0, pos );
leftAndRightEquation[1] = fullEquation.substr( pos + 1 );

reserve()更改为resize(),它将起作用。在所有其他情况下,reserve()调用不会导致重新分配,并且矢量容量不受影响,但resize()会受到影响。