r...@zedat.fu-berlin.de (Stefan Ram) writes:
> Distribution through any means other than regular usenet
>
> channels is forbidden. It is forbidden to publish this
>
> article in the world wide web. It is forbidden to change
>
> URIs of this article into links. It is forbidden to remove
>
> this notice or to transfer the body without this notice.
>X-No-Archive: Yes
>Archive: no
>X-No-Archive-Readme: "X-No-Archive" is only set, because this prevents some
>
> services to mirror the article via the web (HTTP). But Stefan Ram
>
> hereby allows to keep this article within a Usenet archive server
>
> with only NNTP access without any time limitation.
What is all this double-spaced scheisse?
> The second == is evaluated even if the first one was true.
> I'd use an »else« there.
>
>bool is_balanced( ::std::string const & s )
>{ auto top = s.size(); signed long long c{ 0 };
> for( int i = 0; i < top; ++i )
> { switch( s[ i ]){ case '(': ++c; break; case ')': --c; }
> if( c == LLONG_MAX || c == LLONG_MIN )
> throw ::std::overflow_error( "too many parentheses" );
> if( c < 0 )return 0; } return !c; }
>
> (untested). The optimizer might have accomplished this before,
> but not we can be sure that »s.size()« is only evaluated once
> and »s[ i ]« is only evaluated once per loop.
>
> Use
s.at( i ) for an additional layer of security.
>
> Or using a pointer:
>
>bool is_balanced( ::std::string const & s )
>{ auto top = s.size(); signed long long c{ 0 };
> char const * b = s.c_str(); char const * e = b + top;
> for( char const * p = b; p < e; ++p )
> { switch( *p ){ '(': ++c; break; ')': --c; }
> if( c == LLONG_MAX || c == LLONG_MIN )
> throw ::std::overflow_error( "too many parentheses" );
> if( c < 0 )return 0; } return !c; }
>
> (untested). But this pointer style might be too low-level in C++.
>
> Maybe it should be a template?
>
>templace< typename C, typename T, typename A >
>bool is_balanced( ::std::basic_string< C, T, A >const & s )
>...
>
> (untested). Maybe it should be preceded by »constexpr«?
>
This is far more readable, yet untested.
bool balanced(std::string &str, char open = '(');
/**
* Return true if the enclosing characters are
* balanced.
*
* @note: A character will be considered regardless of
* whether or not it is quoted (with ', ", \, », or «).
*
* @param str A reference to the string to analyze
* @param open The opening character (one of '(', '[', or '{')
* @returns true if the character represented by 'open' is balanced.
*/
bool balanced(std::string &str, char open)
{
char closed = (open == '(')?open+1:open+2;
size_t count = 0ul;
if ((open != '(') && (open != '[') && (open != '{')) return false;
for(auto i: str) {
if (i == open) count++, continue;
if (i == closed) {
if (count == 0) return false;
--count;
}
}
return count == 0;
}
On an EBCDIC system:
uint8_t closed = (open == '[')?open+1:open+16;