C++ 为什么此错误"basic_string::substr"并破坏循环

c++ why this error "basic_string::substr" and breaking up the loop

本文关键字:substr 循环 为什么 错误 basic C++ string      更新时间:2023-10-16

我试图得到一个词的最后一个字母,比较如果这些字母行是在一个向量。我想先检查最后2个字母,然后是最后3个和最后4个字母。一旦它找到一个,它就会中断,并返回false。否则,它应该检查所有留下的东西,如果没有发现,就返回,这是真的。

This my function:

bool isIt(wstring word, vector <wstring> vec) {
int ct = 2;
while (ct < 5) {
    word = word.substr(word.length() - ct, word.length()-1);
    //wcout << word << endl;
    if (find(vec.begin(), vec.end(), word) != vec.end()) {
        //wcout << "false" << endl;
        ct = 5; return false;
    } else {ct++; wcout << ct << endl; continue; }
}  return true;}

函数通过this调用:

if( word >3){ isIt(word, vec); }

当第一次检查失败时,我收到这个错误消息:

抛出std::out_of_range实例后调用终止(): basic_string: substr

我不明白,为什么它不继续,一旦它在else部分。我希望我的描述足够好。BR

bug在这里,在这里修改word

    word = word.substr(word.length() - ct, word.length()-1);

如果word"ABCD"进入这个函数,那么第一次通过循环,结果为:

    word = std::string("ABCD").substr( 2, 3 );

第二次循环的结果是:

    word = std::string("CD").substr( size_t(-1), 1 );