c++ - 递归函数有 out_of_range 异常

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

给定一个包含 ASCII 码和相应数值的全局 vector list 以及一个字符串,例如 000.00-000.0.0.0,此函数接受一个输入 token strings 2-char or 3-char long 并将其替换为表示 0 到 184 之间数值的单个 ASCII 符号,然后返回不带分隔符的缩短字符串作为 out。此外,在给定 ASCII 符号的情况下(方向 1),它会转换回数字字符串并返回。

//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() 应该清除 temp 并将临时字符添加到输出字符串,因为 temp == 1char 然后它应该按原样从 vectorSearch() 返回。然后清除convertOntology()返回检查inputtemp == ""。但是,它永远不会在 vectorSearch() 的第一行中断,并且有一个

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

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

最佳答案

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

关于c++ - 递归函数有 out_of_range 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11672353/

相关文章:

c - 这个使用 RECURSION 删除给定数组中所有强数字的函数有什么错误?

c++ - 'if' 表达式后续变量声明

python - 修正牛顿差分插值法的递归python实现,在递归中获取部分返回值

c++ - std::map 是一个好的解决方案吗?

.net - 如何在 .net 框架内的方法上设置断点

visual-studio-2008 - 将 Qt 应用程序链接到 Google Breakpad 时出现 Unresolved 符号错误

visual-studio-2012 - 如何在不使用 VS2008 的情况下使用 Windows SDK 在 VS2012 中使用 v90 平台工具集进行构建?

python-3.x - 使用python递归返回列表列表

c++ - 多线程处理,同时保持部分顺序

c++ - {1, 2} 是一个值吗?如果是,它的类型是什么?如果不是,为什么可以将其分配给初始化列表?