我该如何将这段C++代码现代化

How can I modernify this piece of C++ code?

本文关键字:C++ 代码 现代化      更新时间:2023-10-16

我有一个算法,它是我正在编写的数学方程解析函数的一部分。它位于当前字符(c*it)已被确定为右向视差(的部分内,并且应该递增it,直到它找到闭合视差为止。

       /* Iterate until the current character is the closing paranthesis or is off the end of the equation string */
        std::string::const_iterator opi = it;
        ++it;
        for (int nrfp = 1; nrfp > 0 && it != offend; c = *++it)
        {
            if (c == ')') --nrfp;
            else if (c == '(') ++nrfp;
        }
        if (it == offend) throw "Unbalanced parantheses";
        /* If we're here, the current character is the closing paranthesis, meaning the characters in the range (opi, it) are the inside of the paranthesis */
        /* Check that the paranthesis are not empty */
        if ((it - opi) == 1) throw "Empty paranthesis";

作为参考,opi的意思应该是"打开并行迭代器",nrfp的意思是"右向并行迭代数",而offend是我正在迭代的字符串的end()的迭代器。

我如何在可读性、性能和现代性方面提高这一点,而不在三者之间做出任何妥协?有没有一个我应该利用的标准库算法?

我认为您唯一需要做的就是:不要抛出字符串文字。相反,抛出(最终)从std::exception派生的异常类的对象。

例如。替换此:

 if (it == offend) throw "Unbalanced parantheses";

带有

 if (it == offend) throw std::runtime_error("Unbalanced parantheses");

或者std::logic_error的一个实例,或者其他一些(更具体的)类。此修改将允许您优雅地捕捉异常。阅读有关异常的更多信息。