Sign in to follow this  
tom_mai78101

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

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 this post


Link to post
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 interface
bool 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 this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this