Is there a C++ function that helps to evaluate parentheses?
For ex开发者_StackOverflow中文版ample, 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.
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:
pair<int,int> findparens( const char* input )
{
int depth = 0;
int first;
for( const char* c = input; *c; ++c ) {
if (*c == '(' && !depth++) first = c - input;
else if (*c == ')' && !--depth) return make_pair(first, c - input);
}
throw depth;
}
You may want to consider using a lexer and parser generator to solve your problem.
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:
(a+b(c+d))(((d)(e+f)))
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.
精彩评论