【发布时间】: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