GCC 下 tranform 调用 toupper, tolower 出错原因及解决

来源:互联网 发布:下载淘宝软件并安装 编辑:程序博客网 时间:2024/06/01 08:55

    今天用 transform 将一个字符串进行大小写转换时,意外发现 GCC 下竟然会报错,之前在 VS2013 一直可以用,即如下代码:

#include <iostream>#include <algorithm>using namespace std;int main(){    string str = "heLLo";    transform(str.begin(), str.end(), str.begin(), toupper);    cout << str << endl;    transform(str.begin(), str.end(), str.begin(), tolower);    cout << str << endl;    return 0;}

    没错,就是这么一段简单的代码,GCC 竟然报错

error: no matching function for call to 'transform(std::basic_string<char>::iterator, std::basic_string<char>::iterator, std::basic_string<char>::iterator, <unresolved overloaded function type>)'|

    后来网上查资料得知,貌似 GCC 的 toupper, tolower 是宏而非函数(本人未考证),这里仅给出解决办法:

#include <iostream>#include <algorithm>using namespace std;int main(){    string str = "heLLo";    transform(str.begin(), str.end(), str.begin(), (int (*)(int))toupper);    cout << str << endl;    transform(str.begin(), str.end(), str.begin(), (int (*)(int))tolower);    cout << str << endl;    return 0;}

    即将 toupper, tolower 转化为一个返回值为 int, 参数为 int 的函数指针,该问题即可解决。

0 0