我该如何将这段C++代码现代化
How can I modernify this piece of C++ code?
我有一个算法,它是我正在编写的数学方程解析函数的一部分。它位于当前字符(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
的一个实例,或者其他一些(更具体的)类。此修改将允许您优雅地捕捉异常。阅读有关异常的更多信息。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 代码在main()中运行,但在函数中出现错误
- 在VS代码中交叉编译Windows与Linux上的MinGW的SDL程序
- 编译包含字符串的代码时遇到问题
- 我在c++代码中生成了一个运行时#3异常
- 如何在linux终端中同时编译和运行c++代码
- 为cl.exe(Visual Studio代码)指定命令行C++版本
- 在Linux for Windows上编译C++代码时出错
- 我的字符计数代码计算错误.为什么
- 孤立代码块在结构中引发异常
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- 此代码是否违反一个定义规则
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 使用动态分配的数组会导致代码分析发出虚假的C6386缓冲区溢出警告
- 为什么在这个代码结束循环中没有得到结束
- 在c代码之间共享数据的最佳方式
- 这个指针和内存代码打印是什么?我不知道是打印垃圾还是如何打印我需要的值