std::string.substr 运行时错误
std::string.substr Run Time Error
我一直在研究一个平衡化学方程式的程序。我有它,所以它根据=
将方程分成两边。我正在处理我的程序并做了一些事情,现在当我尝试将 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()
会受到影响。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 运行时错误:引用绑定到类型"int"的未对齐地址0xbebebebebebebec6,这需要 4 个字节对齐 (stl_vector.h)
- 试图找出为什么我会收到运行时错误?
- 迭代二维矢量时发生运行时错误
- std::string.substr 运行时错误