string foo = "Some Mixed Case Text";
transform(foo.begin(), foo.end(), foo.begin(), tolower);
I thought the above code is portable.
But, the following page has a different view on this:
http://lists.debian.org/debian-gcc/2002/debian-gcc-200204/msg00092.html
Well that's a damn good question!
The problem is that most implementations of the standard C <ctype.h>
header define functions like toupper/tolower/etc as macros. To make it
work in STL algorithms, you have to include <cctype> header instead of
<ctype.h>. At least on my PC (Debian/gcc 3.3), <cctype> undefines all
tolower/etc macros and pulls ::tolower/::toupper/etc functions into
std namespace, so that your sample will work fine.
However, in general it is recommended to drop old C functions in favor
of new standard library functionality. In this particular case, you
may want use the ctype locale facet, i.e.
#include <locale>
// ..............
std::locale loc;
char s[] = "Test String";
std::use_facet< std::ctype<char> >( loc ).tolower( s, s + sizeof(s)
);
Too bad it does not work for std::string, i.e the following code will
not compile:
std::locale loc;
string s = "Test String";
std::use_facet< std::ctype<char> >( loc ).tolower( s.begin(),
s.end() );
because std::ctype::tolower() definition has only two variants:
char_type tolower(char_type __c) const;
const char_type* tolower(char_type* __lo, const char_type* __hi)
const;
This leads me to the following piece of code:
std::transform( s.begin(), s.end(), s.begin(),
std::bind1st( std::mem_fun( &std::ctype<char>::tolower ),
&std::use_facet< std::ctype<char> >( loc ) ) );
Nice, eh?
Now it's truly C++, but I am not sure if I want to use such thing
instead of good old tolower() from <cctype>. Can anyone suggest a
better solution?
PS. <locale> header also defines a standalone std::tolower() function
that takes locale as a second parameter, but I don't know if it can be
used in transform, because it is a template/inline function, i.e.
std::bind2nd and std:
tr_fun do not work with it.
PPS. It would be REALLY great to hear other opinions on this subject!
Thanks,
Sergei.