【问题标题】:std::string.substr Run Time Errorstd::string.substr 运行时错误
【发布时间】:2014-03-30 05:02:41
【问题描述】:

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

【问题讨论】:

  • reserve 实际上并没有创建任何新元素。
  • 旁注:为什么使用向量而不是两个变量?
  • @Cameron 因为后来我必须对它们执行一些操作,我认为最好的做法是编写一个循环而不是两次相同的代码,但变量除外。
  • 那么如果 findPosition() 返回找不到字符串怎么办?
  • @PaulMcKenzie,我不认为我应该有这个问题。我的程序进入需要 findPosition() 的阶段的唯一方法我还没有进入异常处理。我会将代码发布到我原来的问题中,你可以告诉我你的想法。老实说,我什至没有考虑过。

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


【解决方案1】:

错误不在substr 上,而在矢量的operator[] 上。当您尝试在索引 0 和 1 处分配时,向量仍然是空的。如果需要,它有两个点保留用于扩展,但其“活动区域”的大小为零;访问它会导致错误。

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

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

【讨论】:

    【解决方案2】:

    会员功能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 );
    

    【讨论】:

    • 感谢我的第二个substr 的简化。我没有意识到reserveresize 之间的区别。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2018-09-12
      相关资源
      最近更新 更多