![](/img/trans.png)
[英]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.