有没有 C++有助于评估括号的函数?
例如,如果输入是“(A + (BC))(表达式中没有 giggity (this text))”,则它将返回 (0, 9),因为第一个括号位于 0 上,第二个括号位于9 号?
如果没有,请告诉我如何构造一个以字符串作为参数的函数,以便我可以自己完成。
For example, if the input is "(A + (BC)) (giggity (this text) isn't in the expression)", it would return (0, 9), because the first parenthesis is on 0 and the second is on 9?
If not, please tell me how to construct a function that takes a string as its arguments so I can do it myself.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
匹配的括号通常使用堆栈找到:从左到右遍历字符串,当找到左括号时,将当前位置推入堆栈,当找到右括号时,从堆栈中弹出值。弹出的值将是匹配左括号的位置。
Matching parentheses are usually found using stack: traverse string left ro right, when you find opening one, you push current position to the stack, when you find closing one - you pop value from the stack. Popped value will be the position of matching opening parenthesis.
标准库中没有内置函数可以做到这一点,但它很容易编写:
There is no function built into the standard library that does that, but it's really easy to write:
您可能需要考虑使用 词法分析器 和 解析器生成器 来解决您的问题。
You may want to consider using a lexer and parser generator to solve your problem.
我不会告诉您如何构造这样的函数,因为我认为您想要做的是评估这些函数,从而创建一个解析器,并且只知道位置是错误的。
例如,考虑一下:
知道位置如何帮助您解析该表达式?
正如 n0rd 刚刚发布的那样,您需要一台堆栈机来执行此操作。将 FILO(先进后出)模型考虑为括号的求值顺序......从内到外。
I'm not going to tell you how to construct such a function because I think what you want to do is evaluate those, and hence create a parser, and just knowing the position is wrong.
For example, consider:
How does knowing the position help you parse that expression?
As n0rd has just posted, you want a stack machine to do this. Consider the FILO (First in, Last Out) model to the order of evaluation of the parentheses... inside out.