James Kanze
9/4/2008 9:42:00 AM
On Sep 4, 1:03 am, Sam <s...@email-scan.com> wrote:
> Darío writes:
> > On Sep 3, 2:21 pm, puzzlecracker <ironsel2...@gmail.com> wrote:
> >> What is the quickest way to check that the following:
> >> const line[127]; only contains whitespace, in which case to ignore it.
> >> something along these lines:
> >> isspacedLine(line);
> > bool isLineSpaced(const char line[127])
> > {
> > int i = 0;
> > for(; i<127 && line[i++] == ' '; );
> > return i==127;
> > }
> That's C, not C++.
Well, it's also C++, albeit not idiomatic or good C++.
> The C++ solution would be:
> #include <algorithm>
> #include <cctype>
The C++ solution would use <locale>, and not <cctype>:-). (With
subsequent changes in the code, of course.)
> #include <functional>
> #include <vector>
> bool isLineSpaced(const std::vector<char> &line)
> {
> return std::find_if(line.begin(), line.end(),
> std::not1(std::ptr_fun(isspace))) == line..end();
> }
Which is fine, except that it has undefined behavior. What you
probably meant was somthing like:
struct NotIsSpace
{
bool operator()( char ch ) const
{
return ! std::isspace(
static_cast< unsigned char >( ch ) ) ;
}
} ;
bool
isEmptyLine(
std::string const& line )
{
return std::find_if( line.begin(), line.end(), NotIsSpace() )
== line.end() ;
}
(You cannot call the version of isspace in <cctype> with a char
without risking undefined behavior.)
Still, a quick benchmark shows that something like:
myCtype.scan_not( std::ctype_base::space,
myData.data(),
myData.data() + myData.size() )
== myData.data() + myData.size() ;
, with myCtype initialized with "std::use_facet< std::ctype<
char > >( std::locale()" is roughly five times faster (at least
on one system: g++ 4.1 under Linux on an Intel). And it's
certainly more idiotic^H^H^Hmatic with regards to C++.
(FWIW, using a full regular expression was only about three
times slower than your solution. And is a lot more powerful.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orientée objet/
Beratung in objektorientierter Datenverarbeitung
9 place Sémard, 78210 St.-Cyr-l'École, France, +33 (0)1 30 23 00 34