# Std::string and iterator: Trying to get a second std::String out from iterator.

This topic is 2753 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I'm scanning a string ending with an equal sign, if it contains parentheses, use a recursive function to do mathematics within that parenthese, then break out of the recursive function until the string iterator reaches the end.

The code:
bool Parenthese (std::string &ptr){  std::string::iterator left = ptr.begin();  while (left <= ptr.end() - 1)  {    if (*left == '(')    {      Parenthese (    /* THIS PLACE */ );      break;    }    left++;  }  std::string::iterator right = left;  while (*right != ')')  {    //Code snipped, as it doesn't matter with this problem.  }  //The rest of the code is merely pure mathematics.}

The commented "THIS PLACE" is the place where I can't seem to use my iterator and convert it to string. What should I do? What else can I do in order for me to pass a std::string argument from an iterator? Do I have no other choice but to rewrite the whole code, and don't use std::string and its iterator? Thanks in advance.

##### Share on other sites
One option is to rewrite the code in terms of two iterators. This is more efficient as you don't need to make a copy of the substring during recursion. It is also easier to use some standard algorithms with the iterators.
typedef std::string::const_iterator StringIt;bool Parentheses(StringIt begin, StringIt end){    // Example of using stuff from #include <algorithm>    StringIt left = std::find(begin, end, '(');    StringIt right = std::find(begin, end, ')');    // ...}// Keep an easy to use interfacebool Parentheses(const std::string &string){   return Parentheses(string.begin(), string.end());}

Alternatively, you can keep your code using strings and build a substring by using the constructor that takes a pair of InputIterators. The iterator types of a std::string can be used as an InputIterator to this function:
bool Parenthese (std::string &ptr){  std::string::iterator left = ptr.begin();  while (left <= ptr.end() - 1)  {    if (*left == '(')    {      std::string string( /* left + 1 */, /* ptr.end() ? */);      Parenthese(string);      break;    }    left++;  }  std::string::iterator right = left;  while (*right != ')')  {    //Code snipped, as it doesn't matter with this problem.  }  //The rest of the code is merely pure mathematics.}

##### Share on other sites
Thank you. I have implemented the code above, but I realized it wouldn't work out well enough if the math problem have nested parentheses.

Nonetheless, the main problem is solved. :D

##### Share on other sites
... You really should look up proper tools for parsing. In general, this is not a trivial task.

• 11
• 20
• 12
• 10
• 35
• ### Forum Statistics

• Total Topics
631399
• Total Posts
2999857
×