Search code examples
c++exceptionstdstringoutofrangeexception

std::out_of_range exception in string compare


I am trying to use compare function of 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.


Solution

  • I've changed your second call to compare() to this:

    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.