[英]std::string constructor throws std::out_of_range exception
[英]std::out_of_range exception in string compare
我正在嘗試使用std :: string的比較功能。 這是我的代碼:
int main() {
string str1 = {"apple"};
vector<string> vec1 = {"apple"};
string suffix = {"le"};
if (str1.compare(str1.size() - suffix.length(), suffix.length(), suffix) == 0)
cout << "Yes!!" << endl; // This prints
if (vec1[0].compare(vec1[0][vec1[0].size() - suffix.length()], suffix.length(), suffix) == 0)
cout << "Yes-1!!" << endl; // This doesn't
}
輸出為:
Yes!!
terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::compare: __pos (which is 108) > this->size() (which
is 5)
Aborted (core dumped)
需要一些幫助找出我在做什么錯。 謝謝。
我將您的第二個調用compare()
更改為:
if (vec1[0].compare(vec1[0].size() - suffix.length(), suffix.length(), suffix) == 0)
因為目前尚不清楚您要在原始通話中完成的任務。
這是完整的代碼,不會拋出錯誤:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int main() {
string str1 = {"apple"};
vector<string> vec1 = {"apple"};
string suffix = {"le"};
if (str1.compare(str1.size() - suffix.length(), suffix.length(), suffix) == 0)
cout << "Yes!!" << endl; // This prints
if (vec1[0].compare(vec1[0].size() - suffix.length(), suffix.length(), suffix) == 0)
cout << "Yes-1!!" << endl; // This doesn't
}
另外,請注意在代碼中帶有錯別字的張貼,因為已經注意到對問題的評論。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.