[英]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()
更改為resize()
,它將起作用。 在所有其他情況下, reserve()
調用不會導致重新分配,並且向量容量不受影響,但是resize()
會影響。
會員功能reserve
leftAndRightEquation.reserve(2);
類std::vector
不會創建向量的元素。 它只是為將來將添加到向量中的元素保留內存。
因此,由於向量沒有元素,因此您可能無法使用下標運算符。 取而代之的是,您必須使用成員函數push_back
AL,以便可以更簡單地指定第二個子字符串。
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 );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.