2

我正在尝试获取单词的最后一个字母,以比较这些字母行是否在向量中。所以我想先检查最后 2 个,然后是最后 3 个和最后 4 个字母。一旦它找到一个,它就应该分解,并返回 false。否则它应该检查剩下的所有东西,并在没有任何证据的情况下返回,真的。

这是我的功能:

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

该函数通过以下方式调用:

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

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

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

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

4

1 回答 1

2

错误在这里,您可以在其中修改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 );
于 2013-03-24T16:47:21.177 回答