Soumen wrote:
I wanted convert a mixed case string to a lower case one. And I tried
following code:
std::transform(mixedCaseString.begin(), mixedCaseString::end(),
mixedCaseString.begin(), std::ptr_fun(tolower));
Even though I's including cctype and algorithm, I's getting compiler
(g ++ 3.3.6) error:
no matching function for call to `ptr_fun(<unknown type>)'
I could resolve this only by using "::tolower" instead of "tolower".
But then I started googling. And it looks to me
this is not safe. And got confused with many types of responses on
similar topic.
Can someone point me what's the **safe (portable), less-cumbersome**
way to change case of an std::string
using std::transform or any other algorithm? Using boost is also
acceptable (but I've not used boost much other
than using shared_ptr and polymorphic_cast) to me.
Slightly modified from the archive:
#include <tr1/memory>
#include <cstdlib>
#include <locale>
template < typename CharT >
class to_lower {
typedef std::ctype< CharT > char_type;
std::tr1::shared_ptr< std::locale > the_loc_ptr;
char_type const * ? ? ? ? ? ? ? ? ? the_type_ptr;
public:
to_lower ( std::locale const & r_loc = std::locale() )
: the_loc_ptr ( new std::locale ( r_loc ) )
, the_type_ptr ( &std::use_facet< char_type >( *the_loc_ptr ) )
{}
CharT operator() ( CharT chr ) const {
return ( the_type_ptr->tolower( chr ) );
}
};
This is to be used with std::transform like so:
std::transform( mixedCaseString.begin(), mixedCaseString::end(),
mixedCaseString.begin(),
to_lower<char>() );
You could also initialize to_lower from a different locale.
Best
Kai-Uwe Bux
Thanks. Could you please explain a bit about the functor class? I'm
not able to follow std::use_facet and std::locale part.