简体   繁体   English

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

[英]std::out_of_range exception in string compare

I am trying to use compare function of std::string. 我正在尝试使用std :: string的比较功能。 Here is my code: 这是我的代码:

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
}

The output is: 输出为:

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)

Need some help figuring out what am I doing wrong. 需要一些帮助找出我在做什么错。 Thanks. 谢谢。

I've changed your second call to compare() to this: 我将您的第二个调用compare()更改为:

if (vec1[0].compare(vec1[0].size() - suffix.length(), suffix.length(), suffix) == 0)

as it was unclear what you we're trying to accomplish in the original call. 因为目前尚不清楚您要在原始通话中完成的任务。

This is the full code that works without throwing an error: 这是完整的代码,不会抛出错误:

#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
}

Also, beware of posting with typos in the code, as the comment on the question already noted. 另外,请注意在代码中带有错别字的张贴,因为已经注意到对问题的评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM