std::out_of_range 字符串比较异常

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
}

此外,请注意不要在代码中出现拼写错误,因为问题的评论已经指出。