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

时间:2018-09-11 04:46:56

标签: c++ exception stdstring outofrangeexception

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

需要一些帮助来弄清楚我在做什么错。谢谢。

1 个答案:

答案 0 :(得分:4)

我已将您第二个电话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
}

另外,请注意在代码中带有错别字的发布,因为对此问题的评论已经指出。