Selasa, April 10, 2007

Weird GNU C++

While programming in C++, I need to transform a string into lower case. I search how to do it, and found a STL algorithm transform:

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
using namespace std;
int main() {
  //create a string
  string s("Some STRING with MiXed cASE");
  cout << "original: " << s << endl;
  //lowercase all characters
  transform (s.begin(), s.end(),    //source
             s.begin(),             //destination
             tolower);              //operation
  cout << "lowered: " << s << endl;
  //uppercase all characters
  transform (s.begin(), s.end(),    //source
             s.begin(),             //destination
             toupper);              //operation
  cout << "uppered: " << s << endl;
}


However, when I compile it, I got this error message:
error: no matching function for call to 'transform(__gnu_cxx::__normal_iterator<char*,>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*,>, std::allocator<char> > >, __gnu_cxx::__normal_iterator<char*,>, std::allocator<char> > >, <unresolved>)'


After googling for it, I've found a tricky solution here. Just made a new function:
char to_lower (const char c) { return tolower(c); }


Then change the transform function calling into:
  //lowercase all characters
  transform (s.begin(), s.end(),    //source
             s.begin(),             //destination
             to_lower);             //operation
  cout << "lowered: " << s << endl;


It's now compiled with error free, and running as expected. Weird isn't it??

Update : I've found another link explaining this phenomena here.
Rewriting the transform calling into this works too.
  //lowercase all characters
  transform (s.begin(), s.end(),    //source
             s.begin(),             //destination
             (int(*)(int))std::tolower);             //operation
  cout << "lowered: " << s << endl;

1 komentar:

Anonim mengatakan...

Yeah, I always use transform( s.begin(), s.end(), s.begin(), ::tolower ) ;
See also http://www.josuttis.com/libbook/new.html
cheers,
KB