c++ - 特殊情况不返回的递归返回函数

标签 c++ recursion

我需要通过暴力破解给定的密码。所以我决定使用返回 string

的递归函数
string bruteforce(string password, string forcedPassword)
{
    if (password.length() == forcedPassword.length())
    {
        if (password == forcedPassword)
        {
            return forcedPassword;
        }
        // What can I do here to return nothing and continue from the previous step?
    }

    for (int j = 32; j <= 126; j++)
    {
        forcedPassword += char(j);
        bruteforce(password, forcedPassword);
    }
}

int main()
{
   ...
   cin >> password;
   cout << bruteforce(password, "");
   ...
}

问题是当我得到 password.length() == forcedPassword.length() 但它们不一样。我只需要在没有任何返回值的情况下退出递归的最后一步。有什么办法可以做到吗?

最佳答案

假设密码非空(否则使用optional),你可以这样写:

std::string bruteforce(const std::string& password, const std::string& forcedPassword)
{
    if (password.length() == forcedPassword.length())
    {
        if (password == forcedPassword)
        {
            return forcedPassword;
        }
        return "";
    }

    for (int j = 32; j <= 126; j++)
    {
        auto res = bruteforce(password, forcedPassword + char(j));
        if (!res.empty()) {
            return res;
        }
    }
    return "";
}

关于c++ - 特殊情况不返回的递归返回函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48346951/

相关文章:

c++ - 检测基类分配给指向派生类的引用

c++ - GLSL 变换反馈返回数组与 vector

java - 递归检查

java - 错误处理中的递归?

c++ - C++ 中的 friend 和模板

C++ 在什么时候使用堆而不是栈才有意义?

for-loop - GO - 递归函数中的 switch 语句

sql-server - 为什么 Transact-SQL 中的递归 CTE 需要 UNION ALL 而不是 UNION?

python - 在元组上分配字符串

c++ - 为什么在 std::shared_ptr 实现中需要两个指向托管对象的原始指针?