c++ - std::string.substr 运行时错误

标签 c++ string c++11 vector std

我一直在研究平衡化学方程式的程序。我有它所以它根据 = 将等式分成两边.我正在处理我的程序并且做了一些事情,现在当我尝试设置 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/

相关文章:

javascript - 验证表单而不提交

c++ - 如何使用多态性将相同的操作应用于具有相同基类的不同对象的 unordered_sets?

c++ - 在我的类中声明的函数未显示在范围内

c# - .NET 是否有任何可用的方法来获取两个字符串的差异?

python - "cannot concatenate ' str ' and ' int ' objects"错误

c++ - 在 Visual Studio 中更改(使用旧的)c++ 版本

C++11:函数模板:通过引用传递参数

C++为什么vector初始化会调用copy constructor

java - c++中的运算符重载可以用在java中吗

c++ - 遍历 C++ unordered_map 的时间复杂度