【问题标题】:recursive function has out_of_range exception递归函数有 out_of_range 异常
【发布时间】:2012-07-25 05:16:48
【问题描述】:

给定一个包含 ASCII 码和相应数值的全局向量 list 和一个字符串,例如 000.00-000.0.0.0,这个函数接受一个 2 字符或 3 字符长的 input 标记字符串,并将其替换为单个 ASCII表示 0 到 184 之间的数值的符号,然后将不带分隔符的缩短字符串返回为 out。此外,在反向(方向 1)给定 ASCII 符号的情况下,它会转换回数字字符串并返回。

//looks for input string in vector and returns output, 'c' is check row, 'r' is return row
string vectorSearch(string &check, int n, int c, int r) 
{
    if (check.length() <= 1) 
        return check;
    if (list[n][c] == check || list[n][c] == ('0'+check)) //adds leading zero if 2char long
        return list[n][r];
    else 
        return vectorSearch (check, ++n, c, r);
}

//this function takes an ontology and either changes from single char 
//to string or takes strings and converts to char representation
string Lexicon::convertOntology(string input, int direction, string out, string temp) 
{
    if (input == "" && temp == "") 
        return out; //check for completed conversion
    else {
        if (input[0] == '.' || input[0] == '-' || input == "") { //found deliniator or endk
            if (input != "") return convertOntology(input.substr(1),direction, 
                 out+=vectorSearch(temp, 0, direction, 1-direction), "");
            else return convertOntology("", direction, 
                 out+=vectorSearch(temp, 0, direction, 1-direction), "");
        } else 
            return convertOntology(input.substr(1), direction, out, temp+=input[0]); //increment and check
    }
}

这些函数工作正常,除了在最后一个字符被解析后输出。在return convertOntology(input.substr(1), direction, out+=add, temp); 线上有一个中断,当input == ""temp == "0" 时出现错误 - 最后一次通过vectorSearch() 应该清除临时并将临时字符添加到输出字符串,因为临时是== 1char那么它应该按原样从vectorSearch() 返回。然后清除inputtemp == ""convertOntology()返回校验。但是,它永远不会在vectorSearch() 的第一行中断,并且有一个

Unhandled exception at 0x77bc15de exception: std::out_of_range at memory location 0x0035cf1c

发生了什么事?这是通过返回进行递归回溯的问题吗?我在某处缺少返回以打破递归循环?

【问题讨论】:

  • 我可能已经找到了;在最后一轮 input.substr(1) 在字符串 "" 上被调用

标签: c++ visual-studio-2008 recursion backtracking outofrangeexception


【解决方案1】:

对于 temp == ""input != "" 你调用 input.substr(1) 的情况,嗯,超出范围。

【讨论】:

    【解决方案2】:

    即使你没有进入 else 部分,

    input.substr(1)
    

    input 字符串正好是一个字符时会抛出异常。

    似乎不允许 - input.substr(input.size()) 被允许,并返回一个空字符串。


    您稍后可能会在 VectorSearch 中遇到类似的问题。如果没有匹配,您将递增 n 直到超出范围。

    【讨论】:

    • 捕获不匹配的情况 - 这是为下一个版本保存的功能。我将用 1 个字符测试 input.substr(1),第一轮似乎没问题。
    • 我添加了这个修复方法if (check.length() &lt;= 1 || n &gt; 200)
    • 是的,我错了——实际上没问题。 substr(pos) 中的 pos 的要求是 pos &lt;= size(),而不是我假设的 pos &lt; size()。这很奇怪。所以substr(1) 会在size() == 1 时得到一个空字符串。
    猜你喜欢
    • 2015-02-20
    • 2021-07-12
    • 1970-01-01
    • 2022-01-23
    • 2020-10-01
    • 2015-10-09
    • 1970-01-01
    • 2018-01-03
    • 1970-01-01
    相关资源
    最近更新 更多