std::out_of_range字符串比较中的异常

std::out_of_range exception in string compare

本文关键字:异常 比较 range out of std 字符串      更新时间:2023-10-16

我正在尝试使用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
}

另外,请注意代码中带有拼写错误的帖子,因为对该问题的评论已经指出。