I do parsing of the string in order to find wrapped sub-string inside brackets of the first level. a+(b+(d-g))+g+d, in this case I will need to separate (b+(d-g)). Below is the function which i use for such situations. This function is invoked when i find any opening bracket (. I did profiling of the program and unfortunately it is one of the slowest parts.
Could you please advise how I can optimise the code?
Input
"(b+(d-g))+g+d"
^ ^
| +--------iterator `end_` points to the end of the expression
+-------------iterator `tail_` points to beginning of the expression with brackets
Output
string with (b+(d-g))
side-effect
tail_ iterator
"(b+(d-g))+g+d"
^
|
+------iterator `tail_` points to the last correctly closed bracket.
Function
string get_between_brackets(string::iterator& tail_, const string::iterator& end_)
{
string brackets_content;
brackets_content.reserve(248); //cannot be longer than that
if(distance(tail_, end_) >= 2)
{
uint br_cnt = 0;
while(tail_ != end_)
{
const auto& chr = *tail_;
switch(chr)
{
case '(': ++br_cnt; break;
case ')': --br_cnt; break;
}
if(br_cnt >= 0)
brackets_content.push_back(chr);
if (br_cnt == 0)
break;
advance(tail_, 1);
}
} else throw std::invalid_argument("brackets tail is not long enough");
return(brackets_content);
}
"(a+b)*(c+d)"output? \$\endgroup\$(a+b)and(c+d)separately. To be more correct, it will receive(a+b)*(c+d)first, and stop before*, and then will receive(c+d)\$\endgroup\$shunting yard. \$\endgroup\$